Java. Scanner Trying to to a loop until user quits - java

I've been trying to make a while loop where I enter in a movie number until the user types 'q' for quit, but every time I enter a valid number, I have to enter it twice before it prompts me with the "Enter movie number" message again. And the break function doesn't work when I wish to leave the loop. I simply wish to enter in the movie number once and break out when I want to.
public class Main {
public static void main(String[] args) {
while(true)
{
System.out.println("Enter in movie number: ");
Scanner input = new Scanner(System.in);
if(!input.hasNextInt())
{
System.out.println("invalid input");
continue;
}
if (Integer.parseInt(input.next()) < 0)
{
System.out.println("invalid no negative numbers");
continue;
}
if(Objects.equals(input.next(), "q"))
break;
}
}
I tried other variations of the while loop, but a similar thing has happened.

I assume your intention is to get one line of input, and if it is a number, process it somehow, and if not check if the user wants to quit.
You've got a couple problems with your program, firstly, you're creating a new Scanner within the while loop, which creates unnecessary overhead. Second, you're trying to get 2 lines of input within your loop, you wait for the user to input an integer, then you try to parse that integer with input.next(). Afterwards, you call input.next() again to check if the user wants to quit. By calling next() twice, you're requiring the user to input 2 lines, causing the issue you were describing.
You can fix this by calling next() once and storing its return value in a variable, then check if it equals q for quit, otherwise you can parse an integer value from it.
Here is working code that applies fixes to these issues:
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.println("Enter in a movie number:");
// Get user input
String input = scanner.next();
// If the input equals q, we break out of the loop
if(input.equalsIgnoreCase("q")) break;
int intInput;
try {
// Get integer input
intInput = Integer.parseInt(input);
} catch(NumberFormatException e) { // Input was not a number
System.out.println("Invalid, must input a number");
continue;
}
if(intInput < 0) {
System.out.println("Invalid, no negative numbers");
continue;
}
}
}
}
Also, a small note, instead of using Object.equals to check if two strings are equal you can just use the equals method inside of the String class like so: str1.equals(str2).

Related

Teach me why this code fails to check if my input is a int, and how I can fix it

import java.util.Scanner;
public class HelloWorld {
public static int num;
public static Scanner scan;
public static void main(String[] args) {
System.out.println("Hello World");
/* This reads the input provided by user
* using keyboard
*/
scan = new Scanner(System.in);
System.out.print("Enter any number: ");
// This method reads the number provided using keyboard
check();
// Closing Scanner after the use
// Displaying the number
System.out.println("The number entered by user: "+num);
}
public static void check(){
try{
num = scan.nextInt();
}
catch (Exception e){
System.out.println("not a integer, try again");
check();
}
}
}
Im new to coding, and am taking this summer to teach myself some basics. I was wondering if someone could advise me on how I can create this method to take in a int, and check the input to make sure thats its a int. If the input is not a int, I would like to re run in.
Simple. Say you have something as shown below . . .
NumberThing.isNumber(myStringValue);
.isNumber() determines if your string is a numerical value (aka a number). As for putting the code in a loop to continue to ask the user for input if their input is invalid, using a while loop should work. Something like . . .
while (. . .) {
// use something to exit the loop
// depending on what the user does
}
You might consider moving the user request code to the check method. Also, use a break statement to exit your while loop after a valid number is entered.
while ( true )
{
System.out.println( "Enter an integer.");
try
{
num = scan.nextInt();
break;
}
catch (Exception e)
{
System.out.println("not a integer");
}
}

How to have check user input using scanner without having scanner prompt multiple times

So im writing a couple methods that require the user to input what hour(1-24) they want. I need however to check whether they enter in an int, and a number between 1-24. The problem is that the scanners are called multiple times if sent to the error statement. I don't know how to do this without having these issues.
public static int getHour(Scanner scan){
int hour=0;
System.out.println("Enter the hour for the showtime (1-24):");
do{
if((!scan.hasNextInt())||((hour=scan.nextInt())<1)||(hour>24)){
System.out.println("Enter a valid number");
scan.next();
} else{
return hour;
}
}while((!scan.hasNextInt())||(hour<1)||(hour>24));
return hour;
}
Ideally it only prompts one time when entering in a not valid input such as a string or int outside of 1-24. but it prompts twice or sometimes once depending on the order of what incorrect input you put in.
Any help would be appreciated, thanks
You're encountering this problem because .hasNextInt() does not advance past the input, and .nextInt() only advances if translation is successful. A combination of loops and if-statements can thus cause confusion as to whether or not the scanner will advance. Here's your method rewritten to have the scanner prompt only once for each bad input:
public int getHour(Scanner scan) {
System.out.printf("%nEnter the hour for the showtime (1-24): ");
while (true) {
input = scan.next();
entry = -1;
try {
entry = (int)Double.parseDouble(input);
} catch (NumberFormatException e) {
// Ensures error is printed for all bad inputs
}
if (entry >= 1 && entry <= 24) {
return entry;
}
System.out.printf("%nEnter a valid number: ");
}
}
I prefer to use an infinite loop in this case, but as that can be dangerous, receive it with caution. Hope this helps!

hasNextInt won't return false and exit the loop

I'm trying to put user input into an array but the hasNextInt() method will not return false and stop the input.
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
int target = in.nextInt();
while(in.hasNextInt()) {
weights.insert(in.nextInt());
}
recKnapSack(target, 0);
}
Scanner.hasNextInt() will return false when it encounters a non-integer character in its buffer.
However, it may strip out whitespace when it's reading prompts. So Space+Enter or Enter will most likely not stop the loop. But any other character will.
Since you'd like to input any number of ints, you must instruct the user on what to type when they're done. In fact, if you're writing a console application, it's a good idea to always explain WHY a program is waiting for input.
Any non-integer will stop the loop condition. In this case the syntax will work as-is, the user just needs some instruction:
System.out.println("Please enter the target");
int target = in.nextInt();
System.out.println("Enter weights. Type 'X' to stop");
while(in.hasNextInt()) {

Display an error message for the non-numeric input

So this is my code i dont know what to add if i want to display invalid message for the non numeric inputs please help ty
import java.util.Scanner;
public class Date
{
public static void main (String args [])
{
int x;
Scanner in = new Scanner (System.in);
System.out.print("Enter a date ");
x = in.nextInt();
while (x < 1520 || x > 3999)
{
System.out.println ("Invalid Gregorian Calendar date.");
System.out.print ("Please Input a valid Gregorian Calendar date: ");
x = in.nextInt();
}
System.out.println("Good");
Use a try catch block, and put x = in.nextInt(); inside it
I've changed your code a bit. I think this is what you were aiming for.
I'm not that good in explaining but I try to tell what I did.
First of all I got rid of your in.nextInt() since this is very restrictive. It does only accept an integer and will throw an exception if you type something else in. Normally this would be OK, but since you want the user to be able to correct the input, this will cause more troubles than it would solve.
I then put your code into an infinite loop while(true) which assures, you do not have to restart your application again once you've typed in a wrong value.
What is going on within the loop is quite simple. The console prints out what you want the user to do and reads the consoles input as a String, so you don't have to face any exceptions in the first place.
I then try to parse the given String into an integer value. I added trim() to kill leading spaces as well as trailing, so I won't have to deal with users being confused by typing in numbers with a space since they don't directly see whats wrong when getting their "not an integer" error. This would be thrown, if the input contains spaces.
Now I check whether or not the given integer-value fits your specifiation. I don't need a loop here, so I changed it to be a simple if-statement.
If the value is wrong (or lets say the if (x < 1520 || x > 3999) returns true) I'm going to print out your error message. Since we already passed casting the String input into the integer and we do not reach the else-branch we now return back to the beginning of our loop with printing out the request again before waiting for a new input to be made.
Now, as soon as the user typed in another value, e.g. 2011 (which is valid based on your specification) we will now reach the else-branch which prints the "Good" and leaves the loop by calling break. And since there is nothing left to do for the application it will stop running. If you want the user to be able to type in new values in the positive case, you simply have to remove the break-statement.
If the user types in a value which is not an integer, the cast will fail and throw a NumberFormatException. We catch this exception by surrounding the cast with the try-catch-block and print out the integer-error once we've reached the catch-block.
Then the application reacts the same way like if you typed in a wrong number and we will return to the beginning of the loop again.
The reason for putting a try-block around the Scanner is to handle closing.
import java.util.Scanner;
public class Date {
public static void main(String args[]) {
String input = "";
int x = 0;
try (Scanner in = new Scanner(System.in);) {
while (true) {
System.out.print("Please Input a valid Gregorian Calendar date: ");
input = in.nextLine();
try {
x = Integer.parseInt(input.trim());
if (x < 1520 || x > 3999) {
System.out.println("Invalid Gregorian Calendar date.");
}
else {
System.out.println("Good");
break;
}
} catch (NumberFormatException e) {
System.out.println("Given value \"" + input.trim() + "\" is not an integer.");
}
}
}
}
}
The Scanner class has a method for this
Scanner in = new Scanner(System.in);
int x;
if(in.hasNextInt()){
x = in.nextInt();
System.out.println("Valid number");
}else{
System.out.println("Not a number");
}
To keep prompting until a valid number is entered
int x;
System.out.println("Enter a number: ");
while(!in.hasNextInt()){
System.out.println("Invalid number, try again: ");
key.nextLine(); // Flush out invalid number
}
x = key.nextInt();

how to avoid pressing several time enter affects the input data?

I'm writting a JAVA Class to validate input data, especifically integer numbers.
The class I develop is running fine but when I press more than one time enter and then a char type, it display several times " Error!! Invalid number. Try again. " and I would like to avoid it.
I have use nextLine() method but it doesn't seems to correct it.
Here is the Class:
package chapter07.libro;
import java.util.Scanner;
public class Validator_integer
{
public static int getInt (Scanner scanner, String promt)
{
int numberInteger = 0;
boolean isValid = false;
System.out.println(promt);
while(isValid == false)
{
if(scanner.hasNextInt())
{
numberInteger= scanner.nextInt();
isValid = true;
}//if
else
{
System.out.println("Error!! Invalid number. Try again.");
}//else
scanner.nextLine();
}//while
return numberInteger;
}//getInt
}//Validator_integer
and next is the app to use the class:
package chapter.prueba;
import java.util.Scanner;
import chapter07.libro.Validator_integer;
public class Test_Validator_Integer
{
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
String choice = "y";
while(choice.equalsIgnoreCase("y"))
{
int number = Validator_integer.getInt(sc, "Enter integer number: ");
System.out.println(number);
System.out.println("Continue (y/n): ");
choice = sc.next();
}//while
}//main
}//Test_Validator_Integer
The results I get are next:
Enter integer number:
2
2
Continue (y/n):
y
Enter integer number:
(Here I press several time enter)
xx
Error!! Invalid number. Try again.
Error!! Invalid number. Try again.
Error!! Invalid number. Try again.
Error!! Invalid number. Try again.
2
2
Continue (y/n):
n
So the part of (Error!! Invalid number. Try again.) displayed several times, is the one I would like to avoid.
Does any one know how to fix it???
Thanks in advance!!!
Before you read from System.in, make sure to "clear" it's contents to get rid of buffered/queued-up input. If there are n characters queued-up, then skip that many chars and you'll need to enter something new.
int n = System.in.available();
System.in.skip(n);
http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html

Categories

Resources