我编写了一个程序来确定一个素数,并且需要使用“Q”作为退出函数才能退出程序。下面是我写的代码。我想知道如何修改退出程序的方法以使其正确退出。
import java.util.Scanner;
public class Practice
{
public static void main(String[]args)
{
Scanner keyboard = new Scanner(System.in);
int number, i=2;
String quit;
boolean prime = true;
System.out.println("Please enter a number to determine if it is prime, to quit please enter Q.");
number = keyboard.nextInt();
quit = keyboard.nextLine();
for (i=0; i<number;i++)
{
if ((number%2==0) || (number==1) || (number%3==0))
{
prime = false;
}
}
if (prime==false)
{
System.out.println(number+" is not a prime number.");
}
else if(prime==true)
System.out.println(number+" is a prime number.");
if (quit.charAt(0)=='Q')
{ System.exit(0);}
输入“Q”后我的输出是:
----jGRASP exec: java Practice
Please enter a number to determine if it is prime, to quit please enter Q.
Q
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Practice.main(Practice.java:15)
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
}
}