Hi Guys and Gals,

I am new to programming and I decided to write my self a simple class to help me with my uni work. It is just to save me writing to screen then using the scanner class to read the input. It would be easier with a one line of code and a class.

anInt = PromptGetInput.typeInt("Please enter the first int: ");

Basically I call the class with the desired method (that related to the data type that i would like to read in from the keyboard). I pass in a string as an argument and the method displays the string to the screen and then reads in the relative data type from the scanner class. The input is then returned. Not rocket science I know.. but hey I am learning and nothing like growing my knowledge of java over the weekend.

Something I have not learned yet at Uni is error checking/handling. So I decided I would go out on a mission to learn about this to add this to my class. My class is almost there, but I am stuck on something and I am hoping someone can point me in the right direction. I cannot seam to find what I want in the SDK.

Now the below code of mine is not the class I was talking about, as I thought I would try it in another program that they had me write (basic i know) (I am using this as it is already written and I dont want to write a main to test my class). But the problem is expressed in the same way.

The issue is that I want to be able to catch if the input is valid for an int data type. BUT I also want to have it loop around continually until it gets the correct input. So if you see the current code with the dowhile loop it is not working, well it works.. but I want to compact these two lines into 1 line -

validInput = keyboard.hasNextInt();
a = keyboard.nextInt();

The only other thing I can currently think of is removing the validInput = keyboard.hasNextInt(); and putting the data range of an int in the dowhile which would work,.. but it is a pretty savage way to get the result I want.. So guys how do I get some boolean input about whether it is an integer that has been input? As all the examples I have seen online use data ranges in the dowhile (eg like a percentage with - while ((a > 0) && (a <= 100)).

Ok I think I have communicated this clearly.. Thanks again for your help in advance.

Here is a snippet of the code.

Scanner keyboard = new Scanner (System.in);

	int a = -1;
        int counter = 0;
        double tally = 0.0;
        int largeNum = 0;
        int smallNum = 0;
        double average = 0.0;
        boolean validInput = false;

		while (a != 0)
        {
			//an infinite loop, use Ctrl-C to quit

            System.out.println("The program will continually take in integers.");
            System.out.println("Press Ctrl-C to quit, then the program will display, ");
            System.out.println("the total, average, the largest and smallest input numbers.");

            do
            {
                try
                {
                    System.out.println("Enter your number: ");
                    validInput = keyboard.hasNextInt();
                    a = keyboard.nextInt();
                   

                }

                catch (InputMismatchException e)
                {
                    System.out.println("Must enter an integer!");
                    keyboard.next();   // discard the bad input
                }

            }while(!validInput);

Recommended Answers

All 2 Replies

I haven't used scanner a lot, but I think that error handling is built in. Below is an example of prompting for 10 integers. If invalid data is entered it prompts again. If "quit" is entered, the program exits.

Scanner input = new Scanner(System.in);

    int x=0;
    while (x<10)
    {

      //prompt for integer
      System.out.print("Enter a number[" + x + "]: ");
      if (input.hasNextInt())
      {
        userData=input.nextInt ();//input next integer
      }
      else if(input.hasNext("quit"))
      {
          System.out.println("Exiting.");
          break;
      }
      else
      {
          //don't do anything with the invalid data;
          // read it and trash it
          input.next();
          System.out.print("Invalid data entered. Enter only integers ");
          System.out.println("(-999,999,999 < x < 999,999,999).");

          //go to next iteration of loop; skipping everything below
          continue;
      }

     

     // enter the rest of your code here

     x = x+1;

}
//close scanner
input.close();

I fixed it as below. But thanks for your reply.. it also presented another way for me to error check..

Thanks again.. Nate

do
            {
                try
                {
                    System.out.println("Enter your number: ");
                    a = keyboard.nextInt();
                    validInput = true;
                }
                catch (InputMismatchException e)
                {
                    System.out.println("Must enter an integer!");
                    keyboard.next();   // discard the bad input
                    validInput = false;
                }

            }while(!validInput);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.