Joao
Joao

Reputation: 21

User input only numbers, not text in Java

I am working on a recipe manager project in Java where I have the user input: name of the ingredient, calories per cup of the ingredient, cups of the ingredient, and finally the program will then calculate the total of calories total.

My issue is that if a user inputs a letter or symbol, then the program crashes. I would like to know how I can fix that. Any help would be great!

Here is my code:

public static void main(String[] args) {
   String nameOfIngredient = "";
   float numberCups = 0;
   int numberCaloriesPerCup = 0;
   double totalCalories = 0.0;

   Scanner scnr = new Scanner(System.in);

   System.out.println("Please enter the name of the ingredient: ");
   nameOfIngredient = scnr.next();

   System.out.println("Please enter the number of cups of " + nameOfIngredient + " we'll need: ");
   numberCups = scnr.nextFloat();


   System.out.println("Please enter the name of calories per cup: ");
   numberCaloriesPerCup = scnr.nextInt();

   totalCalories = numberCups * numberCaloriesPerCup;

   System.out.println(nameOfIngredient + " uses " + numberCups + " cups and has " + totalCalories + " calories.");

}

}

Thanks, everyone!

Upvotes: 2

Views: 2808

Answers (4)

Alexander van Oostenrijk
Alexander van Oostenrijk

Reputation: 4754

Though your program works for valid inputs, you can make it robust by checking for invalid ones like non-numbers where a number is expected. Your program crashes for a reason: when a user inputs a string, not a number, in this line:

numberCups = scnr.nextFloat();

... then the method nextFloat() will raise an exception, a NumberFormatException to be precise. The Java interpreter cannot handle this exception - it doesn't know what to do when this (valid) situation arises. There is something you can do about that:

do {
  bool validInput = true;
  try {
    numberCups = scnr.nextFloat();
  }
  catch(NumberFormatException ex) {
    validInput = false;
    System.out.println("Please enter a number.");
  }
} while(!validInput);

Now, Java will try to execute nextFloat, and if it fails with a NumberFormatException, it executes the catch block. This gives you a chance to tell the user that their input was wrong. I've put everything in a loop so that when the exception arises, the loop simply runs again until a valid number is input. Note that if the exception does not arise, then the catch block is never executed.

It is good practice to wrap code where an expected error may occur in such a try block in order to handle the situation without unnecessarily crashing the program. Note that there are many types of Exceptions. You should catch the one you expect may happen.

Upvotes: 3

Adithya
Adithya

Reputation: 257

The best you could do is as @ayrton said, use scnr.nextLine() instead of next() or nextFloat(). you can always use the Integer.parseInt() method from Integer class to convert the string into a Number.

Hope this helps.

Upvotes: 0

Devzone
Devzone

Reputation: 73

Ref : Only allow input of integers with java scanner

 boolean testing = false;
 String pos = "";
 while(true)
 {
 testing = false;   
 Scanner sc = new Scanner(System.in);
 System.out.println("Enter the integer value.... ");
 pos = sc.next();
 for(int i=0; i<pos.length();i++)
 {
     if(!Character.isDigit(pos.charAt(i)))
         testing = true;
 }
 if(testing == true)
 {
     System.out.print("Enter only numbers..   ");
     continue;
 }

 else
 {
     int key = Integer.parseInt(pos);
     // Your code here....
     break;
 }

Upvotes: 2

Ayrton
Ayrton

Reputation: 2303

You could change nextFloat() and nextInt() for nextLine(), then try to convert them to Integer or Float inside a try-catch block using Integer.parseInt() and Float.parseFloat().

Upvotes: 1

Related Questions