Java - if/else fails immediately when supposed to pause - java

I'm having troubles with a function in java. Here's my code:
do{
System.out.print("Proceed to payment? (y/n) ");
input = scan.nextLine();
if((input.trim()).equals("y")){
break;
}
else if((input.trim()).equals("n")){
System.out.print("Come back next time, " + name + ".");
System.exit(0);
}
else{
System.out.println("Invalid response. Try again.");
}
}
while(true);
Basically, the first time the function loops it 'skips' the "input = scan.nextLine" and immediately prints "Invalid response. Try again." to the terminal. It then allows the user to input something, and works normally.
Yes, I have declared input, scan (java.util.Scanner;), and name earlier in my code. It'd be a great help if someone can point out what I've done wrong! Thanks!

While adding scan.nextLine() before does help, I keep a general rule of setting the delimiter whenever I initialize the Scanner class by using:
scan.useDelimiter("\n");
in this case, which uses a newline as a delimiter. As a result, for all the methods of scan, whenever the user presses Enter, it is interpreted as the end of the input. This includes, nextInt(), nextDouble(), next()etc...
Using the delimiter also means that I don't have to add scan.nextLine() after every non-nextLine() input.

You probably called scan.next(), or something like that, before entering the do-while loop. That left a next line character in the input, and the call to scan.nextLine() consumed it. To fix it, you could place a scan.nextLine() call right after scan.next() so it will consume the next line before entering the loop.
For example:
Scanner scan = new Scanner(System.in);
String input;
String name = scan.next();
scan.nextLine();
do {
System.out.print("Proceed to payment? (y/n) ");
input = scan.nextLine();
// rest of the code
}
while(true);

Related

How to skip control when we are using scanner readLine() when user is nothing entered from keyboard?

My code is :
System.out.print("press key Y or N to run the test");
Scanner sc = new Scanner(System.in);
String input = null;
input = sc.nextLine();
There is nothing you can do. nextLine() waits for the user to press "Enter" on the keyboard; it will block forever until that happens.
If you really want that things happen "automatically", you will need a more complex solution; for example you can wait for user input in a separate thread; and if there is no input after a given amount of time, your other thread can start doing "whatever" "automatically".
Please tell the user to hit return after his input and check for empty lines like this:
if("".equals(input)){ //skip control
}
else{ //do something on input
}

Java scanner - can't read user input

I want to read user input like: 11 12 13 14 15 16
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
System.out.println(sc.next());
}
System.out.println("Test");
but it newer goes out of while loop and prints "Test".
How could i read that input?
The method hasNext() works like this:
If it sees the end of the file, it returns false;
If it sees another valid, non-whitespace input, it returns true;
If neither of the above is true, it waits for the next input the user is going to enter, and doesn't return until he does.
Usually, if you use Scanner for files, such a loop will work correctly, because a file has a definite end, and it usually doesn't get stuck waiting for more input.
But when you are working with console input (System.in, not redirected), then usually the user does not send the end-of-file signal. He just presses Return, and so, hasNext() sits and waits to see if the user will enter more input on the next line and so on.
There are two general ways to deal with this:
The user has to actually terminate the input. After you finish entering all your numbers and press Return, you also need to send the end-of-file sequence, which is usually ctrlD or ctrlZ.
If you do that, you will not be able to enter any more input to that program.
The program tells the user to enter some particular value that will tell it that the input is over. For example, the string "DONE". When you do that, you have to change the loop to something like:
String nextInput;
while( sc.hasNext() && ! (nextInput = sc.next()).equals( "DONE" ) ){
System.out.println(nextInput);
}
You can break the loop depending whether you want to quit or not E.g.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String next = sc.next();
if (next.equals("q")) { //if user press q then break the loop
break;
}
System.out.println(next);
}
System.out.println("Test");
}
Use api like:
while(sc.hasNextInt()){
int aba= sc.nextInt();
if (aba == 0) {//or even non numeric value here would let this loop exit
break;
}
}
So you need to enter 0 or even in other way enter non numeric value inorder to come out of loop. nextLine method will read whole line just once and then you will need to parse it and then convert to integer so it's good to use sc.nextInt which will do the work for you.

How does one fix the nextLine() command so that it does not take the remaining "/n" when you press enter?

I have a couple nextLine satements prior to the ones I'm having issues with.
System.out.println("Welcome to the game of BlackJack!");
System.out.println("Would you like to play? (Y/N)");
play = in.nextLine();
gameResponse = false;
while (gameResponse == false)
{
//if satements, no nextLine under them
else
{
System.out.println("Invaild response. Enter Y for yes or N for no.");
play = in.nextLine();
}
A few lines later, I have this line of code:
hitResponse = false;
while (hitResponse == false)
{
System.out.println("Would you like to take a hit(H) or stand(S)?");
String hitStand = in.nextLine();
The console prints out:
Would you like to take a hit(H) or stand(S)?
Invaild response, please enter either 'h' or 's'
Would you like to take a hit(H) or stand(S)?
any help is appriciated :)
Use one extra in.nextLine() to consume "\n"
It seems that execution hits the hit stand input code with a newline in the input buffer, probably with just a newline.
The simplest approach is to read all input as a string using Scanner#next(), which will automatically deal with (and consume) the newlines.
Using the various input-sensitive scanner methods such as nextInt() for reading human input is a bad idea; leading only to brittle and verbose code.

I need to make Scanner check to see if input is "quit", and then if it's not, accept an integer

I'm trying to write a program that gets an integer from the user, but also ends the program if the user enters "quit". When I run the program, it works when I enter "quit", but when I start entering an integer, I get a blank line. If I enter the integer the second time, it works. I have tried several suggestions that I have found for similar problems - including try/catch, parsing the input to Integer, and firing a blank Scanner#nextLine or Scanner#nextInt (and going back and forth between all of these options). Here is an example of my latest attempt. Any insight would be appreciated.
int colInput;
System.out.println(", please pick a column in which to place your token (1-8).");
System.out.println("(Type 'quit' to exit the game or 'restart' to start over.)");
System.out.print("Column Choice: ");
Scanner selectCol = new Scanner (System.in);
try {
if (selectCol.next().equals("quit"))
Connect4.close();
}
finally {
colInput = selectCol.nextInt();
}
String input = selectCol.next();
int colInput;
if (input.equals("quit"))
Connect4.close();
else
colInput = Integer.parseInt(input);
//Use colInput here or return colInput or whatever you wish to do with it
In the code you mention you are consuming the "next token" found by your scanner in the line
if (selectCol.next().equals("quit"))
the token is received and compared against "quit". No matter what the value of the token originally was it is lost afterwards. Then later in the finally block you ask your scanner for a new token. He is then waiting for a new value from System.in.
To receive the token from the scanner only if it matches "quit" you should change the line to
if (selectCol.next("quit"))
This way you are making use of a method offered by the Scanner class javadoc for next(String).

While-loop termination

If I comment out the line garbage = scan.nextLine();, the while-loop runs infinitely. Otherwise, it does not. I understand why it will run infinitely if there were only the print command, but I don't completely understand how the inclusion of the garbage variable stops it from running infintely. Can someone explain please?
import java.util.Scanner;
public class TypeSafeReadInteger
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
String garbage;
System.out.print("Enter age as an integer > ");
while (! scan.hasNextInt())
{
garbage = scan.nextLine();
System.out.print("\nPlease enter an integer > ");
}
int age = scan.nextInt();
System.out.println("Your age is " + age);
}
}
garbage is just a variable, what 'stops' the while loop is the nextLine() It is a method that waits for user input. The while doesn't continue until your user inputs something using a keyboard and saves the input into the garbage variable.
You need to know two things:
hasNextLine() does not advance the Scanner instance.
nextLine() does advance the Scanner instance.
By "advance the Scanner instance", I mean "consume" input. Think of input as a stream, and think of a scanner object as something that is consuming that stream.
Things in a normal stream can only be consumed once. You captured your's in a variable called garbage, but you could just as easily have called scan.nextLine() without storing the result. I strongly advise you to read the Javadoc on Scanner to see which methods advance the Scanner instance and which do not.
To fix your code:
while (!scan.hasNextInt())
{
scan.nextLine(); // the order of the lines inside the loop makes the difference!
System.out.print("\nPlease enter an integer > ");
// when you perform nextLine() here - you reach the beginning of the loop
// without a token in the scanner - so you end up looping forever
}
int age = scan.nextInt();
By the way - as you can see from the example above, garbage is redundant.
If the user inputs an integer, then everything works. If they don't, then you get the infinite loop without the garbage = scan.nextLine(); line due to the way the Scanner class works.
When you do something like scan.hasNextInt();, no characters are actually read from the input. So if a user input something like "cat" in response to your prompt, then the input would be paused just before the first letter of that word. Since you are looping until there is an integer in the input, nothing further is read and you will loop infinitely because "cat" is just sitting in the input buffer.
By adding in the scan.nextLine() you will cause the Scanner to discard everything up to when the user hit <enter> and additional input could be processed.

Categories

Resources