循环中的Java“while”变量
抱歉,如果有人问这个问题(可能很多次),但我找不到答案。我正在学习Java,并编写了一个简单的代码。它需要两个数字,比较并使用If给出一些结果。它运行得很好,但我试着循环它。gram在循环中,而我给出的第一个数值是10。这不会像这样工作,因为“First无法解析为变量”,因为它位于循环中。好吧,我明白了,但有没有办法让这个循环中的变量起作用呢
import java.util.Scanner;
public class Loop {
public static void main(String[] args) {
do {
System.out.println("give me 2 numbers: ");
String FirstNum, SecNum;
Scanner FirstRead = new Scanner(System.in);
Scanner SecRead = new Scanner(System.in);
FirstNum = FirstRead.nextLine();
SecNum = SecRead.nextLine();
int First = Integer.parseInt(FirstNum); // changing String to int
int Second = Integer.parseInt(SecNum); // changing String to int
// Playing with loop
if (First == Second) {
System.out.println("First " + First + " is same as "+ Second);
}
else {
System.out.println("Number " + First + " is different then " + Second);
}
}
while(First == 10);
System.out.print("We're done here, because first number is 10");
}
}
# 1 楼答案
首先,请使用lowerCamelCase来命名变量。第一个字母总是小写的
不,不能在循环中声明变量并将其用作条件。使用变量时,需要知道定义变量的范围。如果在循环内定义它,它将仅在循环内可用。因此,你唯一能做的就是在循环外定义变量,然后在循环内使用它
# 2 楼答案
你应该首先声明你的扫描仪在循环之外
你的while条款错了。如果在
first == 10
时循环,这意味着如果“first”不同于10,程序将退出# 3 楼答案
正如其他人所说,您必须在循环范围之外声明条件变量。您还可以对您的程序应用其他一些改进: