inputmismatch exception [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
import java.util.*;
public class NGG {
static Scanner numberEntered;
static Scanner userInput = new Scanner(System.in);
static int guessedNumber;
static int randomNumber = (int) (Math.random()* 11);
static Scanner reply;
static String answer;
public static void main(String[] args) {
guessChecker(guessedNumber);
}
public static void guessChecker(int userGuess) {
while (userGuess != randomNumber) {
intro();
userGuess = intChecker();
if (userGuess == randomNumber) {
System.out.println("Congradulations!");
System.exit(0);
} else {
System.out.println("That was Incorrect!");
delay(1000);
retryChecker(reply, answer);
}
}
}
public static int intChecker() {
try {
return userInput.nextInt();
} catch (InputMismatchException e) {
userInput.next();
System.out.println("Your answer was Invalid!");
delay(2000);
retryChecker(reply, answer);
return 0;
}
}
public static void retryChecker(Scanner userReply, String userChoice) {
System.out.println("Would you like to try again?");
userReply = new Scanner(System.in);
userChoice = userReply.nextLine();
if (userChoice.equalsIgnoreCase("yes") || userChoice.equalsIgnoreCase("y")) {
guessChecker(guessedNumber);
} else {
System.exit(0);
}
}
public static void intro() {
System.out.println("I'm thinking of a number in my head...");
delay(1000);
System.out.print("Try to guess it: ");
}
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {}
}
}
and here's my problem:
I have a number guessing game, every time it says "try to guess it:"
it usually will let you type in a guess, unless your previous guess was a string, letter or number, followed by a space and then another string, letter or number, then instead of letting you write your own guess it will just print out "your answer was Invalid" and move on with the program.
How would I fix this? so that the userInput can also be a string, letter or number, followed by a space and then another string, letter or number and it'll move one with the program normally.

The problem is in the intChecker().
public static int intChecker() {
try {
return userInput.nextInt();
} catch (InputMismatchException e) {
userInput.nextLine(); // -> changed from .next() to nextLine()
System.out.println("Your answer was Invalid!");
delay(2000);
retryChecker(reply, answer);
return 0;
}
}
The reason is when you use next() it returns string when it encounters space or EOF.
So when you give input it's me!, first checks it's and says it's wrong. It asks whether to continue or not next. When you press y to goes to the method and reads the remaining string me!.
Here you have used different scanners userInput and userReply. As the userInput is static, the object doesn't dies and has the remaining string in it which is me! after returning its.
So using nextLine() returns the whole string.
For more info on how they both work, check out my other answer
I hope it helped.

Related

Java, How to break a loop when input is empty? [duplicate]

This question already has answers here:
How to test for blank line with Java Scanner?
(5 answers)
Closed 3 years ago.
The goal of this is to let the user enter a number per line and when the user no longer wish to continue they should be able to enter a empty line and when that happens the program should you give you a message with the largest number.
Problem is I can't make the loop break with an empty line. I'm not sure how to. I've checked other questions for a solution but I couldn't find anything that helped. I also can't assign scan.hasNextInt() == null....
I'm sure there is a quick and logical solution to this that I'm not thinking of.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number and press [Enter] per line, when you no longer wish to continue press [Enter] with no input.(empty line)");
int x = 0;
while(scan.hasNextInt()){
int n = scan.nextInt();
if (n > x){
x = n;
}
}
System.out.println("Largets number entered: " + x);
}
}
This should solve your problem:
import java.util.Scanner;
public class StackOverflow {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number and press [Enter] per line, when you no longer wish to continue press [Enter] with no input.(empty line)");
int x = 0;
try {
while(!scan.nextLine().isEmpty()){
int num = Integer.parseInt(scan.nextLine());
if(num > x) {
x = num;
}
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
System.out.println("Largest number entered: " + x);
scan.close();
}
}
import java.util.*;
public class main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number and press [Enter] per line, when you no longer wish to continue press [Enter] with no input.");
String str = scanner.nextLine();
int x = 0;
try {
while(!str.isEmpty()){
int number = Integer.parseInt(str);
if (number > x){
x = number;
}
str = scanner.nextLine();
}
}
catch (NumberFormatException e) {
System.out.println("There was an exception. You entered a data type other than Integer");
}
System.out.println("Largets number entered: " + x);
}
}

The Command Prompt just hangs after executing my java program

It seems like there is no problem with this code (here it is):
import java.util.*;
public class NumberGuessingGame {
static int randomNumber = (int) (Math.random() * 11);
static Scanner userInput = new Scanner(System.in);
static int guessedNumber = userInput.nextInt();
public static void main(String[] args) {
start: {
while (guessedNumber != randomNumber) {
System.out.println("I'm thinking of a number in my mind between 0 and 10. ");
delay(1500);
System.out.print("Try to guess it: ");
if (guessedNumber == randomNumber) {
System.out.print("Congradulations! ");
delay(800);
System.out.println("The number really was " + randomNumber);
} else {
break start;
}
}
}
}
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
}
}
}
If you couldn't tell already I'm a beginner trying to create a basic number guessing game. So I successfully coded it but now every time I execute it this happens:
It just freezes. Why?
The issue is that you're putting the userInput.nextInt() call in the initializer for a static field; so it gets called (and the program pauses for input) as your class is loading, before it can pribt a prompt requesting the input. So it looks like it froze, but if you enter a number it will then proceed.
You want the nextInt() call to be inside your method after the calls that prompt for input
The error is because your program is waiting for an user input. According to the docs, a Scanning operation may block waiting for input
The solution is implementing a do/while and userInput and guessedNumber initialized when they are required.
NumberGuessingGame:
import java.util.*;
public class NumberGuessingGame {
static int randomNumber = (int) (Math.random() * 11);
static Scanner userInput;
static int guessedNumber;
public static void main(String[] args) {
System.out.println("I'm thinking of a number in my mind between 0 and 10. ");
do
{
delay(1500);
System.out.print("Try to guess it: ");
userInput = new Scanner(System.in);
guessedNumber = userInput.nextInt();
if (guessedNumber == randomNumber) {
System.out.print("Congratulations! ");
delay(800);
System.out.println("The number really was " + randomNumber);
} else {
System.out.println("Error, try again! ");
delay(800);
}
}
while (guessedNumber != randomNumber);
}
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
}
}
}
Documentation:
do-while statement
its probably waiting for you to enter a number. I conformed its not hanging. its waiting for user input. try entering a number.

Determining if number entered is an int [duplicate]

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();
}
}

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();
}
}
}

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