2

Here is my code that I have so far:

import java.util.Scanner;
public class Whatever{
    public static void main(String[] args) {
    Scanner keyboard = new Scanner (System.in);
    System.out.println("How many pigs are there?");
    int number = Integer.parseInt( keyboard.nextLine() );
    int continueProgram = 0
    while(continueProgram == 0)
        {
            if (number>= 0 && number <= 32767)
            { do this;
                      continueProgram++;
            }else{
                     do this;
            }

I have to use integer.parseInt for the rest of my code to work so I can't change that. Any ways to take only integers rather than letters? My code produces errors because if I input a letter, parseInt will produce red errors rather than output a string like "try again. input numbers please" or something like that.

2
  • How can your program say "try again. input numbers please" or something like that. when you never even tried to tell it to do that? Commented Apr 13, 2014 at 20:15
  • beacuse parseInt stop the rest of the code for me to put that string in there for output. Commented Apr 13, 2014 at 20:15

2 Answers 2

2

You need to surround your parse.int with a try catch like this

int number = 0; // you need to initialize your variable first
while (true) {
    try {
    number = Integer.parseInt(keyboard.nextLine());
    break; // this will escape the while loop
    } catch (Exception e) {
    System.out.println("That is not a number. Try again.");
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

hmm actually my question is: if i input a letter, and the program goes to the catch method with a system.out.println method, how do i loop it back to "how many pigs are there?" step from my code?
@user3503794 I updated the code above for you just copy and paste it in and it will work.
Wow so fast. Thank you CodeCamper. I will try that.
@user3503794 Anymore errors? This code will loop just as you asked.
no more errors. I up voted you. Thank you very much.
1

Try this one :

 Scanner keyboard = new Scanner (System.in);
 System.out.println("How many pigs are there?");
 if(keyboard.hasNextInt()) {

   int number =  keyboard.nextInt();        

   }else{ 
        System.out.println("Not an integer number!");
        keyboard.next();
   }

3 Comments

oh ok. let me give this a try. Thank you for your input.
If u wanna loop it back then just use the while loop like the first answer,note that the input statement only works if the number is integer,So,I suppose this is what you are looking for.
Thanks for the help. I ll keep that in mind next time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.