How to let the user input back to the former question - java

I write a code to let the user input cruise id first and then enter the ship name.
At first, I want to detect whether the user input integer type, if not, the user has to re-enter the first question again.
But in my code, it will directly print the second question instead of go back to the first question and ask again. Same, for the second question, I also want it return back and ask user to input again if the input is wrong
Please help me for that. Thanks!!
try{
System.out.println("Input Cruise ID:");
sc1 = sc.nextInt();
}catch(Exception e){
System.out.println("Please Enter integer:");
sc.nextLine();
}
System.out.println("Input ship name :");
try{
sc2 = sc.next();
}catch(Exception e){
if( sc2 != "Sydney1" || sc2 !="Melmone1"){
System.out.println("Oops!! We don't have this ship!! Please enter the ship name : Sydney1 or Melbone1");
}
}

I write a code to let the user input cruise id first and then enter the ship name. At first, I want to detect whether the user input integer type, if not, the user has to re-enter the first question again.
What you need is an input validation. try-catch block itself will not create an endless loop to reprompt the user should the input is not an integer. What you need is a while loop.
You can use a do-while loop as follows so that it runs first before performing a check:
String input = ""; //just for receiving inputs
do{
System.out.println("Input Cruise ID:");
input = sc.nextInt();
}while(!input.matches("[0-9]+")); //repeat if input does not contain only numbers
int cruiseID = Integer.parseInt(input); //actual curiseID in integer
To perform validation for your second input (i.e, your shipName, you need another while loop which encloses your prompt for input).
try-catch block are mainly used to handle exceptional cases. Try not to misuse it as a control statement for your implementations.

You can add more checks inside the while loop itself. For example, checking if the number is a negative number or zero etc. For example
while (true) {
try {
System.out.println("Input Cruise ID:");
cruiseId = sc.nextInt();
if(cruiseId <=0){
System.out.println("Please Enter integer:");
sc.nextLine();
}
break; // break when no exception happens till here.
} catch (Exception e) {
System.out.println("Please Enter integer:");
sc.nextLine();
}
}

Related

How to Loop the prompt for user input if it is not a unique value in an ArrayList?

I am trying to have users input a UNIQUE value for a book's ISBN.
I am able to receive user input and it populates the ArrayList just fine, but if a user inputs a value that is already in the ArrayList, I want them to receive an error message and be prompted to try again.
do{
System.out.print("\n ISBN must be 4 numbers only.\nEnter isbn: ");
isbn = sc.nextLine();
try{
isbnInt = Integer.valueOf(isbn);
}//end try
catch(NumberFormatException nfe){
System.out.println("\nPlease enter integer numbers only.");
}//end catch
}while(isbn.trim().length() <4 && (isbn.trim().length()>0) || (isbn.trim().length() >4));
sc = new Scanner(System.in);
System.out.println();
do{
System.out.print("Enter quantity: ");
quantity = sc.nextLine();
try{
quantityInt = Integer.valueOf(quantity);
}//end try
catch(NumberFormatException nfe){
System.out.println("\nPlease enter integer numbers from 1 through 1000 only.");
}//end catch
}while(quantity.trim().length() > 1000 ||(quantity.trim().length()<0) );
Create a method to validate ISBN such as
public boolean verifyISBN(int ISBN)
Here you will check if ISBN exists in the arraylist by using a for loop
Upon receiving the return value store it in a variable and use in while condition of 1st do-while loop.
I think you're in need of a different data structure, like HashSet, because it doesn't allow duplicates.
When calling the add method:
hashSet.add(quantityInt);
It verifies if the HashSet already contains that element.
if it contains: it'll not insert the element and will return false;
if it doesn't contain: it'll insert the element and will return true.
You can check if the method returned false and if so, show an error message and enable the input again.
...
final Set<Integer> set = new HashSet<>();
int quantityInt = scanner.nextInt();
while(!set.add(quantityInt)) {
System.out.println("You can't insert duplicate elements.");
quantityInt = scanner.nextInt();
}
...
I feel like I am dialing in on it. Unfortunately I am required to use an ArrayList for the assignment.
I have a while loop setup with a boolean operator "contains"
while(contains != books.contains(isbnInt)){
But it isn't working

user input within while loop

I was asked to run a loop that asks for user input, applies the change using the adjustPrice() method, print the new information after adjusting the price. and then finishes the loop when the user enters 0.
Right now it does all of the above, just doesn't ask for the user input again and ends with the printed new information. please help!
boolean done = false;
while (!done) {
System.out.print("Enter adjustment to price in percent (0 to quit): ");
double adjustment = in.nextDouble();
if (adjustment == 0) {
done = true;
}else{
swag.adjustPrice(adjustment);
System.out.println(swag.toString());
in.next();
}
}
You have in.next() at the end. This expects the user to input something before the loop will reset to the System.out line. Take out that line.
to allow user input using the end
else {
swag.adjustPrice(adjustment);
System.out.println(swag.toString());
in.next();
}
but beware that this method does not take keys as enter or space to
take into account these keys use.
else {
swag.adjustPrice(adjustment);
System.out.println(swag.toString());
System.in.read();
}

Scanner type checking in method [duplicate]

I have read user input that must be only of type int, the problem comes when the user enters letter instead of a int. I know how to handle the exception, but I would like to return the scanner read where the user has made a mistake. How can I do?
I already tried with an infinite loop, but it does not work.
try{
System.out.print("enter number: ");
value = scanner.nextInt();
}catch(InputMismatchException e){
System.err.println("enter a number!");
}
While other answers give you correct idea to use loop you should avoid using exceptions as part of your basic logic. Instead you can use hasNextInt from Scanner to check if user passed integer.
System.out.print("enter number: ");
while (!scanner.hasNextInt()) {
scanner.nextLine();// consume incorrect values from entire line
//or
//tastiera.next(); //consume only one invalid token
System.out.print("enter number!: ");
}
// here we are sure that user passed integer
int value = scanner.nextInt();
A loop is the right idea. You just need to mark a success and carry on:
boolean inputOK = false;
while (!inputOK) {
try{
System.out.print("enter number: ");
numAb = tastiera.nextInt();
// we only reach this line if an exception was NOT thrown
inputOK = true;
} catch(InputMismatchException e) {
// If tastiera.nextInt() throws an exception, we need to clean the buffer
tastiera.nextLine();
}
}

Back scanner reading after user error - java

I have read user input that must be only of type int, the problem comes when the user enters letter instead of a int. I know how to handle the exception, but I would like to return the scanner read where the user has made a mistake. How can I do?
I already tried with an infinite loop, but it does not work.
try{
System.out.print("enter number: ");
value = scanner.nextInt();
}catch(InputMismatchException e){
System.err.println("enter a number!");
}
While other answers give you correct idea to use loop you should avoid using exceptions as part of your basic logic. Instead you can use hasNextInt from Scanner to check if user passed integer.
System.out.print("enter number: ");
while (!scanner.hasNextInt()) {
scanner.nextLine();// consume incorrect values from entire line
//or
//tastiera.next(); //consume only one invalid token
System.out.print("enter number!: ");
}
// here we are sure that user passed integer
int value = scanner.nextInt();
A loop is the right idea. You just need to mark a success and carry on:
boolean inputOK = false;
while (!inputOK) {
try{
System.out.print("enter number: ");
numAb = tastiera.nextInt();
// we only reach this line if an exception was NOT thrown
inputOK = true;
} catch(InputMismatchException e) {
// If tastiera.nextInt() throws an exception, we need to clean the buffer
tastiera.nextLine();
}
}

Scanner.reset() doesn't work

This piece of code is supposed to get an integer number from user and then finish the program. If the user inputs an invalid number, it asks user again.
After catching exception, it uses Scanner.reset() to reset the scanner, but it doesn't work. and it re-throws previous exception.
Scanner in = new Scanner(System.in);
while (true) {
try {
System.out.print("Enter an integer number: ");
long i = in.nextLong();
System.out.print("Thanks, you entered: ");
System.out.println(i);
break;
} catch (InputMismatchException ex) {
System.out.println("Error in your input");
in.reset(); // <----------------------------- [The reset is here]
}
}
I thought Scanner.reset() will reset everything and forget the exception. I put it before asking the user for a new input.
If I get the point wrong, what is the right way?
You misunderstood the purpose of the reset method: it is there to reset the "metadata" associated with the scanner - its whitespace, delimiter characters, and so on. It does not change the state of its input, so it would not achieve what you are looking for.
What you need is a call of next(), which reads and discards any String from the Scanner:
try {
System.out.print("Enter an integer number: ");
long i = in.nextLong();
System.out.print("Thanks, you entered: ");
System.out.println(i);
break;
} catch (InputMismatchException ex) {
System.out.println("Error in your input");
in.next(); // Read and discard whatever string the user has entered
}
Relying upon exceptions to catch exceptional situations is OK, but an even better approach to the same issue would be using has... methods before calling the next... methods, like this:
System.out.print("Enter an integer number: ");
if (!in.hasNextLong()) {
in.next();
continue;
}
long i = in.nextLong();
System.out.print("Thanks, you entered: ");
System.out.println(i);
break;
Per Scanner.reset() javadoc, the method only "resets" locale, radix and delimiter settings. It does not do anything to the data it already read.

Categories

Resources