Determining if number entered is an int [duplicate] - java

This question already has answers here:
What's the best way to check if a String represents an integer in Java?
(40 answers)
Closed 8 years ago.
import java.util.Scanner;
public class test {
/**
* #param args
*/
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
boolean US1 = false;
boolean game;
int score = 1;
int wage = 0;
int fin_score = 0;
String ans;
if (US1 == false) {
game = false;
System.out.println (score);
System.out.println("Enter a wager");
wage = input.nextInt();
}
if (wage < score) {
System.out.println ("What is the capital of Liberia?");
ans = input.next();
if (ans.equalsIgnoreCase("Monrovia")) {
System.out.println ("You got it right!");
System.out.println ("Final score " + fin_score);
}
}
}
}
I have found a bunch of solutions using InputMismatchException and try{}catch{} but they never work when they are implemented in my code. is there a way to implement these here? I am trying to make a loop that iterates until the wage entered is an integer

You can have multiple catch exceptions in your code to check for bad input. For example
try{
wage = input.nextInt();
catch (InputMismatchException e){
System.out.print(e.getMessage());
//handle mismatch input exception
}
catch (NumberFormatException e) {
System.out.print(e.getMessage());
//handle NFE
}
catch (Exception e) {
System.out.print(e.getMessage());
//last ditch case
}
Any of these would work fine for Scanner errors, but InputMismatchException is the best to use. It would help your case a great deal if you included the non-working code with the try-catch blocks.

First of all, You should be using Scanner.nextLine, because Scanner.nextInt uses spaces and newlines as delimiters, which is probably not what you want (any thing after a space will be left on the scanner, breaking any next reads).
Try this instead:
boolean valid = false;
System.out.print("Enter a wager: "); //Looks nicer when the input is put right next to the label
while(!valid)
try {
wage = Integer.valueOf(input.nextLine());
valid = true;
} catch (NumberFormatException e) {
System.out.print("That's not a valid number! Enter a wager: ");
}
}

Yes! There is a good way to do this:
Scanner input = new Scanner(System.in);
boolean gotAnInt = false;
while(!gotAnInt){
System.out.println("Enter int: ");
if(input.hasNextInt()){
int theInt = input.nextInt();
gotAnInt = true;
}else{
input.next();
}
}

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.

About some simple exception handling in Java

There are several questions I would like to ask, please refer the comment part I have added in the code, Thanks.
package test;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
/* Task:
prompt user to read two integers and display the sum. prompt user to read the number again if the input is incorrect */
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean accept_a = false;
boolean accept_b = false;
int a;
int b;
while (accept_a == false) {
try {
System.out.print("Input A: ");
a = input.nextInt(); /* 1. Let's enter "abc" to trigger the exception handling part first*/
accept_a = true;
} catch (InputMismatchException ex) {
System.out.println("Input is Wrong");
input.nextLine(); /* 2. I am still not familiar with nextLine() parameter after reading the java manual, would you mind to explain more? All I want to do is "Clear Scanner Buffer" so it wont loop for the println and ask user to input A again, is it a correct way to do it? */
}
}
while (accept_b == false) {
try {
System.out.print("Input B: ");
b = input.nextInt();
accept_b = true;
} catch (InputMismatchException ex) { /*3. Since this is similar to the above situation, is it possible to reuse the try-catch block to handling b (or even more input like c d e...) exception? */
System.out.println("Input is Wrong");
input.nextLine();
}
}
System.out.println("The sum is " + (a + b)); /* 4. Why a & b is not found?*/
}
}
I am still not familiar with nextLine() parameter after reading the java manual, would you mind to explain more? All I want to do is "Clear Scanner Buffer" so it wont loop for the println and ask user to input A again, is it a correct way to do it?
The use of input.nextLine(); after input.nextInt(); is to clear the remaining content from the input stream, as (at least) the new line character is still in the buffer, leaving the contents in the buffer will cause input.nextInt(); to continue throwing an Exception if it's no cleared first
Since this is similar to the above situation, is it possible to reuse the try-catch block to handling b (or even more input like c d e...) exception?
You could, but what happens if input b is wrong? Do you ask the user to re-enter input a? What happens if you have 100 inputs and they get the last one wrong?You'd actually be better off writing a method which did this for, that is, one which prompted the user for a value and returned that value
For example...
public int promptForIntValue(String prompt) {
int value = -1;
boolean accepted = false;
do {
try {
System.out.print(prompt);
value = input.nextInt();
accepted = true;
} catch (InputMismatchException ex) {
System.out.println("Input is Wrong");
input.nextLine();
}
} while (!accepted);
return value;
}
Why a & b is not found?
Because they've not been initialised and the compiler can not be sure that they have a valid value...
Try changing it something more like.
int a = 0;
int b = 0;
Yes, it's okay. And will consume the non-integer input.
Yes. If we extract it to a method.
Because the compiler believes they might not be initialized.
Let's simplify and extract a method,
private static int readInt(String name, Scanner input) {
while (true) {
try {
System.out.printf("Input %s: ", name);
return input.nextInt();
} catch (InputMismatchException ex) {
System.out.printf("Input %s is Wrong%n", input.nextLine());
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a = readInt("A", input);
int b = readInt("B", input);
System.out.println("The sum is " + (a + b));
}
I have put comment to that question line.
package test;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean accept_a = false;
boolean accept_b = false;
int a=0;
int b=0;
System.out.print("Input A: ");
while (accept_a == false) {
try {
a = input.nextInt(); // it looks for integer token otherwise exception
accept_a = true;
} catch (InputMismatchException ex) {
System.out.println("Input is Wrong");
input.next(); // Move to next other wise exception // you can use hasNextInt()
}
}
System.out.print("Input B: ");
while (accept_b == false) {
try {
b = input.nextInt();
accept_b = true;
} catch (InputMismatchException ex) {
System.out.println("Input is Wrong");
input.next();
}
}
System.out.println("The sum is " + (a + b)); // complier doesn't know wheather they have initialised or not because of try-catch blocks. so explicitly initialised them.
}
}
Check out this "nextLine() after nextInt()"
and initialize the variable a and b to zero
nextInt() method does not read the last newline character.

Inputing Integers error throwing

Can someone help me make this code neater. I would rather use parse int than a buffer reader. I want my code to loop until the user inputs a number. I couldn't figure out how to do this without the code printing out the same statement twice.
public void setAge()
{
try {
age = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("What is your age?");
this.setAge();
}
}
Alright, my question is unclear. I am unsure of how to handle the error that a scanner throws when you don't input an integer. How do I handle this? I found "NumberFormatException" in a different post, but I am unsure of what this does. Can anyone help me with this, or is my question still unclear?
Try this:
import java.util.InputMismatchException;
import java.util.Scanner;
public class TestScanner {
public static void main(String[] args) {
Scanner scanner = null;
int age = -1;
do {
try {
scanner = new Scanner(System.in);
System.out.println("What is your age?");
age = scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Please enter a number!");
}
} while (age == -1);
System.out.println("You are " + age + " years old.");
if (scanner != null)
scanner.close();
}
}
I get this output (the first time I enter abc instead of a number to make it retry):
What is your age?
abc
Please enter a number!
What is your age?
35
You are 35 years old.
Have fun!
Use scan.nextInt(); instead of scan.nextLine();
With this, you don't need to parse the line.
EDIT: Oops, i misread your question
Number Format Exception occurs in the java code when a programmer tries to convert a String into a number. The Number might be int,float or any java numeric values.
The conversions are done by the functions Integer.parseInt.Consider if you give the value of str is "saurabh", the function call will fail to compile because "saurabh" is not a legal string representation of an int value and NumberFormatException will occurs
You could use a scanner.
You'll need to;
import java.util.*;
static Scanner console = new Scanner(System.in);
You won't need the parse statement at all.
age = console.nextInt();
EDIT: Editing my answer after seeing your edit.
I would put the entire try in a do loop. Using a new boolean variable to control when you come out of it.
boolean excep;
do {
excep = false;
try {
age = console.nextInt();
}
catch (Exception exRef) {
System.out.println("Please input an integer");
console.nextLine();
excep = true;
}
} while (excep);
The console.nextLine() just clears a line so it doesnt re-read the last input. Sometimes it's needed.
Using this i don't receive any error notifications on the running of it.
Try this:
static boolean firstTime = true;
public static void main(String[] args) {
boolean firstTime = true;
setAge();
}
public static void setAge()
{
if(firstTime)
{
System.out.println("What is your age?");
firstTime = false;
}
Scanner scan = new Scanner(System.in);
try{
int age = scan.nextInt();
System.out.println(age);
}
catch(InputMismatchException e)
{
setAge();
}
}
if you want to print different messages you would have to do like:
import java.util.Scanner;
public class Numbers {
public static void main(String args[]) {
Numbers numbers = new Numbers();
numbers.setAge();
}
private boolean alrearyAsked = false;
private int age = 0;
static Scanner scan = new Scanner(System.in);
public void setAge()
{
try {
age = scan.nextInt();
} catch (NumberFormatException e) {
if (alrearyAsked) {
System.out.println("you typed a wrong age, please try again.");
}
else {
System.out.println("What is your age?");
}
this.setAge();
}
}
}

Looping around a try catch

In the below code I am attempting to allow the program to catch an exception for an invalid input from user but still allow the program to loop back to the start of the method once exception has been caught. However in my example once there is an exception the program terminates. How can I rectify this? Thank a lot in advance!
public static void add() {
// Setting up random
Random random = new Random();
// Declaring Integers
int num1;
int num2;
int result;
int input;
input = 0;
// Declaring boolean for userAnswer (Defaulted to false)
boolean correctAnswer = false;
do {
// Create two random numbers between 1 and 100
num1 = random.nextInt(100);
num1++;
num2 = random.nextInt(100);
num2++;
// Displaying numbers for user and getting user input for answer
System.out.println("Adding numbers...");
System.out.printf("What is: %d + %d? Please enter answer below", num1, num2);
result = num1 + num2;
do {
try {
input = scanner.nextInt();
} catch (Exception ex) {
// Print error message
System.out.println("Sorry, invalid number entered for addition");
// flush scanner
scanner.next();
correctAnswer=false;
}
} while (correctAnswer);
// Line break for code clarity
System.out.println();
// if else statement to determine if answer is correct
if (result == input) {
System.out.println("Well done, you guessed corectly!");
correctAnswer = true;
} else {
System.out.println("Sorry incorrect, please guess again");
}
} while (!correctAnswer);
}// End of add
I'm not quite sure about the exceptions part, but have you maybe though about just using if statements?
Scanner has a method 'hasNextInt' which you can use to check that the the input is na int. For example:
Scanner scan = new Scanner(System.in);
int i=0;
boolean correctAnswer = false;
while(correctAnswer == false){
if(scan.hasNextInt()){
i = scan.nextInt(); correctAnswer = true;
}else{ System.out.println("Invalid entry");
correctAnswer = false;
scan.next();
}
System.out.println(i);
}
Sorry that it doesn't actually directly answer your question, but I though you might want to know about this possible way too. :)
Instead of throw an exception maybe you can use the method hasNextInt() which returns true if the token is a number.
But if you want absolutely use the try catch block, you have to remove the scanner.next() instrsctions because when nothings available on the buffer, it's throws an NoSuchElementException
I think solution i am giving can be improved but this is simple modification to fix your code: (just add new condition variable to check if further input/ans attempts required)
Hope it helps - MAK
public class StackTest {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws InterruptedException{
// Setting up random
Random random = new Random();
// Declaring Integers
int num1;
int num2;
int result;
int input;
input = 0;
// Declaring boolean for userAnswer (Defaulted to false)
boolean correctAnswer = false;
//MAK: Add new condition for checking need of input
boolean needAnswer = true;
do {
// Create two random numbers between 1 and 100
num1 = random.nextInt(100);
num1++;
num2 = random.nextInt(100);
num2++;
// Displaying numbers for user and getting user input for answer
System.out.println("Adding numbers...");
System.out.printf("What is: %d + %d? Please enter answer below",
num1, num2);
result = num1 + num2;
while(needAnswer){
try {
input = scanner.nextInt();
needAnswer = false;
} catch (Exception ex) {
// Print error message
System.out.println("Sorry, invalid number entered for addition");
// flush scanner
scanner.next();
needAnswer = true;
}
} ;
// Line break for code clarity
System.out.println();
// if else statement to determine if answer is correct
if (result == input) {
System.out.println("Well done, you guessed corectly!");
correctAnswer = true;
} else {
System.out.println("Sorry incorrect, please guess again");
needAnswer = true;
}
} while (!correctAnswer);
}
}
If you want to have the following:
1) Ask the user how much is x + y
2) Let the user answer
3) If answer is invalid (e.g. user typed in "www"), let the user type his answer to question 1) again
than you should replace your inner do-while loop with the following:
boolean validInput = true;
do {
try {
input = scanner.nextInt();
} catch (Exception ex) {
// Print error message
System.out.println("Sorry, invalid number entered for addition. Please enter your answer again.");
// flush scanner
scanner.next();
validInput = false;
}
} while (!validInput);

Comparing User Input To Integer

I'm still in the learning part of Java. I've made a kind of guessing game. It looks like this:
import java.util.Scanner;
import java.util.Random;
public class guessing_game {
static Scanner input = new Scanner(System.in);
static Random generator = new Random();
public static void main(String[] args) {
int number;
number = generator.nextInt(20);
System.out.println("Guess the number!");
game(number);
}
public static void game(int number) {
int inputStorage;
inputStorage = input.nextInt();
if (inputStorage == number) {
System.out.println("You've guessed the right number!");
}
else if (inputStorage != number) {
System.out.println("Wrong number, try again!");
game(number);
}
}
}
Now I have a problem. My little sister and I played this "game". My sister was typing on the numpad. She accidently hit the + button before pressing enter and I got some errors. My question is: How can I let my application print a line which is saying that you can only input numbers and then restarts the game stub again?
One way would be to wrap the input.nextInt() in a try catch statement and catch the exceptions that are thrown by input.nextInt(), InputMismatchException. A good tutorial for try catch statements is here if you aren't sure what I am talking about.
try {
inputStorage = input.nextInt();
} catch (InputMismatchException e){
System.out.println("invalid type");
}
Another way you can do this is:
if(input.hasNextInt()){
inputStorage = input.nextInt();
}else{
System.out.println("invalid type");
}
There is also an error with continuing the game try using a while loop with a break if the number was guessed correctly:
int inputStorage;
boolean notGuessed = true;
while(notGuessed)
{
if(input.hasNextInt()){
inputStorage = input.nextInt();
} else{
System.out.println("invalid type");
}
if (inputStorage == number) {
System.out.println("You've guessed the right number!");
notGuessed = false;
}
else if (inputStorage != number) {
System.out.println("Wrong number, try again!");
}
}
Well this is quite easy. You can accomplish it in various way.
Try this one
public static int checkInt(String strNumber) {
int Number;
try {
Number = Integer.parseInt(strNumber);
} catch (NumberFormatException ex) {
Number = -1;
}
return Number;
}
Or even simpler:
public static int checkInt(String strNumber) {
Number = Integer.parseInt(strNumber, -1);
return Number;
}
The second one is even simpler because you omit a try catch block, that is rather not correctly used in such case. Read about the functions of Integer class.
You can use a try/catch:
boolean b = true;
while (b) {
try {
inputStorage = input.nextInt();
b= false;
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter again!");
}
}
Since the error you got was an Exceptiion: InputMismatchException.
You can explicitly handle the exception using the Exception handling mechanism in java.
Read this
Read this
to know how it actually works.
Above suggested answers are exception handling only.

Categories

Resources