Scanner hasNext() infinite loop when displayed with printf() and nextInt() method - java

I have this code that asks for a name and age in a do-while loop:
public class Test1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
do {
System.out.print("Enter name & age: ");
System.out.printf("%s %d",
scanner.next(), scanner.nextInt());
} while (scanner.hasNext());
}
}
It outputs:
Enter name & age: test 6
test 6
and then doesn't seem to react to my input, while it should have repeated the question on the third line. What is wrong here?

I think this should stop by the points it gets its input, since when you'll press enter, it would automatically enter the input and your method would end.
I would recommend you to use a while(true) statement if you want to have an infinite input. That issue shouldn't appear if you do it that way.

The java.util.Scanner.hasNext() method 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. Read more
To avoid getting blocked by hasNext() you can simply pass true for loop condition.
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
do {
System.out.print("Enter name & age: ");
System.out.printf("%s %d", scanner.next(), scanner.nextInt());
} while (true);
}
}

Related

Java if (Yes or No Statement)

Hey there I got into some trouble with my java Code.
I try to code a bit around with java for a few hours and I dont know much thats why im asking. I learn best by trying but I get into so many problems.
So: I want the scanner to scan the next Statement and if its "ja" it should do the if thing etc.
The problem is, when i try to compile it it has an error with the = s.nextInt thing. In the console it says: "cannot find symbole". I tried so many things I dont know what to do. Allready tried so much.
import java.util.Scanner;
public class Brotcrunsher {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println ("Hallo");
System.out.println ("A flag has more then 1 color right?");
String a = s.NextInt();
if (a.equals("ja")) {
System.out.println ("You arent dumb, nice.");
} // end of if
else {
System.out.println ("You arentn a genie");
} // end of if-else
}
}
thanks in advance.
EDIT: Problem solved. Thank you for every awnser. I try my best to Tag my posts better and to format my code better
Here:
String a = s.NextInt();
You want a to be String (which makes sense, as you want to compare it against other Strings later on); so you better use:
String a = s.nextLine();
instead!
The other method a) does not exist and b) nextInt() ... returns a number, not a string
I can see two errors, firstly you are taking a string input from the command line user so your scanner must be "scanner.nextLine()" which takes a string, as it stands you are expecting an integer value.
Second your "s.scanner" is not calling anything, you have declared your scanner with the name "scan", so you need to change that to "scan".
import java.util.Scanner;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("A flag has more than one colour?");
String input = scan.nextLine();
if (input.equals("yes")) {
System.out.println("well done");
} else {
System.out.println("wrong answer");
}
}
Try:
import java.util.Scanner;
public class Brotcrunsher {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
System.out.println ("Hallo");
System.out.println ("A flag has more then 1 color right?");
String a = scan.nextLine();
if (a.equals("ja")) {
System.out.println ("You arent dumb, nice.");
} // end of if
else {
System.out.println ("You arentn a genie");
} // end of if-else
}
}
You have got a compilation error that should be
String a = scan.next();
Since scan is your scanner object where you are using String a = s.NextInt(); which is not at all an object of scanner.
Two issues, one is a is a String not an int and the second is Scanner.nextLine() (or nextInt() or next()). And, the local reference is scan (not s). Like,
String a = scan.nextLine();
You can use like this.
import java.util.Scanner;
class ScannerTest{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
sc.close();
}
}
refrence: http://www.javatpoint.com/Scanner-class

Usage of hasNextInt() in java

I am a beginner and I am confused with using hasNextInt(). If it checks the input, then shouldn't we be using it after asking the user for input? However, in the given code below, it is used with if statement. Please advise.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Enter your number");
if (userInput.hasNextInt()) {
int numberEntered = userInput.nextInt();
System.out.println("You entered an integer");
} else {
System.out.println("you didn't enter an integer");
}
}
}
The java.util.Scanner.hasNextInt() method returns true if the next
token in this scanner's input can be interpreted as an int value in
the default radix using the nextInt() method. The scanner does not
advance past any input.
So Scanner would be invoked upon user presses "Enter" and then it would evaluate if the next input provided by user is int or not.
You use it to test the user's input, so you are sure that when you call nextInt you won't have an exception because the input wasn't an int, it's also not moving he cursor forward:
Scanner scanner = new Scanner(System.in);
if(scanner.hasNextInt()){
System.out.println(scanner.nextInt());
}

Scanner code that produces an error message instead of crashing

I need this code to produce an error message when the user tries to input a string instead of an int. How would I go about doing that?
import java.util.Scanner;
public class Testing {
public static void main (String [] args){
Scanner s = new Scanner(System.in);
System.out.println("Please enter an int");
input = s.nextInt();
}
}
Check if user provided proper int with hasNextInt() method.
if validation was OK read that value with nextInt().
if value was not int you can use next() to consume it (you don't have to really use that value, but you need to take it out from scanner so you could read other values from user).
Use a loop. Check if there is an int. And if there isn't display a message. Something like,
Scanner s = new Scanner(System.in);
while (true) {
System.out.println("Please enter an int");
if (s.hasNextInt()) {
input = s.nextInt();
// ...
break;
}
System.err.printf("%s isn't an int%n", s.next());
}

Java code suddenly stop

Ive got a problem.I 'm new to Java,I've started today:D) ..I've programmed before so I know it little bit,but I am new to Java. Here is my code: `
public class Tutorial {
public static void main(String[] args) {
double num1,num2;
String operacia;
Scanner in=new Scanner (System.in);
System.out.println("Write 2 numbers");
num1=in.nextDouble();
num2=in.nextDouble();
System.out.println("Choose the operation");
operacia=in.nextLine();
if (operacia.equals("+")){
System.out.println("Your result is "+(num1+num2)) ;
}
else if (operacia.equals("-")){
System.out.println("Your result is "+(num1-num2)) ;
}
else if (operacia.equals("/")){
System.out.println("Your result is "+(num1/num2)) ;
}
else if (operacia.equals("*")){
System.out.println("Your result is "+(num1*num2)) ;
}
}
}`
It wants from me 2 numbers,I write them and them it writes "Choose the operation" and its over.No more inputs.Thank you very much :)
Your problem is simple.
Just replace the code with next() instead of nextLine().Effectively, the line your code is returning is receiving is a blank line. Hence when it reaches the conditional statement it has an empty string and terminates.
next()
Finds and returns the next complete token from this scanner.
nextLine()
Advances this scanner past the current line and returns the input that was skipped.
Your code should be fixed by a simple change.
public static void main(String[] args) {
double num1,num2;
String operacia;
Scanner in=new Scanner (System.in);
System.out.println("Write 2 numbers");
num1=in.nextDouble();
num2=in.nextDouble();
System.out.println("Choose the operation");
operacia=in.next();
if (operacia.equals("+")){
System.out.println("Your result is "+(num1+num2)) ;
}
else if (operacia.equals("-")){
System.out.println("Your result is "+(num1-num2)) ;
}
else if (operacia.equals("/")){
System.out.println("Your result is "+(num1/num2)) ;
}
else if (operacia.equals("*")){
System.out.println("Your result is "+(num1*num2)) ;
}
}
Scanner#nextDouble() consumes only the next token as a double from the input. It does not consume the new line you typed using the Enter on the keyboard while entering the two numbers. When the execution reaches operacia=in.nextLine();, this new line is consumed, never allowing the user a chance to type the operating string.
To solve this, you need to read the whole line using Scanner#nextLine() and convert it to a double:
String input = in.nextLine();
num1 = Double.parseDouble(input);
input = in.nextLine();
num2 = Double.parseDouble(input);
I believe the in.nextLine(); operation is reading only to the end of the line where you input 2 numbers. If you want your program to only consider the next line, you have to clear the current one first.
Try this, it should work:
System.out.println("Choose the operation");
in.nextLine(); //clear the current line
operacia=in.nextLine();

how to accept multiple lines of input just once and making sure the user is not asked for input once again

I have tried to solve the 3n+1 problem, and got very close. I think what happens here is the answer should accept multiple lines of input at once should not ask the user to give input again. I have tried the nextLine() method in a loop conditioned by the hasNextLong(), but the problem is whenever it does not find any more long types, it asks the user to give another input instead of breaking the loop. Is there any way to make sure it takes input only once, regardless of how many lines the user inputs?
The loop breaks if I enter a String. What I want to do is break when only the first input has no more long variables to deal with.
import java.util.Scanner;
import java.io.*;
public class te{
public static void main(String[] args){
Scanner key=new Scanner (new BufferedInputStream(System.in));
String s="";
while(key.hasNextInt()){
System.out.println("Entered loop");
s=s+""+key.nextLong();
}
System.out.println(s);
}
}
Not 100% sure what your trying to accomplish, but to answer this problem:
"..whenever it does not find any more long types, it asks the user to give another input instead of breaking the loop."
I just used a try/catch block. If the input is not a number, it breaks the loop. You can keep inputting numbers and hitting enter, and if an input is not a number, the loop will break; and it will print out the concatenated numbers.
import java.util.Scanner;
public class StackOverflow {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String s = "";
System.out.println("Enter Numbers: ");
while (true) {
try {
s += String.valueOf(scanner.nextInt()); // if input is not an int
} catch (Exception ex) { // it will throw exception
break;
}
}
System.out.println(s);
}
}
Edit: Scanning a line
Scanner input = Scanner(System.in);
System.out.printline("Enter some numbers: ");
String line = scanner.nextLine();
Scanner lineScanner = new Scanner(line);
while (lineScanner.hasNextLong()){
long num = lineScanner.nextLong();
// do something with num
}

Categories