Make a code repeat loop if user input a non-numeric character? - java

Goal:
If the user enters a non-numeric number, make the loop run again.
Also is there another (more efficient) way of writing the numeric inputs?
public static void user_input (){
int input;
input = fgetc (System.in);
while (input != '\n'){
System.out.println("Please enter a number: ");
if (input == '0' == '1' ..... '9'){
//Execute some code
}
else {
System.out.println("Error Please Try Again");
//Repeat While loop
}
}
}
EDIT
I need the while loop condition. Simply asking, how do you repeat the while loop? Also no scanner methods.

Take the input using next instead of nextInt. Put a try catch to parse the input using parseInt method. If parsing is successful break the while loop, otherwise continue. Try this:
public static void user_input() {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a number.");
String input = sc.next();
int intInputValue = 0;
try {
intInputValue = Integer.parseInt(input);
System.out.println("Correct input, exit");
break;
} catch (NumberFormatException ne) {
System.out.println("Input is not a number, continue");
}
}
}
Output
Enter a number.
w
Input is not a number, continue
Enter a number.
3
Correct input, exit

Try this one
System.out.println("Please enter a number: ");
Scanner userInput = new Scanner(System.in);
while(!userInput.hasNextInt()) {
System.out.println("Invalid input. Please enter again");
userInput = new Scanner(System.in);
}
System.out.println("Input is correct : " + userInput.nextInt());

How about this
public static void processInput() {
System.out.println("Enter only numeric: ");
Scanner scannerInput;
while (true) {
scannerInput = new Scanner(System.in);
if (scannerInput.hasNextInt()) {
System.out.println("Entered numeric is " + scannerInput.nextInt());
break;
} else {
System.out.println("Error Please Try Again");
}
}
}

Related

NoSuchElementException Problem in User Input Java

I'm confused while using an Java program I created.
public static void main(String[] args) {
Scanner scanner1 = new Scanner(System.in);
int input1 = 0;
boolean Input1Real = false;
System.out.print("Your first input integer? ");
while (!Input1Real) {
String line = scanner1.nextLine();
try {
input1 = Integer.parseInt(line);
Input1Real = true;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.print("Your first input integer? ");
}
}
System.out.println("Your first input is " + input1);
}
Initially, when a user Ctrl+D during the input, it will promptly end the program and display an error in the form of this,
Your first input integer? ^D
Class transformation time: 0.0073103s for 244 classes or 2.9960245901639343E-5s per class
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651);
at Playground.Test1.main(Test1.java:13)
Doing a bit of research I note that Ctrl+D terminates the input of sort. Therefore, I tried add few more lines to my codes to prevent the error from appearing again and instead printing a simple "Console has been terminated successfully!" and as far as my skills can go.
public static void main(String[] args) {
Scanner scanner1 = new Scanner(System.in);
int input1 = 0;
boolean Input1Real = false;
System.out.print("Your first input integer? ");
while (!Input1Real) {
String line = scanner1.nextLine();
try {
try {
input1 = Integer.parseInt(line);
Input1Real = true;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.print("Your first input integer? ");
}
}
catch (NoSuchElementException e) {
System.out.println("Console has been terminated successfully!");
}
}
System.out.println("Your first input is " + input1);
}
In the end, I still got the same error.
Got it!, the code hasNext() will ensure that the error will not appear. This method is to check whether there is another line in the input of the scanner and to check if its filled or empty. I am also using null to check my statement after passing the loop so the program stops if the input value is still null while keeping the function of Ctrl+D.
public static void main(String[] args) {
Integer input1 = null;
System.out.println("Your first input integer? ");
Scanner scanner1 = new Scanner(System.in);
while(scanner1.hasNextLine()) {
String line = scanner1.nextLine();
try {
input1 = Integer.parseInt(line);
break;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.println("Your first input integer? ");
}
}
if (input1 == null) {
System.out.println("Console has been terminated successfully!");
System.exit(0);
}
System.out.println(input1);
}
This solution is not prefect of course but I would appreciate if there were much simpler options.

Sanitizing user input in Java, correcting mistakes [duplicate]

I'm new to Java and I wanted to keep on asking for user input until the user enters an integer, so that there's no InputMismatchException. I've tried this code, but I still get the exception when I enter a non-integer value.
int getInt(String prompt){
System.out.print(prompt);
Scanner sc = new Scanner(System.in);
while(!sc.hasNextInt()){
System.out.println("Enter a whole number.");
sc.nextInt();
}
return sc.nextInt();
}
Thanks for your time!
Take the input using next instead of nextInt. Put a try catch to parse the input using parseInt method. If parsing is successful break the while loop, otherwise continue.
Try this:
System.out.print("input");
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a whole number.");
String input = sc.next();
int intInputValue = 0;
try {
intInputValue = Integer.parseInt(input);
System.out.println("Correct input, exit");
break;
} catch (NumberFormatException ne) {
System.out.println("Input is not a number, continue");
}
}
Shorter solution. Just take input in sc.next()
public int getInt(String prompt) {
Scanner sc = new Scanner(System.in);
System.out.print(prompt);
while (!sc.hasNextInt()) {
System.out.println("Enter a whole number");
sc.next();
}
return sc.nextInt();
}
Working on Juned's code, I was able to make it shorter.
int getInt(String prompt) {
System.out.print(prompt);
while(true){
try {
return Integer.parseInt(new Scanner(System.in).next());
} catch(NumberFormatException ne) {
System.out.print("That's not a whole number.\n"+prompt);
}
}
}
Keep gently scanning while you still have input, and check if it's indeed integer, as you need:
String s = "This is not yet number 10";
// create a new scanner
// with the specified String Object
Scanner scanner = new Scanner(s);
while (scanner.hasNext()) {
// if the next is a Int,
// print found and the Int
if (scanner.hasNextInt()) {
System.out.println("Found Int value :"
+ scanner.nextInt());
}
// if no Int is found,
// print "Not Found:" and the token
else {
System.out.println("Not found Int value :"
+ scanner.next());
}
}
scanner.close();
As an alternative, if it is just a single digit integer [0-9], then you can check its ASCII code. It should be between 48-57 to be an integer.
Building up on Juned's code, you can replace try block with an if condition:
System.out.print("input");
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a whole number.");
String input = sc.next();
int intInputValue = 0;
if(input.charAt(0) >= 48 && input.charAt(0) <= 57){
System.out.println("Correct input, exit");
break;
}
System.out.println("Input is not a number, continue");
}

How do I stop a loop from indefinitely looping in Java?

I have this try/catch wrapped around a do/while loop because after the try/catch throws the error message, I want it to loop back to the top. I tried do/while, while, and I tried placing the while loop at different places in my code but nothing works. The program works fine until an exception is thrown and then it goes into an infinite loop. After is displays the error message, I just want it to loop back up to the top.
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
Integer userInput;
do {
try{
System.out.print("Enter a number? \n");
userInput = input.nextInt();
if ( userInput == 1 )
Animal1.displayMessage ();//Display the total
if( userInput == 2 )
Animal2.displayMessage ();//Display the total
}
catch (Exception e) {
System.out.println(" That's not right ");
break;
}
} while (true);
}
}
This is what it does after displaying an error message.
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
Enter a number?
If I don't stop it, it just keeps going.
you can try this workaround:
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
Integer userInput;
do {
try{
System.out.print("Enter a number? \n");
userInput = input.nextInt();
if ( userInput == 1 )
Animal1.displayMessage ();//Display the total
if( userInput == 2 )
Animal2.displayMessage ();//Display the total
}
catch (Exception e) {
System.out.println(" That's not right ");
input.next();
}
} while (true);
}
}
or if you want to avoid try-catch:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Integer userInput = 0;
do {
System.out.print("Enter a number? \n");
if (input.hasNextInt())
userInput = input.nextInt();
else {
System.out.println(" That's not right ");
input.next();
}
if (userInput == 1)
Animal1.displayMessage ();//Display the total
;// Display the total
if (userInput == 2)
Animal2.displayMessage ();//Display the total
} while (true);
}
You can give 3 options - one option to exit
System.out.print("Enter a number? \n 1 to display Animal1 total\n2 to display Animal2 total\n 3 to exit");
Inside while loop, you can add
if ( userInput == 3) break;
You need to put the try/catch statements outside of the loop.

InputMismatchException for String input into integer field

I am having trouble with entering non-integers into an integer field. I am only taking precautions so that if another person uses/works on my program they don't get this InputMismatchException.
When I enter a non-digit character into the input variable, I get the above error. Is there any way to compensate for this like one could do for a NullPointerException when it comes to strings?
This code is redacted just to include the relevant portions causing the problem.
import java.util.Scanner;
class MyWorld {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int input = 0;
System.out.println("What is your age? : ");
input = user_input.nextInt();
System.out.println("You are: " +input+ " years old");
}
}
You can use an if statement to check if user_input hasNextInt(). If the input is an integer, then set input equal to user_input.nextInt(). Otherwise, display a message stating that the input is invalid. This should prevent exceptions.
System.out.println("What is your age? : ");
if(user_input.hasNextInt()) {
input = user_input.nextInt();
}
else {
System.out.println("That is not an integer.");
}
Here is some more information about hasNextInt() from Javadocs.
On a side note, variable names in Java should follow the lowerMixedCase convention. For example, user_input should be changed to userInput.
You can add a try-catch block:
import java.util.Scanner;
class MyWorld {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int input = 0;
System.out.println("What is your age? : ");
try{
input = user_input.nextInt();
}catch(InputMisMatchException ex)
System.out.println("An error ocurred");
}
System.out.println("You are: " +input+ " years old");
}
}
If you want to provide the user to enter another int you can create a boolean variable and make a do-while loop to repeat it. As follows:
boolean end = false;
//code
do
{
try{
input = user_input.nextInt();
end = true;
}catch(InputMisMatchException ex)
System.out.println("An error ocurred");
end = false;
System.out.println("Try again");
input.nextLine();
}
}while(end == false);
This is a try-catch block. You need to use this if you want to be sure of not making the program-flow stop.
try {
input = user_input.nextInt();
}
catch (InputMismatchException exception) { //here you can catch that exception, so program will not stop
System.out.println("Integers only, please."); //this is a comment
scanner.nextLine(); //gives a possibility to try giving an input again
}
Test using hasNextInt().
Scanner user_input = new Scanner(System.in);
System.out.println("What is your age?");
if (user_input.hasNextInt()) {
int input = user_input.nextInt();
System.out.println("You are " + input + " years old");
} else {
System.out.println("You are a baby");
}
Use Scanner's next() method to get data instead of using nextInt(). Then parse it to integer using int input = Integer.parseInt(inputString);
parseInt() method throws NumberFormatException if it is not int, which you can handle accordingly.

input a number on scanner

I am trying to create a simple Java program where the user should input his age. If the user entered for example a letter instead of a number, he will get a message.
What I would like to do is that in addition to the message the user should be asked for another input and that input will be checked again to see if it is a number.
Can anyone know how can I achieve that?
System.out.println("2 - Set The Age");
Scanner b = new Scanner(System.in);
if (b.hasNextDouble()) {
double lage = b.nextDouble();
setAge(lage);
addEmployeeMenu();
} else {
System.out.println("You should type only numbers!");
}
You can use a while loop like this
Scanner b = new Scanner(System.in);
double lage;
while (true) {
System.out.println("2 - Set The Age");
if(b.hasNextDouble()){
lage = b.nextDouble();
break;
}else b.nextLine();
}
The point is, get your number and check it inside a while loop, repeat as long as the input is not correct
You can also use NumberFormatException:
while (true) {
System.out.println("Set the age: ");
String input = sc.next();
try {
int x = Integer.parseInt(input);
System.out.println("Your input '" + x + "' is a integer");
break;
} catch (NumberFormatException nFE) {
System.out.println("Not an Integer");
}
}

Categories

Resources