How to read Strings with spaces inside while loop (Java) - java

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

Related

Scanner is skipping one line and going to the next [duplicate]

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

Splitting a Scanner Input Into Strings

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.

How to check the user input is an integer or not with Scanner?

I want the country codes are integer that input by the user. I want an error message to be show when user inputs a code which is not an integer. How can I do this? The program is to ask user to enter country name and country code. In which user will input the country code. But if user inputs a character I want a message to be shown saying Invalid Input.
System.out.println("Enter country name:");
countryName = in.nextLine();
System.out.println("Enter country code:");
int codeNumber = in.nextInt();
in.nextLine();
If the input is not an int value, then Scanner's nextInt() (look here for API) method throws InputMismatchException, which you can catch and then ask the user to re-enter the 'country code' again as shown below:
Scanner in = new Scanner(System.in);
boolean isNumeric = false;//This will be set to true when numeric val entered
while(!isNumeric)
try {
System.out.println("Enter country code:");
int codeNumber = in.nextInt();
in.nextLine();
isNumeric = true;//numeric value entered, so break the while loop
System.out.println("codeNumber ::"+codeNumber);
} catch(InputMismatchException ime) {
//Display Error message
System.out.println("Invalid character found,
Please enter numeric values only !!");
in.nextLine();//Advance the scanner
}
One simple way of doing it, is reading a line for the numbers as you did with the name, and then checking witha Regex (Regular Expression) to see if contains only numbers, with the matches method of string, codeNumber.matches("\\d+"), it returns a boolean if is false, then it's not a number and you can print your error message.
System.out.println("Enter country name:");
countryName = in.nextLine();
System.out.println("Enter country code:");
String codeNumber = in.nextLine();
if (codeNumber.matches("\\d+")){
// is a number
} else {
System.out.println("Please, inform only numbers");
}
You can do something like this, by first getting the input as a string, then try to convert the string to an integer, then outputs an error message if it can't:
String code= in.nextLine();
try
{
// the String to int conversion happens here
int codeNumber = Integer.parseInt(code);
}
catch (NumberFormatException nfe)
{
System.out.println("Invalid Input. NumberFormatException: " + nfe.getMessage());
}
You could instead check hasNextInt then call nextInt
int codeNumber;
System.out.println("Enter country code:");
if(in.hasNextInt())
{
codeNumber = in.nextInt();
}
else
{
System.out.println("Invalid Code !!");
}
If you are creating your own custom exception class, then use regex to check if the input string is an integer or not.
private final String regex = "[0-9]";
Then, check if the input follows the regex pattern.
if (codeNumber.matches(regex)) {
// do stuff.
} else {
throw new InputMismatchException(codeNumber);
}
You can use build in InputMismatchException if you are not creating your custom exception handler.

user input string and integers in Java [duplicate]

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.

Make an email list, by entering only recipient names

I want to make a simple code, that prompts you to enter names, separated by comma or just a space, and when you click enter, to take every one word you entered, and put a #gmail.com at the end of it, how can I do it?
That's what I have for now
Scanner input = new Scanner(System.in);
String mail = "#gmail.com";
String names;
System.out.println("Enter names: ");
names = input.next();
System.out.println(names + mail);
This should be everything you asked for, if you put a list of names separated by commas it will loop through them, otherwise it will just print a single name.
Scanner input = new Scanner(System.in);
String mail = "#gmail.com";
System.out.println("Enter names: ");
String names = input.next();
if(names.contains(",")) {
for(String name : names.split(",")) {
System.out.println(name + mail);
}
} else {
System.out.println(names + mail);
}
Hope that helps.
Not knowing what language this is, here's the pseudo-code:
names = input.next();
namesArray = names.split(" ") -- replace with your preferred delimiter
foreach name in namesArray
print name + mail

Categories