How to loop through until user inputs a valid integer? - java

I'm new to java and am trying to validate numbers being entered into the console. I want an integer, but I know if a letter is entered for example an error would occur, so I thought I'd use try & catch. This works if try and do it first time round, but I want to loop through until the user inputs a valid integer. Got this working, but when I get a valid number and print out the number I get a list of all attempts.... Hope this makes sense
import java.util.Scanner;
public class ConvertStringInt {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i = 0;
System.out.print("Enter a whole number: ");
try {
i = sc.nextInt();
} catch (Exception e){
System.out.println("Error");
main(args);
}
System.out.println(i);
}
}
Here is the output from the console....
Enter a whole number: a
Error
Enter a whole number: d
Error
Enter a whole number: 2.0
Error Enter a whole number: 1
1
0
0
0
Could somebody please explain this?
Thanks in advance
Neil

You are seeing outputs for each input because you call main recursively. If you immediately type a correct int, the flow is this:
main
ask for input -> int
print i (1)
But in your case the input is not an int. This is what happens: you type the first input, it fails. You do not print yet because you first call main again, asking for the next input. Only when you get a correct int you print, and then finish and allow the previous main-execution to finish by printing, which then allows the previous... and so on:
main(args)
ask for input -> a !int
main(args)
ask for input -> d !int
main(args)
ask for input -> 2.0 !int
main(args)
ask for input -> 1 int
print 1 (1)
print 0 (2.0)
print 0 (d)
print 0 (a)
Look at Ravi's answer for a proper way to repeatedly ask for input without using try/catch (which is discouraged).

You could check for integer token in loop
while (!sc.hasNextInt()) // loop until next token is integer
{
// do something or print error
System.out.println(sc.next() +"is not number");
}
i = sc.nextInt();

Related

Using ints/doubles and Strings in the same Scanner variable

So I'm new to java programming, coming from Python, and there's a few concepts that I can't quite understand.
I'm writing a program which allows the user to enter as many numbers as they want and the program should output the average of all of the numbers. I used a while loop to loop through the inputs by the user as many times as they wanted, but I needed a way of exiting the loop so that the program could proceed with calculating the average of all of the inputs. I decided that if the user enters an "=" sign instead of a number, then the program would break out of the loop, but since the Scanner variable was looking for a double, and the "=" sign is not a number, I would have to make it a String. But because the Scanner is looking for a double, the program threw an error when it encountered the "=".
How can I get the program to exit the loop when the user types "="? I know I could just allow the user to enter a number that breaks the loop, but if it was a real world program and the user entered a number, it would count that number along with the previous ones when calculating the average. The code I have so far is as follows:
import java.util.Scanner;
// imports the Scanner class
public class Average{
public static void main(String[] args){
double num, total = 0, noOfInputs = 0, answer;
Scanner scanner = new Scanner(System.in);
while(true){
System.out.print("Enter number: ");
//Prompts the user to enter a number
num = scanner.nextDouble();
/*Adds the number inputted to the "num" variable. This is the
source of my problem*/
if(num.equals("=")){
break;}
/*The if statement breaks the loop if a certain character is
entered*/
total = total + num;
//Adds the number inputted to the sum of all previous inputs
noOfInputs++;
/*This will be divided by the sum of all of the numbers because
Number of inputs = Number of numbers*/
}
answer = total / noOfInputs;
System.out.print(answer);
}
}
Several ways to do this.
You could read every number as a string, and then if it is a number, parse it to get the value.
Integer.parseInt(String s)
Or you could check what comes next and read accordingly:
while (scanner.hasNext()) {
if (sc.hasNextInt()) {
int a = scanner.nextInt();
} else if (scanner.hasNextLong()) {
//...
}
}
Or you could just catch the InputMismatchException, and work from there.
try{
...
} catch(InputMismatchException e){
//check if '=' ...
}

How to check for user input without exiting for error

I need to check the user input and ask for a correct one if the value is not a digit. However when I do this code, the program displays an error message and then crashes- it does not ask the user to give a new input. How can that be fixed? Thank you!
import java.util.Scanner;
import java.lang.Math;
public class CentimeterInch
{
public static void main (String [] args)
{
final int MAX=100, feet=12, meter=100;
final double inch=2.54;
Scanner scan = new Scanner (System.in);
System.out.println ("This program converts distances. ");
System.out.println ("Enter distance and unit (e.g. 37 1 or 100 2):");
double distance=scan.nextDouble();
if (!scan.hasNextDouble())
{
System.out.println ("please enter a numeric value");
distance=scan.nextDouble();
}
int unitType = scan.nextInt();
if (distance<0)
{
System.out.println ("Please enter a non negative distance");
}
....
Just bring the if clause before performing scan.nextDouble().
if (!scan.hasNextDouble())
{
System.out.println ("please enter a numeric value");
scan.nextLine();
distance=scan.nextDouble();
}
double distance=scan.nextDouble();
First make sure that the number to be read is a double value, then read it. You were doing the reverse
What is scan.nextLine() doing here?
Suppose the user enters abc 2. scan.hasNextDouble() checks wether the token to be read next is a double value or not. It's not, so scan.hasNextDouble() evaluates to false and the if clause gets executed. Inside the if clause, you have scan.nextLine(). It simply discards the current input from scan, thus flushing scan. If you don't do so, then scan still contains abc 2 and upon executing distance = scan.nextDouble(), the compiler issues an error.
It's better if you replace if with while. Suppose user gives wrong input. Your program checks the input and finds out that it's not a double value. The if clause if executed and the user is asked to enter a numeric value. What if the user again enters a wrong input. This time, you will get an error. Using a while loop makes your program to keep asking the user for a correct input until he enters a numeric value.

Basic program hanging at nextInt()

I have just started my 2nd programming course at college and our first assignment is rather simple, intended to basically check our environment and to check we know how to submit assignments through the course website.
When I run the code we have been supplied with, it hangs where it is supposed to prompt for the user to enter a number, so that it can print it. I inserted a series of println statements to determine where it was hanging.
It prints TEST1, TEST2 and TEST3, but never makes it to TEST4. So there must be something wrong with the line:
number = input.nextInt();
But I can't for the life of me see what's wrong with that line. Any help would be greatly appreciated! :)
Anyway, here is the code
package rossassignment1;
import java.util.Scanner; // use the Scanner class located in the "java.util" directory
public class RossAssignment1 {
public static void main (String[] args) {
System.out.println("TEST 1");
int number;
System.out.println("TEST 2");
Scanner input = new Scanner(System.in);
System.out.println("TEST 3");
number = input.nextInt();
System.out.println("TEST 4"); // display the number with other messages
System.out.print("This program reads an integer from a keyboard,\n"
+ " and print it out on the display screen.\n"
+ "The number is: " + number + ".\n"
+ "make sure that you get the exact same output as the expected one!\n");
}
}
After the line input.nextInt() is run the program is waiting for the user (you, or whatever marking system is being used) to input an integer in the console. After you do so the program will continue to your TEST4 line.
If after entering an integer, the codes after that still don't show up, you can do this:
number = input.nextInt();
input.nextLine(); //Add this
It will clear the newline.
Alternatively, I prefer to do this:
number = Integer.parseInt(input.nextLine());

Display an error message for the non-numeric input

So this is my code i dont know what to add if i want to display invalid message for the non numeric inputs please help ty
import java.util.Scanner;
public class Date
{
public static void main (String args [])
{
int x;
Scanner in = new Scanner (System.in);
System.out.print("Enter a date ");
x = in.nextInt();
while (x < 1520 || x > 3999)
{
System.out.println ("Invalid Gregorian Calendar date.");
System.out.print ("Please Input a valid Gregorian Calendar date: ");
x = in.nextInt();
}
System.out.println("Good");
Use a try catch block, and put x = in.nextInt(); inside it
I've changed your code a bit. I think this is what you were aiming for.
I'm not that good in explaining but I try to tell what I did.
First of all I got rid of your in.nextInt() since this is very restrictive. It does only accept an integer and will throw an exception if you type something else in. Normally this would be OK, but since you want the user to be able to correct the input, this will cause more troubles than it would solve.
I then put your code into an infinite loop while(true) which assures, you do not have to restart your application again once you've typed in a wrong value.
What is going on within the loop is quite simple. The console prints out what you want the user to do and reads the consoles input as a String, so you don't have to face any exceptions in the first place.
I then try to parse the given String into an integer value. I added trim() to kill leading spaces as well as trailing, so I won't have to deal with users being confused by typing in numbers with a space since they don't directly see whats wrong when getting their "not an integer" error. This would be thrown, if the input contains spaces.
Now I check whether or not the given integer-value fits your specifiation. I don't need a loop here, so I changed it to be a simple if-statement.
If the value is wrong (or lets say the if (x < 1520 || x > 3999) returns true) I'm going to print out your error message. Since we already passed casting the String input into the integer and we do not reach the else-branch we now return back to the beginning of our loop with printing out the request again before waiting for a new input to be made.
Now, as soon as the user typed in another value, e.g. 2011 (which is valid based on your specification) we will now reach the else-branch which prints the "Good" and leaves the loop by calling break. And since there is nothing left to do for the application it will stop running. If you want the user to be able to type in new values in the positive case, you simply have to remove the break-statement.
If the user types in a value which is not an integer, the cast will fail and throw a NumberFormatException. We catch this exception by surrounding the cast with the try-catch-block and print out the integer-error once we've reached the catch-block.
Then the application reacts the same way like if you typed in a wrong number and we will return to the beginning of the loop again.
The reason for putting a try-block around the Scanner is to handle closing.
import java.util.Scanner;
public class Date {
public static void main(String args[]) {
String input = "";
int x = 0;
try (Scanner in = new Scanner(System.in);) {
while (true) {
System.out.print("Please Input a valid Gregorian Calendar date: ");
input = in.nextLine();
try {
x = Integer.parseInt(input.trim());
if (x < 1520 || x > 3999) {
System.out.println("Invalid Gregorian Calendar date.");
}
else {
System.out.println("Good");
break;
}
} catch (NumberFormatException e) {
System.out.println("Given value \"" + input.trim() + "\" is not an integer.");
}
}
}
}
}
The Scanner class has a method for this
Scanner in = new Scanner(System.in);
int x;
if(in.hasNextInt()){
x = in.nextInt();
System.out.println("Valid number");
}else{
System.out.println("Not a number");
}
To keep prompting until a valid number is entered
int x;
System.out.println("Enter a number: ");
while(!in.hasNextInt()){
System.out.println("Invalid number, try again: ");
key.nextLine(); // Flush out invalid number
}
x = key.nextInt();

How do I create an integer input stream in Java?

I need to do an assignment where I have to write a while loop with a condition like:
while (not end of stream) {
}
I'm confused about the "not end of stream part". How do I make it so it stop reading when there is no integer input in the console? It will be entered like this: 1 2 3 4 5 6 7 8 9.
I am using the Scanner class my code is something like this:
Scanner myScanner = new Scanner(System.in);
int inputValue = userInput.nextInt();
while(not end of stream) {
if (.......) {
....
} else {
....
}
}
Thanks!
Don't let the word stream confuse you, when reading from System.in, there is no continuous 'flow' of numbers coming.. The user can type what ever he wants to and as long as he wants to. Until he hits 'Enter' nothing will happen.
That said, the scenario is more like this:
1 user types 71 2 30 5 1 and hits Enter
2 userInput.nextInt(); will return the first int it finds so here 71
3 now you could do something like this: [EDITED]
public static void main(String[] args) {
System.out.print(">");
Scanner userInput = new Scanner(System.in);
int inputValue = userInput.nextInt();
while (userInput.hasNextInt()) {
System.out.println("you just wrote: " + userInput.nextInt());
}
userInput.close();
}
So until the scanner doesn't find any input that is not an int the loop will continue. In other words, when the user types for example an 'b' the loop terminates.
Now it all depends on what you have to do in your while-loop. You could test for userInput.hasNext() to see if anything comes, or userInput.nextLine() which will wait for an Enter .. or what ever you need.
When I run the above main and type in:[ 1 Enter 2 Enter 3 Enter 4 Enter a Enter ], this is the output:
>1 // <-- this is the number before the while loop
2 // <-- now another number
you just wrote: 2 // <-- and the while loop makes its first iteration
3 // <-- then it waits for you to input the 3rd number
you just wrote: 3 // <-- to make its next iteration
4 // <-- and the 4th
you just wrote: 4 // <-- 4th iteration
a // <-- until you type something else
// end of program
The user always has to hit Enter – otherwise the operation system won't give the typed input to the Java program. This has to do with the settings of the Shell / Console that your operation system provides for the Java program to run. So, Java won't see anything of the input until you hit enter.

Categories

Resources