public static void main(String [] args) {
Scanner input = new Scanner(System.in);
double dblNumber, dblSquare, dblSqrt;
String answer;
String answery = "yes";
String answern = "no";
while (true) {
System.out.println( "Welcome to Squarez! Where we do the math for you.\nPlease input a number you would like us to do some math with.");
dblNumber = input.nextDouble();
dblSqrt = Math.sqrt(dblNumber);
dblSquare = Math.pow(dblNumber, 3);
System.out.println("" + dblSquare + " " + dblSqrt);
System.out.println("Would you like to continue?");
answer = input.nextLine();
if (answer.equals(answery)) {
System.out.println("You answered yes");
}
if (answer.equals(answern)) {
System.out.println("You answered no.");
System.exit(0);
}
}
}
程序运行并完全忽略询问用户是否要继续的提示。它直接回到第一个数字的提示。为什么要跳过这个?
答案 0 :(得分:3)
你必须在双倍后使用换行符:
System.out.println("Would you like to continue?");
input.nextLine(); // <-- consumes the last line break
answer = input.nextLine(); // <-- consumes your answer (yes/no)
答案 1 :(得分:1)
您使用声明
读取数字dblNumber = input.nextDouble();
虽然此行会阻塞,直到用户输入整行(包括换行符),但只解析没有换行符的字符并将其作为double返回。
这意味着,换行符仍在等待从扫描仪中检索到!这条线
answer = input.nextLine();
直接就是这样。它使用换行符,用变量answer
提供空字符串。
那么,解决方案是什么?使用始终input.nextLine()
来读取用户输入,然后根据需要解析生成的字符串:
String line = input.nextLine();
dblNumber = Double.parseDouble(line);
答案 2 :(得分:0)
它应该如何:
String answer;
String answery = "yes";
String answern = "no";
System.out.println("Would you like to continue?");
input.nextLine();
answer = input.nextLine();
你只需做出两个决定即可做出&#34;是&#34;或者&#34;没有&#34;,我真的不明白为什么你使用2 if语句;虽然你刚刚为答案的“是”部分做了这个,而相反的部分却是“否”。
if(answer.equals(answery))
{
System.out.println("You answered yes");
}
else
System.out.println("You answered no.");
System.exit(0);