Im having some trouble with scanning user input in one of my first java programs. When I compile and run this, I am immediately prompted for input (i.e the command line stops and blinks). When I enter anything, the first line is printed, asking me to enter an integer. Then the second line is printed and I'm prompted to enter another value.
The output from this program is the first two values that I input. This is hard to explain, but it basically asks for 3 input values and only uses two.
import java.util.Scanner;
public class objects
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer please...");
int input = sc.nextInt();
System.out.println("Enter your name please...");
String name = sc.nextLine();
System.out.println("The read values: " + input + ", " + name);
sc.close();
}
}
Put a System.out.flush() command after your println statements if you're reading from the console directly afterward
just use this:
Scanner sc = new Scanner(System.in);
System.out.print ("Enter your name please... ");
String name = sc.nextLine();
System.out.print ("Enter an integer please... ");
int input = sc.nextInt();
System.out.println ("The read values: " + input + ", " + name);
i just moved the integer below the name and it sorta fixed it. hahaha
When you introduce a number you press enter key, nextInt() uses the number but the enter (\n) remains buffered. After this if you call again nextInt(), Java tries to convert \n into a number giving you a NumberFormatException, but if you invoke nextLine() they read the enter as empty string
Here you have a better explanation and one solution
Can't use Scanner.nextInt() and Scanner.nextLine() together
It seems this is an error to do with my installation of VirtualBox. No matter what I try, the problem persists. Even if i try to only read ONE integer, it will ask me to input two values.
Thanks for everyone who tried to help, I learned a lot just trying to debug this.
Related
I have this programs and a few questions regarding to how .next(), .nextInt(), .hasNext() and .hasNextInt() of Scanner class work. Thank you in advance for any of your help :)
import java.util.Scanner;
public class test {
public static void main (String[] args) {
Scanner console = new Scanner(System.in);
int age;
System.out.print("Please enter your age: ");
while (!console.hasNextInt()) {
System.out.print("Please re-enter your age: ");
console.next();
}
age = console.nextInt();
System.out.println("Your age is "+age);
}
}
1/ When !console.hasNextInt() is executed for the first time, why does it ask for an input?
I thought at first the console is empty, so !console.hasNextInt() is True (empty is not an int), then it should go directly from "Please enter your age: " to "Please re-enter your age: " but my thought seems to be wrong.
Here, the user needs to enter something before "Please re-enter your age: " is printed.
2/ The data type of console.next() is always a String (I tried making int s = console.next(); and it gave an error), then why isn't this a infinite loop?
3/ For an instance, when it comes to console.next();, I input 21. Why does age have the value of 21? I thought because of console.hasNextInt(), I need to enter another number, and that new number will be the value of age.
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.
When you start with a non integer input, hasNextInt() will be false and you will enter while loop. Then it will prompt you to re-enter your age. But if you start with integer, you won't enter the loop. Your age will be printed.
console.next() means it takes next input token and returns String. If you write down your code as:
String s = null;
while (!console.hasNextInt()) {
s = console.next();
System.out.println("You entered an invalid input: " + s);
System.out.print("Please re-enter your age: ");
}
console.next() is being used for handling the non-integer inputs. Now, if you enter a non-integer input twenty, you'll see that console.hasNextInt() will be false and console.next() will read it.
hasNextInt() waits for an input string and then tells you if can be converted to an int. With that in mind, let's go over your questions:
When !console.hasNextInt() is executed for the first time, why does it ask for an input?
Because it blocks until there's some input from the console.
The data type of console.next() is always a String (I tried making int s = console.next(); and it gave an error), then why isn't this a infinite loop?
Because hasNextInt() returns true when the input can be converted to an int, for example "21".
For an instance, when it comes to console.next();, I input 21. Why does age have the value of 21? I thought because of console.hasNextInt(), I need to enter another number, and that new number will be the value of age.
Calling next() doesn't wait for a new input, it just swallows the input that was tested by hasNextInt() so the scanner can move on to the next one. It could have been the first statement in the loop, with the same effect.
I have just started my 2nd programming course at college and our first assignment is rather simple, intended to basically check our environment and to check we know how to submit assignments through the course website.
When I run the code we have been supplied with, it hangs where it is supposed to prompt for the user to enter a number, so that it can print it. I inserted a series of println statements to determine where it was hanging.
It prints TEST1, TEST2 and TEST3, but never makes it to TEST4. So there must be something wrong with the line:
number = input.nextInt();
But I can't for the life of me see what's wrong with that line. Any help would be greatly appreciated! :)
Anyway, here is the code
package rossassignment1;
import java.util.Scanner; // use the Scanner class located in the "java.util" directory
public class RossAssignment1 {
public static void main (String[] args) {
System.out.println("TEST 1");
int number;
System.out.println("TEST 2");
Scanner input = new Scanner(System.in);
System.out.println("TEST 3");
number = input.nextInt();
System.out.println("TEST 4"); // display the number with other messages
System.out.print("This program reads an integer from a keyboard,\n"
+ " and print it out on the display screen.\n"
+ "The number is: " + number + ".\n"
+ "make sure that you get the exact same output as the expected one!\n");
}
}
After the line input.nextInt() is run the program is waiting for the user (you, or whatever marking system is being used) to input an integer in the console. After you do so the program will continue to your TEST4 line.
If after entering an integer, the codes after that still don't show up, you can do this:
number = input.nextInt();
input.nextLine(); //Add this
It will clear the newline.
Alternatively, I prefer to do this:
number = Integer.parseInt(input.nextLine());
I've just learned about scanners but one thing I noticed was when I wrote
Scanner input = new Scanner(System.in); //Creates scanner object
System.out.println("Enter a line: "); //Ask for input
String line = input.nextLine(); //Enter input
System.out.println("You entered: " + line); //Output the input
System.out.println("And enter a number: ");
int value = input.nextInt();
System.out.println(value + " " + line);
the top line of code could be used for both thing I wanted to get input for (string and ints). My question is whether I should be using the same name for a scanner 'input' in this case for multiple things i'd like to input. I'm new so even if I can't find a problem that could come from using the same name, if later on in a big program this could become problematic?
See the scanner instance input is a reference and you are making it point to the standard input stream by specifying new Scanner(System.in);.
In a stream, everything will be in bytes, the methods nextLine() , nextInt() etc will scan / parse the stream and give you the data of that *particular type.
So using the same scanner instance i.e, input is fine because you are parsing data as you receive it.
Yes you can use the same scanner object until its not closed and pointing to input stream.
If you don't need it anymore then use close method to close the Scanner.
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 8 years ago.
I am learning Java and I was trying an input program. When I tried to input an integer and string using instance to Scanner class , there is an error by which I can't input string. When I input string first and int after, it works fine. When I use a different object to Scanner class it also works fine. But what's the problem in this method when I try to input int first and string next using same instance to Scanner class?
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
//Scanner input2=new Scanner(System.in);
System.out.println("Enter your number :" );
int ip = input.nextInt();
System.out.println("Your Number is : " + ip);
System.out.println("Enter Your Name : ");
String name= input.nextLine();
System.out.println("Your Next is : " + name);
}
}
nextInt() doesn't wait for the end of the line - it waits for the end of the token, which is any whitespace, by default. So for example, if you type in "27 Jon" on the first line with your current code, you'll get a value of 27 for ip and Jon for name.
If you actually want to consumer a complete line, you might be best off calling input.nextLine() for the number input as well, and then use Integer.parseInt to parse the line. Aside from anything else, that represents what you actually want to do - enter two lines of text, and parse the first as a number.
Personally I'm not a big fan of Scanner - it has a lot of gotchas like this. I'm sure it's fine when it's being used in exactly the way the designers intended, but it's not always easy to tell what that is.
If you call input.nextInt(); the scanner reads the number from the input, but leaves the line separator there. That means, if you call input.nextLine(); next, it reads everything till the next line separator. And this is in this case only the line separator itself.
You can fix that in two ways.
Way 1:
int ip = Integer.parseInt(input.nextLine());
// output
String name= input.nextLine();
Ways 2:
int ip = input.nextInt();
// output
input.nextLine();
String name= input.nextLine();
This one working, Anyway if you want to save IP address it must be String.
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Scanner input2=new Scanner(System.in);
System.out.println("Enter your number :");
int ip = input.nextInt();
System.out.println("Your Number is : " + ip);
System.out.println("Enter Your Name : ");
input.nextLine();
String name = input.nextLine();
System.out.println("Your Next is : " + name);
}
}
Here is my code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String question;
question = in.next();
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
When I try to write "how do you like school?" the answer is always "Que?" but it works fine as "howdoyoulikeschool?"
Should I define the input as something other than String?
in.next() will return space-delimited strings. Use in.nextLine() if you want to read the whole line. After reading the string, use question = question.replaceAll("\\s","") to remove spaces.
Since it's a long time and people keep suggesting to use Scanner#nextLine(), there's another chance that Scanner can take spaces included in input.
Class Scanner
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
You can use Scanner#useDelimiter() to change the delimiter of Scanner to another pattern such as a line feed or something else.
Scanner in = new Scanner(System.in);
in.useDelimiter("\n"); // use LF as the delimiter
String question;
System.out.println("Please input question:");
question = in.next();
// TODO do something with your input such as removing spaces...
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
I found a very weird thing in Java today, so it goes like -
If you are inputting more than 1 thing from the user, say
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
So, it might look like if we run this program, it will ask for these 3 inputs and say our input values are 10, 2.5, "Welcome to java"
The program should print these 3 values as it is, as we have used nextLine() so it shouldn't ignore the text after spaces that we have entered in our variable s
But, the output that you will get is -
10
2.5
And that's it, it doesn't even prompt for the String input.
Now I was reading about it and to be very honest there are still some gaps in my understanding, all I could figure out was after taking the int input and then the double input when we press enter, it considers that as the prompt and ignores the nextLine().
So changing my code to something like this -
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
does the job perfectly, so it is related to something like "\n" being stored in the keyboard buffer in the previous example which we can bypass using this.
Please if anybody knows help me with an explanation for this.
Instead of
Scanner in = new Scanner(System.in);
String question;
question = in.next();
Type in
Scanner in = new Scanner(System.in);
String question;
question = in.nextLine();
This should be able to take spaces as input.
This is a sample implementation of taking input in java, I added some fault tolerance on just the salary field to show how it's done. If you notice, you also have to close the input stream .. Enjoy :-)
/* AUTHOR: MIKEQ
* DATE: 04/29/2016
* DESCRIPTION: Take input with Java using Scanner Class, Wow, stunningly fun. :-)
* Added example of error check on salary input.
* TESTED: Eclipse Java EE IDE for Web Developers. Version: Mars.2 Release (4.5.2)
*/
import java.util.Scanner;
public class userInputVersion1 {
public static void main(String[] args) {
System.out.println("** Taking in User input **");
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name : ");
String s = input.nextLine(); // getting a String value (full line)
//String s = input.next(); // getting a String value (issues with spaces in line)
System.out.println("Please enter your age : ");
int i = input.nextInt(); // getting an integer
// version with Fault Tolerance:
System.out.println("Please enter your salary : ");
while (!input.hasNextDouble())
{
System.out.println("Invalid input\n Type the double-type number:");
input.next();
}
double d = input.nextDouble(); // need to check the data type?
System.out.printf("\nName %s" +
"\nAge: %d" +
"\nSalary: %f\n", s, i, d);
// close the scanner
System.out.println("Closing Scanner...");
input.close();
System.out.println("Scanner Closed.");
}
}