0 java loops calculator while-loop
package pack;
import java.util.Scanner;
public class Calculator {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
String cont = "Yes";
while(cont == "Yes" || cont == "yes" ){
System.out.print("Enter a Number: ");
int x = scan.nextInt();
System.out.print("Enter another Number: ");
int y = scan.nextInt();
int diff = x - y;
int sum = x + y;
int prod = x * y;
int quot = x / y;
System.out.println("The Sum is: " + sum);
System.out.println("The Diffrence is: " + diff);
System.out.println("The Product is: " + prod);
System.out.println("The quotient is: " + quot);
System.out.print("Enter Yes to Continue: ");
cont = scan.next();
System.out.println(cont);
}
}
}
Run Code Online (Sandbox Code Playgroud)
整个代码都有效,但while循环不重复.在cont = scan.next();被抓的字符串.输出如下所示:
[
Enter a Number: 5
Enter another Number: 6
The Sum is: 11
The Diffrence is: -1
The Product is: 30
The quotient is: 0
Enter Yes to Continue: Yes
Yes
]
Run Code Online (Sandbox Code Playgroud)
然后程序终止没有任何问题.所有我需要它来重复while循环.谢谢您的帮助!
比较字符串.equals而不是==
while(cont.equals("Yes") || cont.equals("yes") )
Run Code Online (Sandbox Code Playgroud)
甚至更好:
while(cont.equalsIgnoreCase("Yes"))
Run Code Online (Sandbox Code Playgroud)