user3503794
user3503794

Reputation: 65

How do I take only integer inputs (with only scanner class and if and else statement or while loops if possible - no booleans)?

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.

Upvotes: 2

Views: 1166

Answers (2)

Ashraful Haque
Ashraful Haque

Reputation: 559

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

Upvotes: 1

CodeCamper
CodeCamper

Reputation: 6980

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.");
    }
}

Upvotes: 2

Related Questions