我的教授被派去写一个素数“finder”。如果输入的数字是素数或偶数,则显示该数字,然后显示下一个素数。他希望我们在输入错误的输入时给出错误信息。我认为负整数部分很简单,但我无法弄清楚字符输入。或者如果角色不是数字。我将如何阻止非数字输入?如何拒绝非数字字符的输入?
此外,系统应该在三个连续的错误输入中退出。我将如何重置柜台?我编写程序的方式,如果用户犯了两个错误,但接下来的错误是可以接受的,那么就犯另一个错误。 (因此不是连续的)。程序关闭。 这是我第一次编程课程,所以我不会理解它。任何帮助将不胜感激。
此外,我必须使用扫描仪和两种方法。
/**
*
* @param n
* @return
*/
public static boolean isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static int nextPrime(int n) {
n++;
isPrime(n);
while (isPrime(n) == false) {
n++;
isPrime(n);
}
int prime = n;
return prime;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int answer = 2;
int counter = 1;
boolean playAgain = false;
Scanner input = new Scanner(System.in);
Scanner reader = new Scanner(System.in);
Scanner in = new Scanner(System.in);
do {
//ask for input
System.out.print("\nEnter the integer value-> ");
//input answer
int n = input.nextInt();
{
//decide is negative
while (n < 0){
//count counter
counter++;
//give error message
System.out.println("\nInvalid Input! Stike!");
//ask for input
System.out.print("\nEnter the integer value-> ");
//input answer
n = input.nextInt();
//decide is character
// if (n != '.'){
//count counter
// counter++;
//give error message
// System.out.println("\nInvalid Input! Strike!");
// }
//decide if count three errors
if (counter == 3){
//display three errors message
System.out.println("Three Strikes! You're Out!");
//close program
System.exit(0);
}
}
//decide if prime
if (isPrime(n)) {
//display prime answer
System.out.println(n + " Is Prime");
//decide if even
} else {
//display even answer
System.out.println(n + " Is Even");
}
//counter input
n++;
//while input is false
while (isPrime(n) == false) {
n++;
}
//display next prime
System.out.println(n + " Next prime");
{
//ask if you want to continue
System.out.println("\nPlay Again?\n\nEnter 1)Yes or 2)No ");
//input answer
answer = in.nextInt();
//if answer is 1)yes
if (answer == 1) {
playAgain = true;
//display play again and next input
System.out.println("\nPlay Again!");
}
//if answer is no
if (answer == 2) {
playAgain = false;
System.out.println("\nGoodbye!");
//close program
System.exit(0);
}
}
}
} while (playAgain != false);
}
}
我同意,简单的研究应该给你这个问题的答案。 – DreadHeadedDeveloper 2014-10-06 01:56:43