我将所有代码放入一个 do-while 语句中,这样它就会一直循环,直到用户输入 3 退出。出于某种原因,当我关闭 do 语句时,它看不到变量 userInput
。我试过改变很多东西,但没有一个奏效。所以问题出在 while (userInput !=3);
它抛出 userInput cannot be resolved to a variable
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
do {
Scanner in = new Scanner (System.in);
System.out.print("Please choose your choice from the following menu");
System.out.print("\n1) Print through all integer numbers between two given integers");
System.out.print("\n2) Display a right triangular pattern of stars");
System.out.println("\n3) Quit");
int userInput = in.nextInt();
if (userInput == 1) {
System.out.print("Enter the start number: ");
int firstInteger = in.nextInt();
System.out.print("Enter the second number: ");
int secondInteger = in.nextInt();
while (firstInteger <= secondInteger) {
System.out.print(firstInteger + " ");
firstInteger++;
}
}else if (userInput == 2) {
System.out.print("Enter the height: ");
int triangleHeight = in.nextInt();
}
} while (userInput != 3);
}
}
答案 0 :(得分:1)
userInput
必须在循环外声明,while
条件才能看到它。
试试这个:
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
int userInput;
do {
Scanner in = new Scanner(System.in);
System.out.print("Please choose your choice from the following menu");
System.out.print("\n1) Print through all integer numbers between two given integers");
System.out.print("\n2) Display a right triangular pattern of stars");
System.out.println("\n3) Quit");
userInput = in.nextInt();
if (userInput == 1) {
System.out.print("Enter the start number: ");
int firstInteger = in.nextInt();
System.out.print("Enter the second number: ");
int secondInteger = in.nextInt();
while (firstInteger <= secondInteger) {
System.out.print(firstInteger + " ");
firstInteger++;
}
} else if (userInput == 2) {
System.out.print("Enter the height: ");
int triangleHeight = in.nextInt();
}
} while (userInput != 3);
}
}
答案 1 :(得分:0)
userInput
定义在循环块内部,因此不能从外部访问它,包括循环的条件。一种解决方案是将声明移出其中:
int userInput = -1;
do {
// code...
userInput = in.nextInt();
// more code...
} while (userInput != 3);