即時通訊編寫一個程序,比較兩個整數,我希望程序運行,直到用戶厭倦,想要退出,這樣做,用戶將輸入q退出。我想寫一個while循環,比較兩個字符,一個是用戶輸入的,另一個字符是'q'分配給它。然而,當我輸入q我的程序擊碎這是爲什麼,我該如何解決一個for循環運行/停止程序
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));
}
}
}
而用戶應該在哪裏輸入'q'?導致我看到它的方式,你只允許輸入數字。 – 2013-02-17 10:21:35