Why is that I can still an input even it's outside the while loop?
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = scan.next();
while(true){
}
}
First, you don't need a while loop to take any input and your loop is practically useless since its not being used. Second, That loop is bad since any other loops you might have in your code will be unreachable. unless you specify a way to break the loop using break; or flags e.g.:
boolean myCondition = true;
while(myCondition){}
or use break:
while(true){
if(whatever){
break;
}
}
Then again you don't need any of this since your not dealing with multiple inputs etc. So your answer is NO its working how you told it to work.
Related
Here's the code:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Number: ");
if (scanner.hasNextInt()) {
System.out.println(scanner.nextInt());
break;
} else {
System.out.println("Not an integer.");
}
}
scanner.close();
}
When the value is an integer everything works fine, the loop breaks out, however when the input is not an integer I keep seeing this infinitely flooding the terminal:
Number: Not an integer.
Number: Not an integer.
Number: Not an integer.
...
...
...
The reason this is happening when using Scanner.hasNextInt() in conjunction with Scanner.nextInt() is because the nextInt() method does not consume the ENTER key strike from the scanner buffer (when you enter a number) so this ENTER keeps getting played indefinitely. You need to clear this out of the Scanner buffer (so to speak) and to do that, you need to do this:
} else {
System.out.println("Not an integer.");
scanner.nextLine(); // Clear Scanner buffer.
}
Another reason why I just use Scanner.nextLine() ;).
OH...and don't close the Scanner object unless you are sure your application is finished with it otherwise you will not be able to use it again until you restart your application. It is auto-closed and Garbage Collected when the application closes anyways.
if (scanner.hasNextInt()) {
System.out.println(scanner.nextInt());
break;
}
Because scanner.hasNextInt() is looking for an Integer input and if the input is integer it prints its value and breaks (break statement) the while loop (i.e come out of the loop) else it keeps scanning for integer input.
Also you are using condition true in while loop which means loop will keep executing infinitely until we break it.
That's simply because:
You are not taking out the non integer element (so it doesn't advance)
There is no other logic to leave the loop (while(true) is not nice anyway) if there is no integer.
You have entered an infinite loop if your scanner object does not recognize an integer input. Since you are not having a "break" inside the else{} block, it would loop through infinite number of times and flood the terminal. Insert a "break;" after the print statement
add break; after System.out inside else bracket , so you can break your loop once you encounter a non-integer input.
while(true)
{
if(Something) // What Ever
{
break;
}
}
System.out.println("Something Happened");
so if something happens you'll see Something Happened Once.
Edit:
If you want it to repeat asking, change it like this:
public static void main(String[] args) {
Scanner scanner;
while (true) {
scanner= new Scanner(System.in);
System.out.print("Number: ");
if (scanner.hasNextInt()) {
System.out.println(scanner.nextInt());
break;
} else {
System.out.println("Not an integer.");
}
}
scanner.close();
}
This is the basic setup for a little console-based quiz game. The answers are numbered. I want the player to give the answer number. If the input is not a number, then my program should give a warning, and wait for proper input.
Instead, what I get (after inserting something that is not a number) is an infinite loop of asking the question and presenting the answers again.
public static void main(String[] args) {
boolean quizActive = true;
while(quizActive) {
presentQuestion();
presentAnswers();
Scanner s = new Scanner(System.in);
if (s.hasNext()) {
String choice = s.next();
if (!NumberUtils.isNumber(choice)) {
presentText("Please insert the answer number.");
} else {
System.out.println("You made a choice!");
checkAnswer(choice);
quizActive = false;
}
s.close();
}
}
}
What am I doing wrong here?
If you do not want to question and answers be presented each time move presentQuestion() and presentAnswers() outside the loop.
But main problem is that you closing Scanner.
Remove s.close(); and move Scanner s = new Scanner(System.in); outside of the loop.
I really don't get the point in using scanner for acquiring user input.
The scanner class is perfect to process structured input from a flat file with known structure like an CSV.
But user input need to deal with all the human imperfection. After all the only advantage you get is not needing to call Integer.parseInt() your yourself at the cost to deal with the not cleared input when scanne.nextInt() fails...
So why not using InputStreamReader aside with a loop suggested by others?
Here an Example :
public class Application {
public static void main(String [] args) {
System.out.println("Please insert the answer number. ");
while (true) {
try {
Scanner in = new Scanner(System.in);
int choice = in.nextInt();
System.out.println("You made a choice!");
checkAnswer(choice);
break;
} catch (Exception e) {
System.out.println("Invalid Number, Please insert the answer number ");
}
}
}
}
You started your Quiz in a loop which is regulated by your quizActive boolean. That means that your methods presentQuestion() and presentAnswers() get called every time the loop starts again.
If you don't input a number but a character for example, your program will run the presentText("Please insert the answer number.") and start the loop again. As it starts the loop again, it will call the methods presentQuestion() and presentAnswers().
To stop that, you can do another loop around the input-sequence. Also your Scanner s = new Scanner(System.in) should be outside the loop. And you shouldn't close your Scanner right after the first input and then open it again!
if you want a code example, please tell me :)
I have a program where a scanner is responding to certain things that you type in.
Here is an example of the code:
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
int i=0;
String in = inp.nextLine();
while(i==0){
if(in.equals("x")){
System.out.println("> y");
in = inp.nextLine();
}
}
Everything works fine, like if I type in x, it says y. However, if I type in z, nothing happens, then if I type in x, nothing happens and it completely breaks. What can I do?
You have an infinite loop right so your program is stuck there. Since the second time you enter z which is not equal to x so your code flow doesn't go into the if and get stuck in the infinite loop since your i variable doesn't change either.
You have created infinite loop.
When input is z, check for equalitiy fails and loop keeps spining on condition i == 0 which is always true.
If you want x to continue working after you put in a value that is not accepted take the in = inp.nextLine(); call out like this:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner inp = new Scanner(System.in);
int i=0;
String in = inp.nextLine();
while(i==0){
if(in.equals("x")){
System.out.println("> y");
//in = inp.nextLine(); remove this
}
in = inp.nextLine();
}
}
Not sure if this is what you were looking for.
Also if you do not plan to change i, you can simply keep the while loop going by doing this.
while(true){
//do stuff here
}
Move this line:
in = inp.nextLine();
outside of the curly braces that it is in.
Also, as others have said you have an infinite loop. One way to fix that is have a sentinel character (like 'q') that it checks for and breaks out if it is detected.
Like everyone said, you're in an infinite loop, and when you type z and the equality check fails, you never enter the if block again to check for user input, so typing x again after z won't print anything.
Assuming you want to keep your program as is and continually ask for input, you can just move the:
in = inp.nextLine();
after the if block.
You may want to have some sort of terminating condition though so the program can exit (like you exit the loop when the user types q or something along those lines).
When you enter z, nothing happens because you did not instruct it to do anything if inpout is not equal to x.
Since the in = inp.nextLine(); is in the if condition, it wont read anything from the keyboard if you do not enter x. So move it outside of the loop.
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
int i=0;
String in = inp.nextLine();
while(i==0){
if(in.equals("x")){
System.out.println("> y");
}else{
System.out.println("input != x");
}
in = inp.nextLine();
}
This program goes in an infinite loop in while cycle. Please, can someone tell me why?
import java.util.Scanner;
public class program {
public static void main(String[] pars) {
System.out.println("Insert something.");
Scanner read = new Scanner(System.in);
String s = "";
while(read.hasNext()) {
System.out.println(read.next());
}
System.out.println("End of program");
}
}
Read the Javadoc 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.
Hence the while loop will always be executed in your case, each time waiting for input from the user. Since the Scanner is linked to System.in, the input stream will always block until the user inputs a string and hasNext() will always return true, unless the user signals the end of file (e.g. through the Ctrl+z combination on Windows). Scanner#hasNext() is more convenient when reading from files where the input size is known and the end of the file marks the end of the stream.
One way to end the loop here is to add a condition on the input:
while (read.hasNext()) {
s = read.next();
if(s.equals("quit")) {
break;
}
System.out.println(s);
}
P.S.: It is more conventional to name classes starting with an uppercase letter.
The problem is this line:
while(read.hasNext()) {
If you use System.in as a stream provided by the user, it will - if no such input is available - as #manouti says, block and wait for input. But even if you provide input, it will keep waiting. The system has no means to detect whether the user wants to provide additional input in the future.
It will only stop, if the Stream ends. This can be under two conditions:
The end of the file (in case of I/O redirection like java -jar program.jar < input.dat; or
The user marks the end of a stream, in most shells with Ctrl+D. This marks the end-of-stream.
An alternative is to provide some kind of stop directive. Something like "END". Thus:
while(read.hasNext()) {
String nx = read.next();
if(nx.equals("END")) {
break;
}
System.out.println(nx);
}
Just remove while loop
public static void main(String[] pars) {
System.out.println("Insert something.");
Scanner read = new Scanner(System.in);
String s = "";
System.out.println(read.next());
System.out.println("End of program");
}
Or if u want display certain no.of string then mention condition properly.
public static void main(String[] pars) {
System.out.println("Insert something.");
Scanner read = new Scanner(System.in);
String s = "";
int i=0;
while(i<5) {
System.out.println(read.next());
i++;
}
System.out.println("End of program");
}
I'm new to programming and to this website, so here goes.
I wanted to write a program that would allow as many input strings as possible to be added to an ArrayList. So I used a while loop in the following code. What I intended was for the loop to break if the input was 0.
import java.util.*;
public class AddToList2
{
static Scanner q = new Scanner(System.in);
public static void main(String[] args)
{
ArrayList<String> inputlist = new ArrayList<String>();
while (true)
{
System.out.print("Enter something here: ");
String x = q.nextLine();
inputlist.add(x);
if (x.equals("0"));
break;
}
}
The program was compiled without error, but sadly, when I ran the program many times, the loop broke no matter what the input was. Any way to solve this?
Well, that was careless of me! Anyway, I had created that program in order to find out what was wrong with this:
ArrayList<String> endangeredlist = new ArrayList<String>();
ArrayList<Integer> popn = new ArrayList<Integer>();
while (true)
{
System.out.print("Name an animal: ");
String animal = q.nextLine();
endangeredlist.add(animal);
if (animal.equals("EXTERMINATE"))
break;
q.next();
System.out.print("How many are left in the wild? ");
int numberleft = q.nextInt();
popn.add(new Integer(numberleft));
}
(This is part of a much larger program.) My intention was for the loop to break when the animal name input was EXTERMINATE. Sadly the program throws a NoSuchElement exception if the input first time round was EXTERMINATE, and if I had inputted something else first the loop would start, but then inputting EXTERMINATE second time round does not break the loop. Why is that?
You have an extraneous semicolon after your if, which effectively makes it
if (x.equals("0")) { }
break;
You have a semi-colon at the end of your condition.
This turns the break into a statement of its own, without the condition.
Your if statement is broken
if (x.equals("0"));
This is basically saying if (x.equals("0")) do nothing...
This is one of the reasons why you should use parenthesis around your if statements
if (x.equals("0")) {
break;
}