如何拒绝非数字字符的输入?

时间:2014-10-06 01:51:43

标签: java character counter

我的教授被指派写一个素数" 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);
}

}

2 个答案:

答案 0 :(得分:0)

您正尝试使用带有

的Scanner类进行输入
int n = input.nextInt();

如果您在此输入一个字符代替数字,您将获得 java.util.InputMismatchException

你能做的就是

try {
    int n = input.nextInt();    
} catch (InputMismatchException e) {
    //handle the error scenario where the input is a character
    System.out.println("Enter Valid Input");
}

答案 1 :(得分:0)

import java.util.Scanner;

public class SOQ5B
{

   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;
      int counter = 0;
      int n;

      boolean playAgain = true;
      boolean isNum;
      boolean isNum2;
      boolean continuePermitted = true;

      Scanner input = new Scanner(System.in);

      String s;

      do {
        //ask for input
         System.out.print("\nEnter the integer value-> ");

         s = input.nextLine();


         isNum = true;

         for(int i = 0; i < s.length(); i++)
         {

            if(!(s.charAt(i) >= '0' && s.charAt(i) <= '9'))
            {

               isNum = false;

            }

         }

         if(isNum)
         {

            counter = 0;

            n = Integer.parseInt(s);

         //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");


            do
            {

               continuePermitted = true;

            //ask if you want to continue
               System.out.println("\nPlay Again?\n\nEnter 1)Yes or 2)No ");
            //input answer

               s = input.nextLine();

               isNum2 = true;

               for(int i = 0; i < s.length(); i++)
               {

                  if(!(s.charAt(i) >= '0' && s.charAt(i) <= '9'))
                  {

                     isNum2 = false;

                  }

               }


               if(isNum2)
               {

                  answer = Integer.parseInt(s);

               //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);
                  }

               }

               else
               {

                  System.out.println("Incorrect response.");
                  continuePermitted = false;

                  //if answering the yes or no question incorrectly is part of the 3 strikes
                  //then uncomment the following lines of code

                  /*
                  counter++;
                  }

                  if(counter >= 3)
                  {

                  System.out.println("3 strikes you out");
                  System.exit(0);
                  */

               }
            }while(!continuePermitted);


         }

         else
         {

            System.out.print("\nIncorrect input. Number must be a positive integer.\n");
            counter++;

         }

         if(counter>=3)
         {

            System.out.println("3 strikes and you're out!");
            System.exit(0);

         }




      } while (playAgain != false);
   }
}

将来,我建议您在提问之前在互联网上研究您的问题。还有其他几个地方可以很容易地回答你的问题。

现在关于你的实际问题,请注意我在s = input.nextLine()的行中如何更改代码?我在那里做的是检查字符串中的每个数字是否是0-9之间的任何数字。我不仅能够检查它们是否都是数字,而且我还能够看到它们是否都是正面的,因为你必须放一个 - 为了它是负面的。除此之外,您还有一个布尔值,只有在输入为正数时才有效。如果没有,它会检查3次,以确保您的程序不会搞砸。此外,我甚至评论了另一个允许3次罢工的部分,如果回答“是”则不包括罢工。如果还有其他问题,请询问,我会编辑我的答案。