英文:
Do While loop terminates and doesn't execute scanner function
问题
以下是我的“Do-While”循环代码。我无法弄清楚为什么在甚至还没有输入变量“redo”的值之前,它就已经终止了,而这是在do {}部分的末尾。它在打印“您是否想再次执行此操作”的部分之后立即终止。
import java.util.Scanner;
public class AlgWorkbench0402 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String redo;
do {
System.out.println("输入两个整数并得到它们的和。");
int val1, val2;
val1 = Integer.valueOf(scanner.nextInt());
val2 = Integer.valueOf(scanner.nextInt());
System.out.println(val1 + val2);
System.out.println("您是否想再次执行此操作?[y/n]");
redo = scanner.nextLine();
}
while (redo.equals("y") || redo.equals("Y"));
}
}
英文:
Below is my code for a "Do-While" loop. I can't figure out why it's terminating before I even get to enter in the value for my variable "redo" at the end of the do {} section. It terminates right after printing the "would you like to do this again" part.
import java.util.Scanner;
public class AlgWorkbench0402 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String redo;
do {
System.out.println("Enter in two integers and get the sum.");
int val1, val2;
val1 = Integer.valueOf(scanner.nextInt());
val2 = Integer.valueOf(scanner.nextInt());
System.out.println(val1 + val2);
System.out.println("Would you like to do this again? [y/n]");
redo = scanner.nextLine();
}
while (redo == "y" || redo == "Y");
}
}
专注分享java语言的经验与见解,让所有开发者获益!
评论