程序的作用:从输入中读取两个值,询问用户是加、减还是求产品。如果用户输入三个选项之一,则计算,否则程序将循环回到开头。如果用户输入三个选项之一,程序应该在计算后停止。
我不确定为什么它一直在循环。仅当用户键入“sum”、“difference”或“product”以外的字符串时,如何使脚本循环?另外,我怎样才能使代码更简单?有没有办法在不使用 do ... while 的情况下循环程序?
import java.util.Scanner;
import java.util.Random;
public class simp_calculator
{
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
double a, b;
String response;
boolean noresponse;
do
{
System.out.println ("Please enter first number.");
a = scan.nextDouble();
System.out.println ("Please enter second number.");
b = scan.nextDouble();
System.out.println ("Would you like to find the sum, difference, product?");
response = scan.next();
if (response.equalsIgnoreCase ("sum"))
{
System.out.println (a + b);
}
if (response.equalsIgnoreCase ("difference"))
{
System.out.println (a - b);
}
if (response.equalsIgnoreCase ("product"))
{
System.out.println (a * b);
}
else
{
noresponse = true;
System.out.println ("Starting again...");
}
}
while (noresponse = true);
}
}