我是编程新手,所以认为我是一个很棒的新手.困境:我想在每次回答"是"时重复我的代码.我确实使用"do while循环",因为首先是一个语句,最后应该评估布尔条件.
代码:
import java.util.Scanner;
class whysoserious {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
do{
String go = YES;
int setone = 0;
int settwo = 0;
System.out.println("Enter two numbers: ");
setone = sc.nextInt();
settwo = sc.nextInt();
int set = setone + settwo;
System.out.println("What is " +setone+ " + " +settwo+ " ? ");
int putone = 0;
putone = sc.nextInt();
if (putone == set)
System.out.println("Correct!");
else
System.out.println("Wrong Answer - The correct answer is: "+set+"");
System.out.println("Continue?");
cont = sc.nextLine();
} while (cont == go);
}
}
Run Code Online (Sandbox Code Playgroud)
我被要求添加CMD提示行.
每次我尝试编译它时总是会出错.这背后的知识是我希望每次用户输入"是"或"否"时重复代码以继续.观察代码在没有do {的情况下工作.在这一点上,我坚持做的同时.
多个问题:
你永远不会声明cont
,YES
所以编译器不知道它们是什么
你go
在循环中声明,因此它超出了while
表达式中的范围
比较字符串==
并不能满足您的需要 - 您可能有两个不同的字符串具有相同的内容.请equals
改用.
来自编译器的错误消息应告诉您前两个 - 注意编译器所说的内容.
最简单的修复:添加String cont;
之前do
,摆脱go
并进行测试while ("YES".equals(cont));
如果用户输入"是"或"是"或"是"或其他一些变体,这仍然会退出.