This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Difference between next() and hasNext() in java collections
(5 answers)
Closed 1 year ago.
I am trying to input some text using a scanner but I am having an issue where the output for name is skipping and going to the next line. If I try to input name it will skip and go straight to surname. Can anyone please assist
Scanner input = new Scanner(System.in);
if(input.hasNext("1")){
System.out.print("Input your Name: ");
name = input.next();
System.out.print("Input your Surname: ");
surname = input.next();
System.out.print("Input your ID: ");
id = input.nextInt();
System.out.print("Input the training program: ");
trainingProgramme = input.next();
registerApplicant(name, surname, id, trainingProgramme);
System.out.print("Congratulations! You have registered for the " +trainingProgramme+ " Training Programme");
}
The output:
debug:
Welcome to the Codex Registration system:
Please select an option:
1 Register for a training program
2 Check registration details
3 Exit program
1
Input your Name: Input your Surname: Blah
Input your ID: 6787
Input the training program: Java
Congratulations! You have registered for the Java Training ProgrammeWelcome to the Codex Registration system:
Please select an option:
The problem is, that with input.hasNext("1") you are not skipping the input 1 from the user.
So the input 1 will be stored to your variable name.
Therefore you need to skip this input. One possibility is to put a input.next() before reading the name like this:
Scanner input = new Scanner(System.in);
if(input.hasNext("1")){
input.next(); //skip the input of choice
System.out.print("Input your Name: ");
name = input.next();
System.out.print("Input your Surname: ");
surname = input.next();
System.out.print("Input your ID: ");
id = input.nextInt();
System.out.print("Input the training program: ");
trainingProgramme = input.next();
registerApplicant(name, surname, id, trainingProgramme);
System.out.print("Congratulations! You have registered for the " +trainingProgramme+ " Training Programme");
}
or (imho the better way) you use a variable for the choice-input:
Scanner input = new Scanner(System.in);
String selection = input.next();
if("1".equals(selection)){
//...
}
The problem is that a new line character added to end of the every scanner-
You can manually set the delimiter of the Scanner:
scanner = new Scanner(...).useDelimiter(" "); //To use only space as a delimiter.
Try to use a new variable for choice.
Scanner input = new Scanner(System.in);
String choice = input.next();
if (choice =="1") {
System.out.print("Input your Name: ");
name = input.next();
System.out.print("Input your Surname: ");
surname = input.next();
System.out.print("Input your ID: ");
id = input.nextInt();
System.out.print("Input the training program: ");
trainingProgramme = input.next();
registerApplicant(name, surname, id, trainingProgramme);
System.out.print("Congratulations! You have registered for the " +trainingProgramme+ " Training Programme");
}
Related
I've been looking for an answer to this for a while, but for some reason, none of them seem to work.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter full name (last, first)");
String[] personalInfo = scanner.next().split(", ");
String firstName = personalInfo[1];
String lastName = personalInfo[0];
System.out.println("Your info: " + firstName + " " + lastName);
There is my code. I'm basically trying to obtain the personal info, which would be the first and last name. I want to split the first and last name into 2 different strings, but whenever I try to print this, I get the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 > out of bounds for length 1
at Fines.main(Fines.java:11)
I'm confused because I even started the array with 0 like I was supposed to.. I just don't understand what is going incorrectly.
Please give me a hand - thanks in advance!
What you want is scanner.nextLine() to read from standard input up until end of line. Then split would work as you expected.
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter full name (last, first)");
String[] personalInfo = scanner.nextLine().split(", ");
String firstName = personalInfo[1];
String lastName = personalInfo[0];
System.out.println("Your info: " + firstName + " " + lastName);
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 1 > out of bounds for length 1 at Fines.main(Fines.java:11)
As the size of the personalInfo is 1 not 2.
use nextLine() instead of next() because next() will only return the input that comes before a space.
String[] personalInfo = scanner.next().split(", "); should be
String[] personalInfo = scanner.nextLine().split(", ");
You might want to read this What's the difference between next() and nextLine() methods from Scanner class?
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Please enter full name (last, first)");
String firstName = scan.next();
String lastName = scan.next();
System.out.println("Your info: " + firstName + ' ' + lastName);
}
scanner.next() read until next delimiter (space by default), so it ready only the firstName. Just replace it with scanner.nextLine() or use scanner.next() two times.
This code is supposed to print the user's name when they enter it and limit it's length to 20 characters, but it only works when the user's name is longer than 20 chars. I get en error when it's below 20. Any ideas on how to fix this?
Thank you.
String name;
Scanner textIn = new Scanner(System.in);
System.out.print("Enter your Name ");
name = textIn.nextLine();
String cutName = name.substring(0, 20);
if (name.length()>20) {
name = cutName;
System.out.print("Hello " +name+"!");
}
Just take the lower index between 20 and the String 's length .
name.substring(0, Math.min(20,name.length()));
If you place your String cutName inside the if, the error should disappear. You cannot take a substring from a string that is longer than the String itself.
if (name.length()>20) {
String cutName = name.substring(0, 20);
name = cutName;
}
System.out.print("Hello " +name+"!");
Scanner textIn = new Scanner(System.in);
System.out.print("Enter your Name ");
name = textIn.nextLine();
if(name.length()>20)
name = name.substring(0,20);
The assignment:
Write a program (Greetings) that prompts the user to enter the first name, the last name, and year of birth, then it returns a greetings message
in proper format (see the example below).
Create a method(s) that accept the scanner and a prompt as parameters and return the user input. A separate method should accept the user input results as parameters, format and print the results. No print statement or scanner input should happen inside main(). Here is an example dialogue with the user:
Please enter your first name:
tom
Please enter your last name:
cruise
Please enter your year of birth:
1962
Greetings, T. Cruise! You are about 53 years old.
I finished the code, but right now it is giving me a compilation error. How do i fix it?
import java.util.*;
public class Greetings {
public static void main(String[] args) {
Scanner newscanner = new Scanner(System.in);
String ask = ("Please enter your first name: ");
String ask2 = ("Please enter your last name: ");
String ask3 = ("Please enter your year of birth: ");
public static String getString(Scanner newscanner, String ask, String ask2, String ask3){
System.out.println(ask);
String first = newscanner.next();
String firstletter = first.substring(0,1).toUpperCase() ;
return firstletter;
System.out.println(ask2);
String second = newscanner.next();
int x = second.length();
String y = second.substring(0, x).toLowerCase();
String lastname = y.substring(0,1).toUpperCase();
return lastname;
System.out.println(ask3);
int third = newscanner.nextInt();
int age = (2015 - third);
return age
System.out.println("Greetings, "+ firstletter + ". " + lastname+"!" +" You are about " + age + " years old");
}
}
}
Hard to read, but I think you actually have the getString() method inside your main() method - it needs to be after it, and only be called from inside main(), not defined there.
This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 9 years ago.
System.out.print("Name : ");
String name = in.nextLine();
System.out.print("Age : ");
int age = in.nextInt();
System.out.print("City : ");
String city = in.nextLine();
the output will be :
Name : test
Age : 20
BUILD SUCCESSFUL
when i debug them, it won't read the user input for "city" . but when i changed the data type for "age" to string, it will read. how can i kept the data type of age to int with the system reading the user inputs for city ?
As there is still a new line character in the buffer after reading the age, change it to..
System.out.print("Name : ");
String name = in.nextLine();
System.out.print("Age : ");
int age = in.nextInt();
//add
in.nextLine();
System.out.print("City : ");
String city = in.nextLine();
Try this,
System.out.print("Age : ");
int age = Integer.parseInt(in.nextLine());
There is still a new line character in the buffer after reading the age. Try adding a in.nextLine before you ask for the city value.
This always gives me a headache. I am trying to read and save multiple-word Strings for the fields "name" and "malady" within a while loop. Here is my code:
while(OR1.isFull() == false || OR2.isFull() == false)
{
// prompt for next request
System.out.println("Enter patient info:");
// read patient info
System.out.print("Name: ");
String name = input.nextLine();
input.nextLine();
System.out.print("Malady: ");
String malady = input.nextLine();
input.nextLine();
System.out.print("Priority: ");
int priority = input.nextInt();
// store patient info
Patient patient = new Patient(name, malady, priority);
OR1.add(patient);
} // end while
System.out.println("List of patients scheduled for Operating Room 1");
while(OR1.isEmpty() == false)
{
// pop and print root
System.out.print(OR1.remove());
}
And here is what my console input and output looks like:
Enter patient info:
Name: John Doe
Malady: Broken hip
Priority: 6
List of patients scheduled for Operating Room 1
Patient: Malady: Broken hip Priority: 6
// end console output.
Notice that it did not record the value I entered for "Name," and also that it prompted for an extra line of input after obtaining "Malady" (required me to press enter again to get it to ask for the next input, "Priority").
I have read the documentation at http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html. I have tried different combinations of next() and nextLine(). I just don't get it.
Problem solved by changing the code to the following:
// read patient info
System.out.print("Name: ");
input.nextLine();
String name = input.nextLine();
System.out.print("Malady: ");
String malady = input.nextLine();
System.out.print("Priority: ");
int priority = input.nextInt();
Though I am still confused about how this silly scanner works =/
I believe it should work for just:
// read patient info
System.out.println("Name: ");
String name = input.nextLine();
System.out.println("Malady: ");
String malady = input.nextLine();
System.out.println("Priority: ");
int priority = input.nextInt();
Perhaps the problem is in the Patient constructor or something?
Problem solved by changing the code to the following:
// read patient info
System.out.print("Name: ");
input.nextLine();
String name = input.nextLine();
System.out.print("Malady: ");
String malady = input.nextLine();
System.out.print("Priority: ");
int priority = input.nextInt();