I have made a program which is like a vending machine!
My code is similar to:
public static void main (String [] args) {
Scanner sc = new Scanner (System.in);
while(sc.hasNext()) {
String string = sc.next();
sum = generateSum(sum)
.....
}
}
public static int generateSum(int sum) {
Scanner sc = new Scanner (System.in);
while (sc.hasNext()) {
....
}
return sum;
}
Sorry for simplifying my code, but the normal one is very long! However, the problem is that I use while (sc.hasNext()) loop twice. Basically I want to continue my main method until the input from the user is TERMINATE, but my program terminates after running once.
I figured that if I take out my generateSum method, then the loop in my main method works fine so i guess it has to be something to do with have the while (sc.hasNext()) loop twice.
Any ideas how I can fix the problem?
The hasNext() method is going to block until you hit the end of file marker on System.in because it doesn't know if there's more input until it reads a full buffers worth or hits end of file (which you can signal with Control-Z on windows and Control-D on unix). At that point System.in is at the EOF mark and there's no way to re-open it from your code.
If you need to process multiple streams of data from System.in you are going to have to use some sort of sentinel value (such as the word END) to mark the end of one input stream and the beginning of another.
I'm quite sure that if you consume the input being scanned with sc.next() the state changes and hasNext() returns accordingly.The problem may be there.
The hasNext() method can be called as much as you want. But if in the inner loop you are calling the next() method, then that can eat the values from your outer loop.
So the inner loop most probably breaks after hasNext() is false and thus the outer loop also finishes.
Related
Obviously, my real code is more complex, but here's an example:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in).useDelimiter("\n");
String[] cmdSplit = null;
while (true) {
while (input.hasNext()) {
cmdSplit = input.next().split("\\s+");
System.out.println("stuff");
}
for (int i = 0; i < cmdSplit.length; i++) System.out.println(cmdSplit[i]);
}
}
}
In the above example, the code takes input from System.in, splits it, and should output each piece. However, for some reason, the code after the inner while loop never executes. If I replace while with if, it works. If you test it, you can see it doesn't run infinitely, because it only prints "stuff" once, showing the loop runs once. What is the issue with the while loop?
Reading from System.in is different than reading from a file or other fixed-size source of input. The input doesn't necessarily exist until you create it, and so attempts to read it need to block until the input actually arrives (i.e. you type it). Try typing another line - you'll see the stuff message again; that will allow .hasNext() to return because there is now input.
To have .hasNext() return false the input source needs to be closed. For a command line application you can do this by sending the EOF signal (Ctrl+D on Linux) which tells the process stdin has no more input. That's not generally how you want a program to work, though, so if your intent is to only read one line and then move on, you should in fact be using an if instead of a while as you've tried to do. Later if you need to read more input you'll call .hasNext() again and your program will block there until the user passes more input.
As #user7 mentions your outer while (true) combined with while(input.hasNext()) is redundant. If you want to read only once get rid of the while (true) and use if (input.hasNext()). Otherwise if you want to read forever just combine the two loops:
while (input.hasNext()) {
cmdSplit = input.next().split("\\s+");
System.out.println("stuff");
for (int i = 0; i < cmdSplit.length; i++) System.out.println(cmdSplit[i]);
} // Loop will terminate once stdin is closed, e.g. by the user sending EOF.
Yes , your code won't go to the for loop because the Scanner.hasNext() will always listen to the console for inputs.
You have to break the loop in order to come out and go to the for loop.
Scanner input = new Scanner(System.in).useDelimiter("\n");
String[] cmdSplit = null;
while (true) {
while (input.hasNext()) {
cmdSplit = input.next().split("\\s+");
System.out.println("stuff");
break;
}
for (String element : cmdSplit) {
System.out.println(element);
}
}
The reason it is printing "stuff" only one time is because the hasNext() returned false.
Let me explain what I have observed.
To get "stuff" printed indefinately the assignment has to be removed. meaning once you assigned the input the scanner does not have any more token
The java.util.Scanner.hasNext() method Returns true if this scanner has another token in its input.
This will print indefinitely
while (input.hasNext()) {
// cmdSplit = input.next().split("\\s+");
System.out.println("stuff");
}
public class Test1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
System.out.println("First name: ");
String fname =sc.next();
System.out.print("Last name: ");
Lname = sc.next();
}
}
I'm just a beginner at java, hope someone can help me out please. Ignore the last print line i used it so i could understand what exactly i can ouptut.
without the while loop i get the correct output i expect of the code, but once i add the while(sc.hasnext)
a scanner comes before the first name and ignores the scanner that used to input the first name. Does the hasNext() skip scanner?
From the documentation of Scanner.hasNext():
Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.
This means that the while loop which you add will wait until you write something. After you write something, it will be read for first name and it will continue on. When you fill all the data it will wait again to write something and basically loop for ever.
You need other condition for the loop. For example you can use do while and after last data is written, you can ask the user additional question whether he wants to add something else. E.g:
do {
// gather data
System.out.println("Continue ?");
String c = scanner.next();
} while("yes".equals(c))
It's not actually ignoring or skipping the scanner for first name (variable fname), but in your case, when the hasNext() function runs, it puts the input in the buffer and transfers it to the immediate sc.next() or sc.nextLine() (if any of them exists).
So a simple program would be:
import java.util.*;
public class practice {
static Scanner reader = new Scanner(System.in);
public static void main(String[] args) {
if(reader.hasNextInt()){
int numberEntered = reader.nextInt();
}
}
}
So I have a misunderstanding. hasNextInt() is supposed to check if the next input will be an int or not. I saw this program and I don't understand how the number can be inputed. Because already for getting an input the reader.hasNextInt() needs to be true and the program hasn't got an input. So how will the program get inside the if statement?
The method Scanner#hasNextInt(), in your case, is a blocking method. This means, it is a method which waits and does only return if some conditions are met. It looks something like this:
public boolean hasNextInt() {
...
boolean condition = false;
while(!condition) {
...
}
...
return stuff;
}
To be more precise, the blocking method is Scanner#hasNext(). It is described in its documentation.
If the method blocks or not depends on the Scanners source. If it is, for example System.in, it will wait. If it is just a File, it will read the whole file until its end and then return, no blocking.
So, what happens? The hasNextInt in your if-condition waits for you to enter some input (until you send it by typing Enter). Then the Scanner saves the input inside a buffer. hasNextInt checks the internal buffer but does not delete stuff from the buffer.
Now comes nextInt which reads from the internal buffer and also deletes the stuff inside it. It advances past read input.
You can read it in detail inside the documentation mentioned above.
Things short: Scanner#hasNextInt() waits for input before it returns true or false.
public class Two {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int c=0;
while(sc.hasNext())System.out.println(++c+" "+sc.nextLine());
}
}
I came across this code and i want to confirm that by taking input directly without using object of any datatype all we are doing is taking input and displaying it and we are not storing it anywhere?
and also how is the condition inside while loop is true for the first time? As we have not given any input yet.
Sure, your code doesn't store sc.nextLine() , so this value will be discarded past the System.out.println instruction.
Also for hasNext() :
This method may block while waiting for input to scan.
so the condition will be met once the stream begins to provide input, and the method will block waiting for this to happen or an Exception to happen (e.g : if the Scanner gets closed ).
As long as nothing of those things happen, hasNext() method doesn't return, so the condition in while is still not evaluated, so the loop is blocked there .
Let's go through your code:
Scanner sc = new Scanner(System.in)
The java.util.Scanner.Scanner(InputStream) constructor is called, and you have an object sc of type Scanner which reads from System.in.
int c = 0;
You now have a primitive c of primitive type int.
while(sc.hasNext()) { ... }
The while loop evaluates sc.hasNext(), which is true. As per the documentation, sc.hasNext() returns true if and only if the input has another token in it. In your case, this means that the InputStream is open.
{... System.out.println(++c + " " + sc.nextLine()); ...}
sc.nextLine() is the problem. Assuming you have not changed System.in, the console/terminal will block the loop (i.e. hold the loop paused) until you give it an input (type in some text and hit [ENTER]).
So, overall:
Scanner::hasNext() will return true if and only if it is possible to get more input (if you are using System.in, this will always be true until you close the scanner).
If you are printing the input directly, you will not be storing any references to it, and no memory will be allocated for it (unless Scanner.nextLine() stores it somewhere).
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.