java for循环打印,在java的for循环之外打印我的值

I am trying to print/get the value of loop variable i and use it in another method outside the for loop. How do I do that?

public void mousePressed() {

for (int i = 0; i < 1000; i++){

boxes[i].openIt();

}

}

解决方案

Variables declared in the for statement are in scope only in the for components and the following code block, see JLS section 14.14.1.1, in particular:

for ( ForInit ; Expression ; ForUpdate ) Statement

If the ForInit code is a local variable declaration, it is executed as

if it were a local variable declaration statement (§14.4) appearing in

a block.

If you want to have it available outside the for, you have to declare it in a scope that is active in the location you want to access it; e.g. just outside the for loop:

int i;

for (i = 0; i < 1000; ++ i)

;

// i is accessible in this scope

System.out.println(i);

Alternatively, if it is more appropriate, you could declare a separate variable and store the value of interest in it:

int k = ...;

for (int i = 0; i < 1000; ++ i)

if (condition) // for example

k = i;

// k is accessible in this scope, i is not

System.out.println(k);

For a brief summary see this page, specifically the Loop Scope example at the end, which has an example that is exactly like your question.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值