Implementing try-catch inside a loop - java

I want to create a try-catch block inside a loop to give the user multiple opportunities to enter the info with the correct format. When I enter something with incorrect format, the program displays the sysout message "Please enter name and age with correct format." from the catch block.
The problem is when I enter the info with the correct formatting after this message, it keeps displaying the same message "Please enter name and age with correct format." even though it should exit and ask if I want to continue.
Here's what I have:
int inAge;
String inName;
while (true) {
try {
inAge = Integer.parseInt((input.substring((input.indexOf(',') + 1))));
inName = input.substring(0, input.indexOf(','));
list.add(new Plant(inName, inAge));
break;
} catch (Exception e) {
System.out.println("Please enter name and age with correct format.");
in.next();
}
}
System.out.println("Do you wish to continue? (Yes or No)");
endOrNo = in.nextLine();
if ("yes".equalsIgnoreCase(endOrNo))
go = true;
else
go = false;

possible that you call next() instead of nextLine(), that may read wrong input and keep taking you back to the exception block.

You need to update the value of input variable as so.
while (true) {
try {
input = in.nextLine(); // accept input
inAge = Integer.parseInt((input.substring((input.indexOf(',') + 1))));
inName = input.substring(0, input.indexOf(','));
list.add(new Plant(inName, inAge));
break;
} catch (Exception e) {
System.out.println("Please enter name and age with correct format.");
input = in.next();
}
}
System.out.println("Do you wish to continue? (Yes or No)");
endOrNo = in.nextLine();
if ("yes".equalsIgnoreCase(endOrNo))
go = true;
else
go = false;

Related

How to allow user to input both string and int in a same variable

I am trying to make a program which can accept certain integer type input from user, but stop the input as soon the user enters "stop".
I have tried doing so, but it's not working properly. Have a look.
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.io.*;
class Iron {
public static void main(String args[]) throws InterruptedException {
Scanner in = new Scanner(System.in);
System.out.println("Do you wanna play?, type yes to start.");
String a = in.nextLine();
String b; String c="goo";
String d,e="helloWorld";
String al="helloworld";
int f=0,g;
if (a.equalsIgnoreCase("yes")) {
System.out.println("Thanks for staring the game ");
TimeUnit.SECONDS.sleep(1);
System.out.println("-------Welcome to Need For Fun-------");
System.out.println();
TimeUnit.SECONDS.sleep(1);
while (!c.equalsIgnoreCase("yes")) {
System.out.println();
System.out.println("Enter your name_");
b = in.nextLine();
System.out.println("Is your name " + b + "?");
System.out.println("If yes type yes or if not type something else");
c = in.nextLine();
}
TimeUnit.SECONDS.sleep(0);
System.out.println("So, the game is quite similar to hand cricket");
System.out.println("You will win, if your number and Computer's number are equal");
System.out.println("To stop the game any time type start");
System.out.println();
TimeUnit.SECONDS.sleep(1);
System.out.println("So ready to play the game?, type yes to confirm.");
d = in.nextLine();
if(d.equalsIgnoreCase("yes"));
{
while(!al.equalsIgnoreCase("stop")) {
System.out.println();
try {
System.out.println("Type your number");
e = in.nextLine();
f = Integer.parseInt(e);
}
catch(NumberFormatException e1) {
al = in.nextLine();
if(al.equalsIgnoreCase("stop"))
break;
}
if (f < 10) {
g = (int) (Math.random() * 10);
if (f == g)
System.out.println("Congrats, you won. ");
else
System.out.println("Oops!, try again");
} else if (f>10)
System.out.println("Please enter a number between 1-10");
}
System.out.println("Thanks for playing, better luck next Time");
}
}
}
}
It does stops when I type stop, but I need to enter it two times.
Here's the run tab where I executed my program.
Do you wanna play?, type yes to start.
yes
Thanks for staring the game
-------Welcome to Need For Fun-------
Enter your name_
gourav
Is your name gourav?
If yes type yes or if not type something else
yes
So, the game is quite similar to had cricket
You will win, if your number and Computer's number are equal
To stop the game any time type start
So ready to play the game?, type yes to confirm.
yes
Type your number
4
Oops!, try again
Type your number
54
Please enter a number between 1-10
Type your number
4
Oops!, try again
Type your number
stop
3
Oops!, try again
Type your number
stop
stop
Process finished with exit code 0
change this block
catch(NumberFormatException e1) {
al = in.nextLine();
if(al.equalsIgnoreCase("stop"))
break;
}
to
catch(NumberFormatException e1) {
if(e.equalsIgnoreCase("stop"))
break;
}

java keep looping if user input is not an integer

I have tried similar codes in this site but nothing works for me. So I want the program to keep asking the user to input an integer if its not integer. If the credit card is integer then go to expiration date and if it is valid then print invoice. I tried if and while loop, also try and catch but I guess my logic is broken. Any help will be appreciated.
Scanner s = new Scanner(System.in);
System.out.println("Type 'quit' to exit payment");
System.out.println("Enter name: ");
String name = s.next();
s.nextLine();
if (name.equals("quit"))
{
return;
}
System.out.println("Enter address: ");
String address = s.nextLine();
if (address.equals("quit"))
{
return;
}
System.out.println("Type '000' to exit payment");
System.out.println("Enter card number: ");
#override
int cardNo = s.nextInt();
if (cardNo == 000)
{
return;
}
System.out.println("Enter card expiration date: (DDMMYY)");
int expirationDate = s.nextInt();
if (expirationDate == 000)
{
return;
}
//if input is ok then printing invoice
}
Try the following, I'll also note a few things afterwards about quitting your application
Scanner s = new Scanner(System.in);
String name = "", address = "";
int cardNo = 0, expirationDate = 0;
while(name == "" || address == "" || cardNo == 0 || expirationDate == 0)
{
System.out.println("Type 'quit' to exit payment");
//Get Name
System.out.print("Enter name: ");
name = s.nextLine();
if (name.equals("quit")){return;}
//Get address
System.out.print("Enter address: ");
address = s.nextLine();
if (address.equals("quit")){return;}
System.out.println("Type '-1' to exit payment");
//Get card number continually until an integer is entered
do {
System.out.print("Enter card number: ");
try {
cardNo = Integer.parseInt(s.nextLine());
break;
} catch (Exception e) {
continue;
}
} while (true);
if (cardNo == -1) {return;}
//Get card expiration date continually until an integer is entered
do {
System.out.println("Enter card expiration date: (DDMMYY)");
try {
expirationDate = Integer.parseInt(s.nextLine());
break;
} catch (Exception e) {
continue;
}
} while (true);
if (expirationDate == -1){return;}
}
You might have noticed I changed what to enter when quitting at the card number and expiration date part of the program from 000 to -1. This is because 000 converted to an int will have the value of 0, so the user would never be able to exit your application.
Remember .nextLine() gets the next element each time you call the method . so it is better to assign it to the variable before processing .
From docs ,
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line,
excluding any line separator at the end. The position is set to the
beginning of the next line.
Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the
line to skip if no line separators are present.

Try-Catch inside While Loop

The code below asks the user how many racers he/she would like.
while (true) { // loops forever until break
try { // checks code for exceptions
System.out.println("How many racers should" + " participate in the race?");
amountRacers = in.nextInt();
break; // if no exceptions breaks out of loop
}
catch (InputMismatchException e) { // if an exception appears prints message below
System.err.println("Please enter a number! " + e.getMessage());
continue; // continues to loop if exception is found
}
}
If a number is entered at amoutnRacers = in.nextInt(); the code breaks out of the loop and the rest of the program runs fine; however, when I enter something such as "awredsf" it should catch that exception, which it does. Instead of prompting the user again it loops continuously, which to me does not make sense.
The program prints like this when looping continuously:
How many racers should participate in the race?
How many racers should participate in the race?
How many racers should participate in the race?
How many racers should participate in the race?
How many racers should participate in the race?
How many racers should participate in the race?
How many racers should participate in the race?Please enter a number! null
Please enter a number! null
Please enter a number! null
Please enter a number! null
Please enter a number! null
Please enter a number! null
Please enter a number! null
...
I do not understand what is going on amountRacers = in.nextInt(); so why is the user not able to enter a number?
Just add input.next() once you catch InputMismatchException.
catch (InputMismatchException e) { //if an exception appears prints message below
System.err.println("Please enter a number! " + e.getMessage());
input.next(); // clear scanner wrong input
continue; // continues to loop if exception is found
}
You need to clear the wrong input, which scanner automatically does not.
Today i solved this problem :-) This is my code. I think that i help
public int choice () throws Exception{
Scanner read = new Scanner(System.in));
System.out.println("Choose the option from the upper list");
int auxiliaryChoiceMenu = 5;
int auxiliaryVariable = -1;
boolean auxiliaryBoolean = false;
while (!auxiliaryBoolean) {
try {
auxiliaryVariable = read.nextInt();
read.nextLine();
} catch (Exception e) {
System.out.println("incorrect data, try again"+e);
read.nextLine();
continue;
}
if (auxiliaryVariable<0 || auxiliaryVariable>auxiliaryChoiceMenu){
System.out.println("incorrect data, try again");
} else {
auxiliaryBoolean = true;
}
choiceMenu = auxiliaryVariable;
}
return choiceMenu;
//choicemenu is a external variable
}
You may need to create a Scanner class for getting standard input streamed from the keyboard. You should have a statement somewhere in your code that creates an instance of a Scanner class like: Scanner in = new Scanner(System.in);
so the " in " variable in your statement: amountRacers = in.nextInt(); waits and scans for entered input from the keyboard and stores it.
Why use a loop with a try and catch?
My advice would be to always use a try and catch with either a while or do while loop, so you can ask the user to repeat his/her input. It also depends which loop you already use and/or on how your code is structured.
For example if you already have a do while loop then I would advice you to simply adjust/modify your existing loop.
I will post some examples on how you can use a try and catch with a loop to repeat the input after a user has provided a wrong one.
See examples below:
Example 1
Scanner input = new Scanner(System.in);
int exampleInput = 0;
do {
try {
System.out.print("\nEnter an integer from 1 to 25: ");
exampleInput = input.nextInt();
}
catch (InputMismatchException e) { //if an exception appears prints message below
System.err.println("Wrong input! Enter an integer from 1 to 25");
input.next(); // Clear scanner buffer of wrong input
}
} while (exampleInput < 1 || exampleInput > 25);
System.out.println("Print exampleInput: " + exampleInput);
Example 2
Scanner input = new Scanner(System.in);
int exampleInput; // Here you don't need to initialize this variable because you don't need it as a condition for the loop.
boolean isDone = false;
do {
try {
System.out.print("\nEnter an integer: ");
exampleInput = input.nextInt();
isDone = true;
}
catch (InputMismatchException e) { //if an exception appears prints message below
System.err.println("Wrong input! Enter an integer");
input.next(); // Clear scanner buffer of wrong input
}
} while (!isDone);
System.out.println("Print exampleInput: " + exampleInput);
Example 3
Scanner input = new Scanner(System.in);
int exampleInput; // Here you don't need to initialize this variable because you don't need it as a condition for the loop.
boolean isDoneLoop2 = false;
while (!isDoneLoop2) {
try {
System.out.print("\nEnter an integer: ");
exampleInput = input.nextInt();
isDoneLoop2 = true;
}
catch (InputMismatchException e) { //if an exception appears prints message below
System.err.println("Wrong input! Enter an integer");
input.next(); // Clear scanner buffer of wrong input
}
}
System.out.println("Print exampleInput: " + exampleInput);
This works for me.
while (true) {
try {
System.out.print("Ingrese la cantidad de puestos de atenciĆ³n: ");
int puestos = Integer.parseInt(scn.nextLine());
break;
}
catch (NumberFormatException e) {
System.out.println("Ingrese un valor correcto");
scn.reset();
continue;
}
}

While loop executing once before prompt

This was a difficult question to research, so please forgive me if this is a duplicate.
Basically, I have a while loop that'll only break if a code the user scans is an integer. I check this by trying Integer.parseInt(integer) and only breaks the loop if a NumberFormatException isn't thrown.
My problem, is that when the loop executes for the first time, the exception is thrown, without any user input.
Here's my code:
Scanner input = new Scanner(System.in);
while (true)
{
System.out.print("Please scan barcode: ");
int inCode = 0;
try
{
inCode = Integer.parseInt(input.next());
}
catch (NumberFormatException e)
{
System.out.println("Numbers only, please.");
}
if (inCode != 0) {
// Do Stuff
} else {
System.out.println("Code can't be zero!");
}
}
What should happen, is this:
Please scan barcode: // And here they enter the barcode
But instead this happens:
Please scan barcode: Numbers only, please.
Please scan barcode:
EDIT:
As per Bohemian's answer, I added the continue keyword to my code. That solves the issue, but only halfway. As per the request of the people who put my question on hold (With good reason, as I now see) I'll post a SSCCE for you guys. I'm going to remove the methods for interfacing with the database, though, only keeping the path that has the problem: creating a new account based on the code.
Scanner input = new Scanner(System.in);
while (true)
{
System.out.print("Please scan barcode: ");
int inCode = 0;
try
{
inCode = Integer.parseInt(input.next());
}
catch (NumberFormatException e)
{
System.out.println("Numbers only, please.");
continue;
}
if (true) // Here it checks if an account associated with the code entered exists in the database. Because I'm having issues when it creates a new account, I've made this true.
{
System.out.println("No account associated with that code! Create one?");
System.out.print("(yes/no): ");
String answer = input.next();
if (answer.equalsIgnoreCase("yes"))
{
System.out.println("Alright.");
System.out.print("Please enter a name: ");
String name = input.next();
System.out.print("Alright. Now I'll add that to the database... ");
// Here I add that to the database. Omitted.
System.out.println("Done! Please scan again to interface.");
}
else if (answer.equalsIgnoreCase("no"))
{
System.out.println("Okay then.");
}
else
{
System.out.println("Defaulting to no.");
}
}
}
// I still haven't written the code to interface with the account.
What happens now is, it says (in the first iteration)
Please scan barcode:
But, after going through the process of adding the account, it loops again and says:
Please scan barcode: Numbers only, please.
Please scan barcode:
EDIT:
Please note, everything is inside a while loop, so that when everything that the user has done is finished, it'll return to:
Please scan barcode:
I think what you want is this:
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Please scan barcode: ");
int inCode = 0;
try {
inCode = Integer.parseInt(input.next());
if (inCode != 0) {
// Do Stuff
break;
}
} catch (NumberFormatException e) {
System.out.println("Numbers only, please.");
}
}
The code you have could be structured better, which would both make it clearer what is happening and easier to track down problems. You only want to loop on the data input - so just loop on the data input:
int inCode = 0;
while (true) {
System.out.print("Please scan barcode: ");
try {
inCode = Integer.parseInt(input.next());
break;
} catch (NumberFormatException e) {
System.out.println("Numbers only, please.");
}
}
// Do stuff
You should consider using scanner.hasNextInt() and scanner.nextInt() rather than scanner.next() though. This will also avoid the need for using the exception like this. Normally using Exceptions to control program flow is a bad idea - really they should be used for handling exceptional circumstances. Integer.parseInt doesn't give you any alternatives, but scanner does.
After the edits, it's clear what the problem is: your while (true) loop doesn't have a break statement in it, so it will keep looping forever.
Personally, I'd suggest moving most of your code out of the loop, and only keeping the barcode-parsing code in it, e.g. like this:
int inCode;
while (true) {
System.out.print("Please scan barcode: ");
try {
inCode = Integer.parseInt(input.next());
if (inCode == 0) {
System.out.println("Code can't be zero!");
} else {
break; // we got a valid barcode! end the loop and move on...
}
} catch (NumberFormatException e) {
System.out.println("Numbers only, please.");
// no need for a "continue" here, since the loop will restart anyway
}
}
// rest of the code here...
or possibly even:
int inCode;
while (true) {
System.out.print("Please scan barcode: ");
try {
inCode = Integer.parseInt(input.next());
} catch (NumberFormatException e) {
System.out.println("Numbers only, please.");
continue;
}
if (inCode == 0) {
System.out.println("Code can't be zero!");
continue;
}
break; // we have a valid barcode! end the loop and move on...
}
// rest of the code here...
I would just continue the loop if there's bad input, then you don't need to test it later:
while (true) {
System.out.print("Please scan barcode: ");
int inCode = 0;
try {
inCode = Integer.parseInt(input.next());
} catch (NumberFormatException e) {
System.out.println("Numbers only, please.");
continue; // ADDED THIS LINE
}
// Do Stuff with inCode
}
Note that by your code testing for zero after the input, you preclude zero as valid input. This code allows any number, including zero. Small point, but there's no worries about edge cases.
You can try this
String in=null;
while (true) {
System.out.print("Please scan barcode: ");
int inCode = 0;
try {
in= input.next();
inCode=Integer.parseInt(in);
} catch (NumberFormatException e) {
System.out.println("Numbers only, please.");
}
if (inCode != 0) {
// Do Stuff
} else {
// Repeat loop
}
or you can directly read an integer through Scanner object instead of using Integer.parseInt() method.
int inCode=0;
while(true) {
System.out.print("Please scan barcode : ");
inCode=input.nextInt();
if(inCode!=0){ //do stuff }
else { //Repeat Loop }
}

How to make a scanner be able to take in both an INT and String. Java

I had a bit of a hard time figuring this part out for a school project of mine.
So looking for a bit of clarification.
Generally, the user had to input a number (column) to insert a game piece.
However, if the user were to enter "q" the program would close down.
We were pointed into the direction of using "parseInt", however i am looking for a bit of clarification as to how this works?
while(response.equalsIgnoreCase("q"));
{
System.out.println("Do you want to play again?");
response = scan.next();
}
System.out.println("Do you want to play again?");
response = scan.next(); // this revisits the while loop that
// prompted the player to play.
import java.util.Scanner;
public class ScanInteger {
public static void main(String...args)throws Throwable {
int num = 0; String s= null;
System.out.print("Please enter a number : ");
Scanner sc = new Scanner(System.in);
do{
try{
s = sc.next();
num= Integer.parseInt(s);
System.out.println("You have entered: "+num+" enter again : ");
}catch(NumberFormatException e){
if(!s.equalsIgnoreCase("q"))
System.out.println("Please enter q to quit else try again ==> ");
}
}while(!s.equalsIgnoreCase("q"));
sc.close();
}
}
See http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
public static int parseInt(String s)
throws NumberFormatException
You want to apply a try-catch block around the Integer.parseInt(userInput) call to catch a NumberFormatException
In the catch body, you can set a flag that the input was invalid. Put the whole thing in a while loop based on the boolean isInputIsValid.
boolean isValidNumber = false, wantsToQuit = false;
while (!isValidNumber) {
// Ask user for a value any way you want and save it to userInput
String userInput = "";
try {
Integer.parseInt(userInput);
isValidNumber = true;
} catch (NumberFormatException e) {
isValidNumber = false;
if (userInput.equals("q")) {
wantsToQuit = true;
break;
}
}
}
wantsToQuit is not a necessary variable, just showing what the purpose of that section is

Categories