我的教授被派去寫一個素數「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