0

I have a program where i ask a user for numberOfCups for and ingredient, i want to make sure that the user input is of type int and only int how can i ensure they do so?

   String nameOfIngredient;
   double numberOfCups;
   int numberCaloriesPerCup;
   double totalCalories;
   
   Scanner scnr = new Scanner(System.in);
   
   System.out.println("Please enter the name of the ingredient: ");
   nameOfIngredient = scnr.nextLine(); // using nextLine incase ingredient is more than one word long
   
   
   System.out.println("Please enter the number of cups of " + nameOfIngredient + " we'll need: ");
   
   numberOfCups = scnr.nextDouble(); // this variable is defined as double but it was written as nextFloat so i changed it 
   
   System.out.println("Please enter the number of calories per cup: ");
   numberCaloriesPerCup = scnr.nextInt();
   
  
   totalCalories = numberOfCups * numberCaloriesPerCup ;
   System.out.println(nameOfIngredient + " uses " + numberOfCups + " cups and has " + totalCalories + " calories.");
   
}

}

ThatGuy
  • 1
  • 4
  • Please read [ask] and do research prior to asking. I found an [answer that shows how to validate](https://stackoverflow.com/questions/3059333/validating-input-using-java-util-scanner/3059367#3059367). – hc_dev Jan 17 '22 at 20:11
  • call toString() on it, if that fails, it's definitely not a String. But, keep in mind, if you have "125", it's a String, not an int. – Stultuske Jan 18 '22 at 07:10

1 Answers1

0

There are a couple of ways:

  1. You could pass the value into a regex for validation.
  2. You can attempt to parse the string into a value (Integer.parseInt(), Double.parseDouble()), wrap it the check into a try/catch block. If there's an exception, then you don't have a number.
Ryan
  • 1,666
  • 5
  • 11