在以下代码中,即使我在同一个for循环中初始化number
,也无法在行number++
中找到变量number
。谁能告诉我为什么?
import java.lang.Math;
import java.util.Random;
public class test
{
public static void main( String [] args )
{
String cardNumber;
double cardRandom;
int cardRandomNumber;
String[] cardSelection = new String[10];
for (int number = 0; number <= 9; );
{
Random ran = new Random();
cardRandom = ran.nextInt(52 - 1 + 1) + 1;
cardRandomNumber = (int) Math.round( cardRandom );
if ( cardRandomNumber > 0 && cardRandomNumber <= 52 )
{
cardNumber = "card" + cardRandomNumber;
System.out.println( cardNumber );
number++; // Says Error: Cannot find symbol
}
}
}
}
这个程序基本上只是从1-52中选择一个随机数,在它的开头添加“卡片”并打印出来。它应该打印出10个数字。
答案 0 :(得分:8)
以下行中的最后一个分号必须消失:
for (int number = 0; number <= 9; );
你基本上声明一个没有正文的for
循环。好IDE应该警告你这些错误。 BTW递增循环计数器应该转到我们都期望它的最后for
表达式:
for (int number = 0; number <= 9; ++number) {
//..
}
BTW在消除了不必要的变量和条件后,您的代码如下所示:
public static void main(String[] args) {
Random r = new Random();
for (int number = 0; number <= 9; ++number) {
int cardRandom = 1 + r.nextInt(52);
String cardNumber = "card" + cardRandom;
System.out.println(cardNumber);
}
}
严重。
答案 1 :(得分:2)
您无意中终止了带有分号的for
循环:
for (int number = 0; number <= 9; );
这相当于:
for (int number = 0; number <= 9; )
{ ; }
{
Random ran = new Random();
cardRandom = ran.nextInt(52 - 1 + 1) + 1;
cardRandomNumber = (int) Math.round( cardRandom );
// etc. ...
因此,number
变量超出范围时会超出范围。
删除该分号。
答案 2 :(得分:1)
删除分号:
for (int number = 0; number <= 9; ); // <-- this is your problem
答案 3 :(得分:0)
import java.lang.Math;
import java.util.Random;
public class foo
{
public static void main( String [] args )
{
String cardNumber;
double cardRandom;
int cardRandomNumber;
String[] cardSelection = new String[10];
for (int number = 0; number <= 9; )
{
Random ran = new Random();
cardRandom = ran.nextInt(52 - 1 + 1) + 1;
cardRandomNumber = (int) Math.round( cardRandom );
if ( cardRandomNumber > 0 && cardRandomNumber <= 52 )
{
cardNumber = "card" + cardRandomNumber;
System.out.println( cardNumber );
}
number++;
}
}
}
输出是一组10项:(请注意,每次运行程序时,它都会提供不同的卡号)
卡2 card12 card37 card23 CARD18 card20 card21 card45 card19 card13