Why does this skips the first line? [duplicate] - java

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

Related

Skipping first String Input when I am giving data in Console [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
I want to make a program that will read user inputs and will printout them gradually. But when I am running the code, in the Console area, the first line is automatically skipping. But when I am taking input as Integer, all is running well. Where is my fault?
import java.util.*;
public class MainClass {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int limit, i, j;
System.out.print("How many names you want to take: ");
limit = input.nextInt();
String[] name = new String[limit];
for (i = 0; i < name.length; i++) {
System.out.print("Enter your name: ");
name[i] = input.nextLine();
}
for (String output : name) {
System.out.println("Names are: " + output);
}
}
}
Console area:
How many names you want to take: 3
Enter your name: Enter your name: Saon
Enter your name: Srabon
Names are:
Names are: Saon
Names are: Srabon
Invoke input.nextLine() after the input.nextInt() in order to clear the new line character produced by pressing Enter key (when you enter int number);
Alternatively, you can read your int as Integer.valueOf(input.nextLine()).

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!

Why string inputs after integer input gets skipped in Java? [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
I am trying to input values of certain string and integer variables in Java.
But if I am taking the input of string after the integer, in the console the string input is just skipped and moves to the next input.
Here is the code
String name1;
int id1,age1;
Scanner in = new Scanner(System.in);
//I can input name if input is before all integers
System.out.println("Enter id");
id1 = in.nextInt();
System.out.println("Enter name"); //Problem here, name input gets skipped
name1 = in.nextLine();
System.out.println("Enter age");
age1 = in.nextInt();
This is a common problem, and it happens because the nextInt method doesn't read the newline character of your input, so when you issue the command nextLine, the Scanner finds the newline character and gives you that as a line.
A workaround could be this one:
System.out.println("Enter id");
id1 = in.nextInt();
in.nextLine(); // skip the newline character
System.out.println("Enter name");
name1 = in.nextLine();
Another way would be to always use nextLine wrapped into a Integer.parseInt:
int id1;
try {
System.out.println("Enter id");
id1 = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
System.out.println("Enter name");
name1 = in.nextLine();
Why not just Scanner.next() ?
I would not use Scanner.next() because this will read only the next token and not the full line. For example the following code:
System.out("Enter name: ");
String name = in.next();
System.out(name);
will produce:
Enter name: Mad Scientist
Mad
It will not process Scientist because Mad is already a completed token per se.
So maybe this is the expected behavior for your application, but it has a different semantic from the code you posted in the question.
This is your updated working code.
package myPackage;
import java.util.Scanner;
public class test {
/**
* #param args
*/
public static void main(String[] args) {
String name1;
int id1,age1;
Scanner in = new Scanner(System.in);
//I can input name if input is before all integers
System.out.println("Enter id");
id1 = in.nextInt();
System.out.println("Enter name"); //Problem here, name input gets skipped
name1 = in.next();
System.out.println("Enter age");
age1 = in.nextInt();
}
}
May be you try this way..
Instead of this code
System.out.println("Enter name"); //Problem here, name input gets skipped
name1 = in.nextLine();
try this
System.out.println("Enter name");
name1 = in.next();

How to capitalize the first letter of your name in java? [duplicate]

This question already has answers here:
How to capitalize the first letter of a String in Java?
(59 answers)
Closed 9 years ago.
Here is my code:
import java.util.Scanner;
class namedisplay {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = input.nextLine();
String capital1 = name.substring(0).toUpperCase();
String capital2 = name.substring(5).toUpperCase();
System.out.println(capital1+capital2);
}
}
The program output:
Enter your name:
anna lee
ANNA LEELEE
What I want the program to do is to capitalize only the first letters of the first name and last name, for example, Anna Lee.
System.out.println("Enter your name: ");
String name = input.nextLine();
String newName = "";
newName += name.charAt(0).toUpperCase();
newName += name.substring(1, name.length());
System.out.println(newName);
To get the first letter and capitalize, you use this name.charAt(0).toUpperCase();.
Then add that to the newName.
Then you want to add the remaining letters from name to newName. You do that by adding a substring of name
name.substring(1, name.length()); // 1 mean the substring will start at the
// second letter and name.length means the
// substring ends with the last letter

scan.nextLine does not work [duplicate]

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

Categories

Resources