Scanner next methods in Java [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I'm new to Java and still confused on how the scanner next methods actually work. I have an example program right here:
import java.util.Scanner;
public class HelloJava{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int varInt;
String varString;
String varStringTwo;
System.out.print("Insert int value: ");
varInt = sc.nextInt();
System.out.print("Insert string value: ");
varString = sc.nextLine();
System.out.print("Insert another string value: ");
varStringTwo = sc.nextLine();
sc.close();
}
}
When i executed the program and entered an integer on the first prompt, the terminal looked like this:
Insert int value: 15
Insert string value: Insert another string value: // i can input any value here //
// ^ but the program doesn't allow me to input anything here
I know that one of the solution is to put "sc.nextLine();" between varInt = "sc.nextInt();" and "System.out.print("Insert a string value: ");", but I don't understand why or how.

When you scan a String values with spaces the scanner.next() method will get you the string up to space.
For example,
your input is This is a String
so when the first time you run scanner.next() it will return the value This. If you run it a second time it will return you is and so on.

Related

java Scanner doesn't pop up [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I'm new to java and I wrote this code
import java.util.Scanner;
public class GamingJava {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String Name;
int password;
String yEs;
System.out.print("hello sir what is your name? ");
Name = input.nextLine();
System.out.print("what is your password? ");
password = input.nextInt();
System.out.println("your name was "+Name+" and your password was "+password);
System.out.print("are you sure? ");
yEs = input.nextLine();
System.out.println(yEs);
}
}
It only ask the name and the password, but Java doesn't ask the last one how did that happen?
It asks for the input and immediately takes it as an empty string i.e. "".
Root Cause : The issue is because of the nextLine() method. Since while providing an input, user has to press the Enter key, the cursor/prompt on the console moves to next line. This line is taken as an empty line by the nextLine() method.
Solution : You must use the next() method as it looks out for the presence of space character for taking the input.
FYR the following line of code
yEs = input.nextLine();
should be changed to
yEs = input.next();

Java string input not working correctly [duplicate]

This question already has answers here:
What's the difference between next() and nextLine() methods from Scanner class?
(15 answers)
Closed 5 years ago.
I have made this program and I have gotten stuck. When I run it and I have inputs without using spaces it works fine, for example just Bob input in customer input. However, when I enter Bob White, it merges the next two string input directions (as Shown in pic attached) . What am I doing wrong here?
import java.util.*;
public class Blah{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String customerName;
System.out.println("Enter customer name: ");
customerName = in.next();
String customerAddress;
System.out.println("Enter customer address: ");
customerAddress = in.next();
String customerPhoneNumber;
System.out.println("Enter customer phone number: ");
customerPhoneNumber = in.next();
in.close();
}
}
Thats because the Scanner#next method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner#nextLine
Try using nextLine() method instead with trem() method
customerName = in.nextLine().trim();
You need to read the entire line using nextLine() method then trim it from leading and trailing whitespace using trim() method.
customerName = in.nextLine().trim();
customerAddress = in.next().trim();
customerPhoneNumber = in.next().trim();

Whats the difference between two multiple user input programs? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
import java.util.Scanner;
public class HelloWorld{
public static void main(String args[]){
Scanner dd = new Scanner(System.in);
System.out.println("Enter name");
String b = dd.nextLine();
System.out.println("Enter num");
int num = dd.nextInt();
}
}
And
import java.util.Scanner;
public class HelloWorld{
public static void main(String args[]){
Scanner dd = new Scanner(System.in);
System.out.println("Enter num");
int num = dd.nextInt();
System.out.println("Enter name");
String b = dd.nextLine();
}
}
Why the latter doesn't work peoperly(doesn't let me enter name), while the first one does?
I have made up a new version without that annoying "Scanner scan = new Scanner".
And what about this solution? What cons may it have?
import java.util.Scanner;
public class HelloWorld{
public static void main(String args[]){
System.out.println("Enter num");
int i = new Scanner(System.in).nextInt();
System.out.println("Enter name");
String b = new Scanner(System.in).nextLine();
}
}
The second program expects an Int first and then a name. And hence might be erroring out when a name is entered.
In the second case, nextInt() does not scan over the newline character that the user inputs when pressing the Return key.
In the first case, nextLine() is encountered first so the problem doesn't manifest itself.
The moral of the story is to always use nextLine() and parse the resulting string accordingly. Use something like Integer#parseInt to convert a string to an integer.

How to get the right input for the String variable using scanner class? [duplicate]

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);
}
}

Scanner not scanning all fields? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 8 years ago.
I was writing my first, well second if you count hello world, program and ran into a small issue.
My code:
import java.util.*;
class test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("What is your name: ");
String name = scan.nextLine();
System.out.print("What is your favorite number: ");
int favoriteNumber = scan.nextInt();
System.out.print("What is your favorite game: ");
String game = scan.nextLine();
}
}
So it scans in name and favoriteNumber but the program ends before asking the user to enter a favorite game. Essentially the user can only enter text twice instead of three times like I would like.
Just a guess: scan.nextInt() does not consume the trailing newline character after the user presses enter. The subsequent call to scan.nextLine() then finds a newline character waiting.
Try switching out int favoriteNumber = scan.nextInt(); for String favoriteNumber = scan.nextLine(); to see if that fixes the issue. If it does, my hypothesis is correct.
If that is the case, then you should probably use Integer.parseInt to convert this string into an integer. The problem here is effectively that you really want to collect 3 lines of input, where a line is defined as "any sequence of characters ending with a newline". Your program is currently written to request a line, an int, then a line, rather than "3 lines of input, one of which contains an int".
an exception must be thrown in here scan.nextInt();
Check whether you entered a proper int

Categories

Resources