im正在编写一个比较两个int的程序,我希望该程序一直运行到用户感到厌倦并想退出为止,为此用户将输入q退出。我想写一个while循环,比较两个字符,一个是用户输入的,另一个是分配给它的"q"。然而,当我输入q时,我的程序崩溃了,为什么是这样,我如何修复
import java.io.IOException;
import java.util.Scanner;
public class numComp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a, b;
char key = 'q';
System.out.println("enter 'q' to quit program and any other key to start it");
char btn = 0;
try {
btn = (char) System.in.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (btn != key){
System.out.println("enter two numbers to compare them");
System.out.println("please enter first number:");
a = in.nextInt();
System.out.println("please enter second number:");
b = in.nextInt();
if (a==b)
System.out.println("the numbers you entered are the same");
else if (a>b)
System.out.println("your first number is greater then your second number by "+ (a-b));
else
System.out.println("your first number is smaller then your second number by "+ (b-a));
}
}
}
这是因为在while循环中,您扫描的是整数,但"q"是一个字符。您需要让用户有机会在while循环中读取btn
。
您的循环应该是这样的:
try{
btn = (char) System.in.read();
while (btn != key){
System.out.println("enter two numbers to compare them");
System.out.println("please enter first number:");
a = in.nextInt();
System.out.println("please enter second number:");
b = in.nextInt();
if (a==b)
System.out.println("the numbers you entered are the same");
else if (a>b)
System.out.println("your first number is greater then your second number by "+ (a-b));
else
System.out.println("your first number is smaller then your second number by "+ (b-a));
System.out.println("enter 'q' to quit program and any other key to start it again");
btn = (char) System.in.read();
} // END OF WHILE LOOP
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
还要注意,您需要在while
循环结束之前再次从用户那里获得输入。
检查时需要更改btn
。在循环之前只设置一次,并且永远不会在中更新
例外情况是因为
a = in.nextInt();
当您输入char
时,您尝试读取int
。
您需要在循环的末尾添加以下内容:
btn = (char) System.in.read();
这是一个简化的程序。
public static void main(String[] args){
// Scanner
Scanner s = new Scanner(System.in);
// Enter the program
System.out.println("enter 'q' to quit program and any other key to start it");
int a, b;
try {
char key;
while ((key = s.next().charAt(0))!='q'){
System.out.println("enter two numbers to compare them");
System.out.println("please enter first number:");
a = s.nextInt();
System.out.println("please enter second number:");
b = s.nextInt();
if (a==b)
System.out.println("the numbers you entered are the same");
else if (a>b)
System.out.println("your first number is greater then your second number by "+ (a-b));
else
System.out.println("your first number is smaller then your second number by "+ (b-a));
}
} catch (Exception e){ e.printStackTrace(); }
}