scan.nextLine does not work [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?
(13 answers)
Closed 9 years ago.
I used Java and I tried to write program that reads a number of patients and then let the employee enter their names and ages.
and I want the program reads full name such as (Maha Saeed) so I wrote the code like this but I don't know why it does not work
name = scan.nextLine();
and this is the full code
import java.util.*;
public class Answer1
{
static Scanner scan = new Scanner (System.in);
public static void main (String[] args)
{
int age ;
int PatientNumber ;
int PatientNO;
String name ;
System.out.print("Enter number of patients :");
PatientNumber = scan.nextInt();
PatientNO = 1;
while ( PatientNO <= PatientNumber)
{
System.out.println("Patient #" +PatientNO);
System.out.print("Enter patient's Name: ");
name = scan.nextLine(); //<- here is the problem if I write scan.next it works but it reads only the first name
System.out.print("Enter patient's Age: ");
age= scan.nextInt();
PatientNO = PatientNO + 1;
}
}
}
thanks all

See Why can't I enter a string in Scanner(System.in), when calling nextLine()-method? and Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
Simple solution, you can consume the \n character:
scan.nextLine();
name = scan.nextLine();

Related

How to fix nextLine error so that both words are printed? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
The code below works perfectly when ran, but if you enter two words in the "bands" question you'll only get one printed back.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("What is your name?");
String name;
name = scan.next();
System.out.println("Hello " + name);
System.out.println("What is your age?");
int years;
years = scan.nextInt();
int ageInMonths;
ageInMonths = years * 12;
System.out.print("Your age is ");
System.out.print(ageInMonths);
System.out.println(" in months");
System.out.println("What are your favorite two bands?");
String bands = scan.next();
System.out.println("I like >>" + bands + "<<too!");
}
}
The method next() from the class Scanner will return only the next token.
As written in the oracle docu:
Finds and returns the next complete token from this scanner. A
complete token is preceded and followed by input that matches the
delimiter pattern. This method may block while waiting for input to
scan, even if a previous invocation of hasNext() returned true.
The default delimiter ist a space, so if your band name will contain more then one word, it will not work.
For reading a whole line of input user nextLine()
If you want to have both band names separatly, call nextLine() twice to get each input separatly:
System.out.println("What are your favorite two bands?");
String band1 = scan.nextLine();
String band2 = scan.nextLine();
System.out.println("I like >>" + band1 + " and " + band2 + "<<too!");
In this case the user has to press 'enter' after each input.
EDIT:
As mentioned in the comment of Elliott Frisch, other readXXX methods will not remove the lineendings from the inputstream.
see:
stackoverflow.com/q/13102045/2970947
You can use nextLine() for every input or remove the lineending after each reading. Sample with your code:
Scanner scan = new Scanner(System.in);
System.out.println("What is your name?");
String name;
name = scan.next();
scan.nextLine();
System.out.println("Hello " + name);
System.out.println("What is your age?");
int years;
years = scan.nextInt();
scan.nextLine();
int ageInMonths;
ageInMonths = years * 12;
System.out.print("Your age is ");
System.out.print(ageInMonths);
System.out.println(" in months");
System.out.println("What are your favorite two bands?");
String bands = scan.nextLine();
System.out.println("I like >>" + bands + "<<too!");
API References:
next()
nextLine()
To get a full string with multiple words (until enter press) you should use scan.nextLine() instead of scan.next() (scan.next() is use to read next word only).
Do not forget to add an extra scan.nextLine() after scan.nextInt()and beforescan.nextLine()` (see it in Java Scanner class reading strings):
public static void main(String... args) {
try (Scanner scan = new Scanner(System.in)) {
System.out.print("What is your name? ");
String name = scan.nextLine();
System.out.println("Hello " + name);
System.out.print("What is your age? ");
int years = scan.nextInt();
int ageInMonths = years * 12;
System.out.println("Your age is " + ageInMonths + " in months");
System.out.print("What are your favorite two bands? ");
scan.nextLine(); // extra one after scan.nextInt() - it retrieves a empty string
String bands = scan.nextLine();
System.out.println("I like >>" + bands + "<< too!");
}
}
Demo, console output:
What is your name? John Doe
Hello John Doe
What is your age? 666
Your age is 7992 in months
What are your favorite two bands? one two three
I like >>one two three<< too!

next() vs nextLine() in JAVA [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 4 years ago.
I was trying to take input for the number of names to be stored in an array from user and then using that i was taking names from the user ,first i tried to take names from the user using next() method and all the things were fine but when i tried to take input using nextLine() method the output was as shown below
package learningJava;
import java.util.Scanner;
public class practice
{
public static void main(String[] args)
{
int n;
Scanner obj = new Scanner(System.in);
System.out.println("Enter the number of names you are gonna enter");
n = obj.nextInt();
String names[] = new String[n];
for(int i=0;i<n;i++)
{
System.out.println("Enter the name of friend "+(i+1));
names[i]=obj.nextLine();
}
obj.close();
System.out.println("Names of your friends are");
for(int i=0;i<names.length;i++)
{
System.out.println(names[i]);
}
}
}
Output for the nextLine() method
Enter the number of names you are gonna enter
5
Enter the name of friend 1
Enter the name of friend 2
It is not prompting me to enter the name of friend 1 and directly skipping it and coming to the friend 2 line.
I am beginner in Java , i know the basic difference in next and nextLine() that next() doesn't take input after a space but nextLine() takes complete input , So what is happening here ??
just in for loop, just change "println" to "print" because nextLine() consumes new line character.
import java.util.Scanner;
public class practice
{
public static void main(String[] args)
{
int n;
Scanner obj = new Scanner(System.in);
System.out.println("Enter the number of names you are gonna enter");
n = obj.nextInt();
String names[] = new String[n];
for(int i=0;i<n;i++)
{
System.out.print("Enter the name of friend "+(i+1));
names[i]=obj.nextLine();
}
obj.close();
System.out.println("Names of your friends are");
for(int i=0;i<names.length;i++)
{
System.out.println(names[i]);
}
}
}
check this answer: Java String Scanner input does not wait for info, moves directly to next statement. How to wait for info?

Why does this skips the first line? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
When I run this code it skips the first line("Input first name:") and ask for the lastname. How do i fix this?
public static void newProduct() {
System.out.println("Input first name: ");
String fname = scan.nextLine();
System.out.println("Input last name: ");
String lname = scan.nextLine();
}
The output everytime I run this is:
Input first name: <User cannot input as this line gets skipped>
Input last name: <User can input>
Thanks in advance.
Try this
public class Readname {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Give a First Name :");
String text = scan.nextLine();
System.out.print("Give a Last Name :");
String text2 = scan.nextLine();
System.out.println("Full Name: "+text+" "+text2);//to bond the last and first name
}
}

The code runs again no matter what. [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
I don't know why, but the below code makes the user run the code again, whether they choose to or not. I've tried many things, but it doesn't work correctly.
Thanks!
public static void main (String [ ] args)
{
boolean a = true;
while (a)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: ");
int x = scan.nextInt();
System.out.print("\n\nEnter a second integer: ");
int z = scan.nextInt();
System.out.println();
System.out.println();
binaryConvert1(x, z);
System.out.println("\n\nWould you like to run this code again? Enter \"Y\" or \"N\".");
System.out.print("Enter your response here: ");
String RUN = scan.nextLine();
String run = RUN.toLowerCase();
if (run.equals("n"))
{
a = false;
}
System.out.println();
System.out.println();
}
System.out.println("Goodbye.");
}
Scanner.nextInt() doesn't consume the line ending characters from the buffer, which is why when you read the value of the "yes/no" question with scan.nextLine(), you'll receive an empty string instead of the value the user entered.
A simple way to fix this is to explicitly parse the integer from raw lines using Integer.parseInt():
System.out.print("Enter an integer: ");
int x = Integer.parseInt(scan.nextLine());
System.out.print("\n\nEnter a second integer: ");
int z = Integer.parseInt(scan.nextLine());

Do-while loop inside a method [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
Everything is working fine in this code sample that i did, but everytime it calls the do-while loop on the output screen, it skips the "First name" input, and goes straight to "How old are you?" input. why is that happening and how can i fix it? I want to be able to repeat the whole thing without skipping "First name" when i pick 'y' to perform the loop.
public class WeightGoalTest
{
public static void main(String[]args)
{
doWhile person = new doWhile();
person.userInput();
}
}
import java.util.*;
public class doWhile
{
Scanner keyboard = new Scanner(System.in);
private String inputFn = "";
private int inputAge = 0;
private int inputHeight = 0;
private double inputWeight = 0.0;
private int inputCalculation = 0;
private int inputGender = 0;
private char loop;
public void userInput()
{
do
{
System.out.println("First Name: ");
inputFn = keyboard.nextLine();
System.out.println("How old are you?");
inputAge = keyboard.nextInt();
System.out.println("Gender 1 - Male: ");
System.out.println(" 2 - Female: ");
inputGender = keyboard.nextInt();
System.out.println("What is your Height in inches? ");
inputHeight = keyboard.nextInt();
System.out.println("Current Weight in pounds: ");
inputWeight = keyboard.nextDouble();
System.out.println("\nDo you want to use the calculator again? (y/n)");
loop = keyboard.next().charAt(0);
}while(loop == 'y');
}
}
Please note:
String java.util.Scanner.next() - Returns:the next token
String java.util.Scanner.nextLine() - Returns:the line that was skipped
Change your code [do while initial lines] as below:
System.out.println("First Name: ");
inputFn = keyboard.next();
use keyboard.next() instead of .nextLine(). For further informations have a look in the Java API concerning the Scanner class. nextLine() will
Advance this scanner past the current line and return the input that was skipped."

Categories

Resources