I wrote a program to determine a prime number and am required to use 'Q' as the quit function to get out of the program. Below is the code i have written. I am wondering how I would modify method of quitting the program to make it exit correctly.
import java.util.Scanner;
public class Practice
{
public static void main(String[]args)
{
Scanner keyboard = new Scanner(System.in);
int number, i=2;
String quit;
boolean prime = true;
System.out.println("Please enter a number to determine if it is prime, to quit please enter Q.");
number = keyboard.nextInt();
quit = keyboard.nextLine();
for (i=0; i<number;i++)
{
if ((number%2==0) || (number==1) || (number%3==0))
{
prime = false;
}
}
if (prime==false)
{
System.out.println(number+" is not a prime number.");
}
else if(prime==true)
System.out.println(number+" is a prime number.");
if (quit.charAt(0)=='Q')
{ System.exit(0);}
and my output upon entering 'Q' is:
----jGRASP exec: java Practice
Please enter a number to determine if it is prime, to quit please enter Q.
Q
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Practice.main(Practice.java:15)
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
}
}
When the input through the console is given as "Q", the value of type String is getting assigned to a variable of type int, which is incorrect.
number = keyboard.nextInt();
The type of in the input needs to be checked, before it can be assigned to a int variable.
You have:
number = keyboard.nextInt();
quit = keyboard.nextLine();
Think for a moment about what actually happens here. 'Q' is not a number and so nextInt(), as documented, throws an InputMismatchException. Your use of nextLine() doesn't make much sense following that.
You have a couple of options:
Use Scanner.hasNextInt() to determine if the next token truly is a well-formed integer. If not, read it as a string and check it.
Use Scanner.next() always, and check if it is "Q" before parsing it with Integer.parseInt() (being prepared to handle errors there as well).
The Scanner.next* functions don't implicitly skip invalid values. The Scanner is only doing what you tell it to do, and if you tell it to grab an integer but the input is not an integer, it rightfully complains. It is up to you to use the Scanner appropriately and check your possible input cases.
You should read in the numbers as Strings with keyboard.nextLine();
and check first if the it contains 'Q'. If it does, quit, else do, number = Integer.parseInt(yourVariableHere); and go from there
Try this instead:
String input;
int number = 1;
int i=2;
Then do this:
System.out.println("Please enter a number to determine if it is prime, "
+ "\nto quit, please enter Q.");
input = keyboard.nextLine();
if (input.charAt(0)=='Q')
{
System.exit(0);
}
else
{
try
{
number = Integer.parseInt(input);
}
catch(NumberFormatException nfe)
{
System.out.println("Please enter a number or Q!");
}
}
Related
This is my first Java program. The assignment is to create a program as follows:
Develop a Java program that works as follows:
1). When the program is started, it displays a message welcoming the player: "Welcome to Game Guru!"
2). Then it creates a secret random number between 1 and 20;
3), Then it displays a message saying: "Guess my magic number [1-20]: "
4). Read and check the number entered by the player.
If is not a number, the program displays a message saying: "Should enter a number". then go back to step 3)
If the number is out of range, the program displays a message saying: "Number out of range". Then go back to step 3)
If the number is smaller than the secret number, the program displays a message saying: "Number too small". Then go back to step 3)
If the number is greater than the secret number, the program displays a message saying: "Number too large". Then go back to step 3)
If the number is the same as the secret number, the program displays a message saying: "You got it!". Then go to step 5)
5). The program displays a message saying: "Want more games?"
6). Read the player's answer. If the answer is "yes", then to step 1); If the answer is "no", then go to step 7)
7). The program displays message "Thanks for playing the game. Goobye".
I have gotten it working completely EXCEPT when entering anything other than an INT it gives an exception. I tried researching this myself and found the Try/Catch but it doesn't seem to be working for me. My instructor wont help me...despite the fact that he hasn't actually taught any of this...
Here's my code:
public static void main(String[] args)
{
// TODO Auto-generated method stub
String more;
do
{
System.out.println("Welcome to Game Guru!");
int number = 1 + (int)(Math.random() * 20);
int guess = 0;
Scanner input = new Scanner(System.in);
try
{
System.out.println("Guess my magic number [1-20]: ");
guess = input.nextInt();
}
catch (Exception e)
{
System.out.println("Should enter an integer");
}
while (guess != number)
{
if (guess > 20 || guess < 1)
{
System.out.println("Number out of range");
System.out.println("Guess my magic number [1-20]: ");
guess = input.nextInt();
}
else if (guess < number)
{
System.out.println("Number too small");
System.out.println("Guess my magic number [1-20]: ");
guess = input.nextInt();
}
else if (guess > number)
{
System.out.println("Number too large");
System.out.println("Guess my magic number [1-20]: ");
guess = input.nextInt();
}
}
if (guess == number)
{
System.out.println("You got it!");
}
System.out.println("Want more games? Please enter Y or N.");
more = input.next();
} while (more.equals("y") || more.equals("Y"));
System.out.println("Thanks for playing the game. Goodbye");
}
}
Here's the console:
Welcome to Game Guru!
Guess my magic number [1-20]:
a
Should enter an integer
Number out of range
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Unknown Source)
at java.base/java.util.Scanner.next(Unknown Source)
at java.base/java.util.Scanner.nextInt(Unknown Source)
at java.base/java.util.Scanner.nextInt(Unknown Source)
Guess my magic number [1-20]:
at Game.main(Game.java:46)
I really appreciate any insight into this. I'm at my wits end...I should be paying Google my tuition.
So, starting with...
try
{
System.out.println("Guess my magic number [1-20]: ");
guess = input.nextInt();
}
catch (Exception e)
{
System.out.println("Should enter an integer");
}
Basically, if an exception occurs, the Scanner still contains non-numerical data in it's buffer, this means that if you then try and read the buffer again, doing something like...
guess = input.nextInt();
You will get the same exception again.
A general solution is to call input.nextLine() to clear the buffer before attempting to read new data from it. Personally, I'd use nextLine for all the inputs and Integer.parseInt to parse those elements which you want as int values, but that's me.
Since you have to ask the user for input each time they need to make a guess, you could simplify your solution by using a do-while loop instead (you have to enter the loop at least once any way), this way you could get the input, verify the value (as an int) and perform your required logic on it, all within a single basic loop...
Scanner input = new Scanner(System.in);
String more = "N";
do {
System.out.println("Welcome to Game Guru!");
int number = 1 + (int) (Math.random() * 20);
int guess = 0;
do {
try {
System.out.println("Guess my magic number [1-20]: ");
String text = input.nextLine();
guess = Integer.parseInt(text);
if (guess > 20 || guess < 1) {
System.out.println("Number out of range");
} else if (guess < number) {
System.out.println("Number too small");
} else if (guess > number) {
System.out.println("Number too large");
}
} catch (NumberFormatException e) {
System.out.println("Should enter an integer");
}
} while (guess != number);
System.out.println("You got it!");
System.out.println("Want more games? Please enter Y or N.");
more = input.nextLine();
} while (more.equalsIgnoreCase("y"));
In the try, you are giving the code you want to execute (fine). In the except statement, you are correctly printing out the error too (great).
Unfortunately, you didn't fix it!
It probably makes sense to put your try/catch in a while loop that repeats until you get valid input. That way, once it works, you move on to the rest of your logic which is dependent on getting valid input from the user in the try/catch.
You're asking to enter an int, if the user enter another value as a String or Float you will get an exception.
Add another try{} catch{} block to verify if it is an Integer otherwise cast it
What happens in your code is that it catches that exception in the first try/catch, prints System.out.println("Should enter an integer"); and then proceeds to the rest of the do block. You need to continue after printing that message.
However, you'll encounter more bugs in that code as you continue testing, this is just to answer your question about that exception.
The purpose of your try/ catch is to tell the user that the number they selected is not an integer. The program is not supposed to continue if you enter something other than an integer, as it says in step 4- The first if statement is used to verify that the number is an integer.
Instead, you are using a try/ catch, which also stops the program, but a little differently.try/catch block
The block of code in the try statement prompts the user to enter a number 1-20. If it is not, it throws the exception because the number entered is not an integer. It prints the message " Should enter an integer", and prints out the errors that should tell the user what is wrong. It is telling you there is an error in the Main class of your program, and where the problem is located. The purpose of the print statement " Should enter an integer" was to prompt the user to enter an integer the next time the program runs, so the program can then run correctly.
In your case, the if statement would make more sense to use. Again, the only point of this block of code is to verify the user has entered an integer.
I have simple java program that accepts 3 user inputs of type integer, double and string. I would like to know the best/most efficient way to perform error handling on all of these inputs in order to keep the program running, inform the user they have entered an incorrect input and ask them the question again . Any help would be greatly appreciated.
Here is my code
Scanner scan = new Scanner(System.in);
int inputInt;
double inputDbl;
String inputString;
System.out.print("Please enter a whole number: ");
inputInt = scan.nextInt();
System.out.print("Please enter a decimal number: ");
inputDbl = scan.nextDouble();
System.out.print("Please enter a string: ");
inputString = scan.next().toLowerCase();
Thanks for all the input people, you guys are awesome. I chose to just use a simple dowhile loop using a boolean trigger. I've tried using try catches before but ended up writing huge blocks of code to perform very basic input checks. So don't have any exception handling here, which I hope isn't gonna be necessary this way. Hopefully it doesn't break on me
do {
System.out.print("Please enter a whole number: ");
if (scan.hasNextInt()){
inputInt = scan.nextInt();
validInput = true;
} else
System.out.println("You have entered incorrect input! Please enter a whole number only");
scan.nextLine();
} while (validInput == false);
validInput = false;
do {
System.out.print("Please enter a decimal number: ");
......
......
Splitting this into n methods where n is how many user inputs there are.
For each user input create a method that gets the input:
String getStringInput(){
System.out.println("Enter input");
String input = scan.next();
//check the input to make sure it is correct
if(input.equals("foo")){
//if the input is incorrect tell the user and get the new input
System.out.println("Invalid Input");
//simply return this method if the input is incorrect.
return getStringInput();
}
//return the input if it is correct
return input;
}
For the main method that gets the input simply call the method:
void getAll(){
String stringValue = getStringInput();
}
This now makes it easy to get any number of inputs and check if the are correct.
boolean validated = false;
// this keeps user locked until he/she provides valid inputs for all variables
while(!validated) {
//get inputs here
// ..
// lastly
validated = validateLogic(inInt, inDbl, inStr);
}
// keep going
If you want to validate separately for each input, you shuold write while loop 3 times.
I am getting an error when I am entering string value in integer variable. I want to know to handle the exception, as my program give a indication that enter your value again rather it stop and gave exceptional handling error.
System.out.println("Please enter a number");
Scanner obj1=new Scanner(System.in);
int a=obj1.nextInt(); //I am entering string value here
System.out.println(a);
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at javaapplication13.JavaApplication13.main(JavaApplication13.java:23)
It is better to preventing throwing exception instead of handling it since creating exception object may be quite expensive. In case of Scanner class your code can look like:
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number:");
while(!scanner.hasNextInt()){//while user is not providing valid int
//inform him about it
System.out.println("that was not valid integer, please try again: ");
//and consume invalid value (maybe even entire line)
scanner.nextLine();
}
//since we are out of loop it must mean that user entered valid int, lets store it
int a = scanner.nextInt();
System.out.println(a);
You can also wrap this code in some nice utility method in which you can even add support to maximal number of tries. For that kind of code you can use as result Optional<Integer>. This will allow us clear info if user
provided proper value, and we will return Optional with this value
or if he failed to do so, in which case we can return empty Optional.
which is cleanest way of handling results which may not exist.
Without Optional we would either have to:
return some default value like:
-1 but in that case we don't know if -1 represents invalid input, or if user actually provided -1 which means it may be proper result
null (if we change return type to Integer) but this way we are making our programmer who will use our method to also check if(result != null) which may not be that obvious for many programmers (using Optional gives us clear idea that result may not exist so programmer knows that he should check this possibility).
throw exception, but since reason why we are creating our method is to avoid creating and handling exception it would be kind of stupid.
So your method can look like
//-1 represents infinite number of tries
public static Optional<Integer> readInt(Scanner sc, String msg, int tries){
System.out.println(msg);
int counter = 0;
//while user still has more tries but is providing invalid int
while((tries == -1 || counter < tries) && !sc.hasNextInt()){
//inform him about wrong data
if (tries == -1 || ++counter < tries)
System.out.println("That was not valid integer. Please try again:");
else
System.out.println("That was not valid integer.");
//and consume invalid value (maybe even entire line)
sc.nextLine();
}
// since we are out of loop it must mean that user entered valid int
// or run out of tries
if (tries == -1 || counter < tries)
return Optional.of(sc.nextInt());
else
return Optional.empty();
}
and its usage can look like
Scanner scanner = new Scanner(System.in);
Optional<Integer> result = readInt(scanner, "Please enter a number:", 1);
if(result.isPresent()){
System.out.println(result.get());
}else{
System.out.println("User failed to give valid integer. Program will terminate");
}
Use this
System.out.println("Please enter a number");
Scanner obj1=new Scanner(System.in);
if(obj1.hasNextInt())
{
int a=obj1.nextInt(); //I am entering string value here
System.out.println(a);
}
Put the code in the try-catch block to handle the InputMismatchException
System.out.println("Please enter a number");
Scanner obj1=new Scanner(System.in);
try {
int a=obj1.nextInt();
}
catch(InputMismatchException ime) {
/*show error message for incorrect input*/
}
catch(Exception e) {
/*Show error message*/
}
System.out.println(a);
Hope, this solves the problem.
You can try this...
boolean i=true;
while(i){
try{
System.out.println("Please enter a number");
Scanner obj1=new Scanner(System.in);
int a=obj1.nextInt(); //I am entering string value here
System.out.println(a);
i=false;
}catch(InputMismatchException e){
System.out.println("Invalid number, please enter again");
}
}
boolean acceptPcode=true;
boolean acceptQty=false;
int Qty=0;
List<Integer> purchasedProdQty=new ArrayList<>();
while(acceptPcode==true && acceptQty==false){
do{
try{
System.out.print("Enter Qty: ");
Qty=sc.nextInt();
acceptQty=true;
}catch(InputMismatchException ime){
System.out.println("Invalid quantity please enter a number!");
acceptQty=false;
}
if(acceptQty==true)
purchaseProdQty.add(Qty);
}while(acceptQty==false);
}
my question is that when i enter a letter it goes in an infinity loop and it doesn't prompt the user to enter a quantity ....which is
Enter Qty: Invalid quantity please enter a number!
Enter Qty: Invalid quantity please enter a number!
Enter Qty: Invalid quantity please enter a number!......
You forgot to read the \n (or \r\n) characters that are from the next line. In your current code, the scanner is waiting for an int input, bu the current next input is this break line char. Just add sc.nextLine() in your code to consume the break line char:
Qty=sc.nextInt();
sc.nextLine();
acceptQty=true;
From what I can gather it seems your scanner(sc) is throwing an exception. This causes acceptQty to constantly be false keeping you stuck in your inner do-while loop.
You need to consume any illegal characters in the exception block otherwise they won't be consumed by the Scanner#nextInt method call causing the loop to repeat itself indefinitely:
} catch(InputMismatchException ime) {
System.out.println
("Invalid quantity: " + sc.nextLine() + " please enter a number ");
...
}
You are getting exception while reading out of sc and so it always go into infinity loop. Can you paste what's the value assiged in sc?
I believe you're doing this all wrong. Your method of validation is very obscure and can be simplified. Suppose you have the following method:
public int readNumber(final String prompt, final Scanner scanner){
System.out.println(prompt);
try{
return scanner.nextInt();
}catch(Exception ex){
System.err.println("Enter a valid number");
return readNumber(prompt, scanner);
}
}
This method will print out the prompt (the first argument) and read input from the provided Scanner (the second argument). If the user enters something that can't be parsed as an int, it will invoke the same method (recursion).
Take out both of your loops and when you want to read an int from your Scanner, do something like:
int value = readNumber("Enter a quantity", sc);
You know for sure that Integer.MAX_VALUE >= value >= Integer.MIN_VALUE
Basic problem here.. I will start off by asking that you please not respond with any code, as that likely will only confuse me further (programming noob). I am looking for a clear explanation on how to solve this issue that I'm having.
I have a scanner that reads input from the user. The user is prompted to enter an int value between 1 to 150 (whole numbers only). I obtain the value as follows:
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
And continue on with my program, and everything works fine.
Unfortunately, the code isn't exactly bulletproof, since any input that is not an integer can break it (letters, symbols, etc).
How can I make the code more robust, where it would verify that only an int was entered?
These are the results I'm hoping for:
Lets say the input was:
23 -> valid
fx -> display an error message, ask the user for input again (a while loop would do..)
7w -> error, again
3.7 -> error
$$ -> error
etc
Scanner.hasNextInt() returns true if the next token is a number, returns false otherwise.
In this example, I call hasNextInt(). If it returns true, I go past the while and set the input; if it returns false, then I discard the input (scanner.next();) and repeat.
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) {
scan.next();
}
int input = scan.nextInt();
Here's a simple example with prompts and comments.
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: "); // Initial prompt for input
// Repeat until next item is an integer
while (!scan.hasNextInt())
{
scan.next(); // Read and discard offending non-int input
System.out.print("Please enter an integer: "); // Re-prompt
}
// At this point in the code, the user has entered an integer
int input = scan.nextInt(); // Get the integer
// And now you can use the input variable.
Use scan.hasNextInt() to make sure the next input is an int.
I have written an example that ensures that the program will continue only if a number and not an invalid value is entered. Do not worry, I added the desired explanation.
The program asks the user to input a number. A loop ensures that the processing will not go on until a valid number is entered. Before that I have defined a variable "inputAccepted" that has false as default value. If he enters a number, the variable "inputAccepted" is set to true and the program leaves the loop. But if he enters something else than a number, an exception is thrown right in this moment, and the line that sets the variable "inputAccepted" to true will not be executed. Instead a message will be printed out that tells the user that his input is not valid. Since "inputAccepted" could not be set to true, the loop will do the same stuff again until the string can be converted to a number.
You can test the program here.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean inputAccepted = false;
while (!inputAccepted) {
try {
System.out.print("Please enter a number: ");
Integer.valueOf(input.nextLine());
inputAccepted = true;
} catch (NumberFormatException e) {
System.out.println("Not a valid number.");
}
}
System.out.println("Thank you!");
}
}
Just get "anything" and parse it:
Scanner scan = new Scanner(System.in);
Integer number = null;
while (number == null) {
try {
number = Integer.parseInt(scan.next());
} catch (NumberParseException e) {
System.out.println("bad input: " + input);
}
}
Without any code and just in English, I'd say there's two things you have to test or look out for. First that the input is an int, second that the int is within the correct range.
In terms of pseudocode, the first thing to do is make sure it's an int. Declaring an int named "input", I would put a try / catch block, where you try to scan in the user input as an int, with parseInt(). If the try part fails, you know it's not an int and can return an error message.
Then, now that you know that "input" is an int, you can test whether it is less than 1 or more than 150, and return an error message if so!
public class Sample {
/**
* author CLRZ
*/
public static void main(String[] args) {
int a; // variable
Scanner in = new Scanner(System.in); // scans your input
System.out.println("Enter your number's choice:");
int sem1 = in.nextInt(); // reads next integer
if (sem1 == 1) // conditioned if your choice number is equal to 1
System.out.println("Hello World1"); // output wil be Hello World
int b;
System.out.println("Enter your number's choice:");
int sem2 = in.nextInt();
if (sem2 == 2)
System.out.println("Hello World2");
int c;
System.out.println("Enter your number's choice:");
int sem3 = in.nextInt();
if (sem3 == 3)
System.out.println("Hello World3");
}
}