该程序让用户输入一个数字并检查该数字是否为素数。但是,如果希望程序在用户输入“q”时退出。我已经尝试了几件事(做一会儿,如果),但似乎没有一种方法有效。这是如何引起的,我该如何解决?
下面是源代码:
// Test for primes 2
import java.io.*;
class FindPrime2 {
public static void main(String args[])
throws IOException {
// int num;
boolean isPrime;
String str;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("\nFINDING PRIME NUMBERS v0.1");
System.out.print("\nPlease enter a number: ");
str = br.readLine();
if(str == "q") System.exit(1);
int num = Integer.valueOf(str);
System.out.println("You have picked: " + num);
if(num < 2) isPrime = false;
else isPrime = true;
for(int i=2; i <= num/i; i++) {
if((num % i) == 0) {
isPrime = false;
break;
}
}
if(isPrime) System.out.println(num +" is Prime.");
else System.out.println(num + " is not Prime.");
}
}