How do you scan multiple strings in all containing spaces? - java

I'm attempting to scan in strings one after another and some may contain spaces. As my code functions currently it will only work if each string you type in is one word. What's the proper way to scan in consecutive lines of text, regardless of there being spaces in the line or not.
System.out.print("Enter your first name: ");
fName = scan.next();
System.out.print("Enter your last name: ");
lName = scan.next();
System.out.print("Enter your street and house number: ");
address = scan.next();
System.out.print("Enter your city: ");
city = scan.next();
System.out.print("Enter your state: ");
state = scan.next();
System.out.print("Enter your telephone number (no spaces): ");
teleNum = scan.next();
System.out.print("Enter your zip code: ");
zip = scan.next();

String[] prompts = {
"Enter your city: ",
"Enter your state: ",
};
Scanner scanner = new Scanner(System.in);
String line = "";
for (String prompt : prompts) {
System.out.println(prompt);
if (scanner.hasNextLine()) {
line += scanner.nextLine();
}
}
System.out.println(line);

Related

Difference between two codes and InputMismatchException

I am a newbie with java and the class scanners.
I have two Codes and I dont get the point why one of them throws a InputMismatchException.
I look forward to the answers.
Here both codes:
1st one with the Exception Error:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String firstName, lastName, completeName;
int age;
System.out.println("Please enter your first name: ");
firstName = sc.nextLine();
System.out.println("Please enter your last name: ");
lastName = sc.nextLine();
System.out.println("Please enter your complete name and your age: ");
completeName = sc.next();
age = sc.nextInt();
System.out.println("Your complete name is: " + completeName);
System.out.println("Your age is: " + age);
}
Console:
Please enter your first name:
Peter
Please enter your last name:
Henrik
Please enter your complete name and your age:
Peter Henrik 22
(InputMismatchException)
2nd one with no error:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String firstName, lastName;
int age;
System.out.println("Please enter your first name: ");
firstName = sc.nextLine();
System.out.println("Please enter your last name: ");
lastName = sc.nextLine();
System.out.println("Please enter your age: ");
age = sc.nextInt();
System.out.println("Your complete name is: " + firstName + " " + lastName);
System.out.println("Your age is: " + age);
}
Console:
Please enter your first name:
Peter
Please enter your last name:
Henrik
Please enter your age:
22
Your complete name is: Peter Henrik
Your age is: 22
Your first code throws InputMismatchException because sc.next() reads the first complete token ("Peter") up to the whitespace (since whitespace is the default delimiter for Scanner in Java), thus after that, the sc.nextInt() method will read "Henrik" which is a String unlike your expectation to read the age (22).
Here's what you can do instead in order to read the complete name of the user as well as the age [CONDITION: You'll have to enter age in a new line]:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String firstName, lastName,completeName;
int age;
System.out.println("Please enter your first name: ");
firstName = sc.nextLine();
System.out.println("Please enter your last name: ");
lastName = sc.nextLine();
System.out.println("Please enter your complete name: ");
completeName = sc.nextLine();
System.out.println("Please enter your age: ");
age = sc.nextInt();
System.out.println("Your complete name is: " + completeName);
System.out.println("Your age is: " + age);
}
PS: An alternate solution can be to read the complete name and the age in a single line as you did and then split up the tokens using the String split() method in Java.
Having a look at the Javadoc of Scanner#next() will tell you the following:
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
The default delimiter for the Scanner is a whitespace.
Knowing this, you provide the following input
Peter Henrik 22
and try to read this input via the following
completeName = sc.next();
age = sc.nextInt();
The call to sc.next() will read the first complete token up to the whitespace, which is "Peter".
So Henrik 22 is still available in the Scanner buffer.
Therefore sc.nextInt() will read Henrik and try to parse it to an int hence the InputMismatchException.
To read both tokens to get the complete name, simply change
completeName = sc.next();
to
completeName = sc.next() + " " + sc.next();
However, names don't always consist of only two parts. Since there could be names that more than two single tokens, you should / could do it like the following (provided you still want to enter the complete name and age in one line):
String line = sc.nextLine(); // read the whole line
// everything up to the last token is the name
completeName = line.substring(0, line.lastIndexOf(" "));
// last token is the age
age = line.substring(line.lastIndexOf(" ") + 1);

java prompt + get number before get a string contain any space (one or more)

I need get a number from prompt, and juste after I need get a String list from prompt. I have a problem. Is it OK if the 1st question ask a string with nextLine() see this post.
Java code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number:");
int num = input.nextInt();
System.out.println("Enter a name list:");
String nameList = input.nextLine();
System.out.println("Enter last name:");
String lastName = input.nextLine();
input.close();
System.out.println(num + " * " + nameList + " ** " + lastName);
}
console result:
Enter a number:
2
Enter a name list:
Enter last name:
1st response is 2 + enter
but juste after 2 + enter, the program display Enter a name list:
Enter last name:
I would use input.next() instead of input.nextLine() as next blocks for user input while nextLine moves the scanner past the current line and it buffers all the inputs until it finds a line separator.
or use nextLine() after nextInt to consume the linefeed which is left by nextInt
Solution add input.nextLine(); juste after int num = input.nextInt();.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number:");
int num = input.nextInt();
input.nextLine();
System.out.println("Enter a name list:");
String nameList = input.nextLine();
System.out.println("Enter last name:");
String lastName = input.nextLine();
input.close();
System.out.println(num + " * " + nameList + " ** " + lastName);
}
console:
Enter a number:
2
Enter a name list:
aa bb cc
Enter last name:
dd
2 * aa bb cc ** dd

nextLine printing out 2 at a time? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(25 answers)
Closed 5 years ago.
So everything compiles fine but when I run it the line asking for city and the line asking for zip both print out at the same time. I need them to print individually so the user can answer.
import java.util.Scanner;
public class PersonalInfo
{
public static void main(String[] args)
{
String name, city, state, major;
int zip, phone, address;
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your name: ");
name = scanner.nextLine();
System.out.println("please enter your address number: ");
address = scanner.nextInt();
System.out.println("Please enter the name of the city you live in: ");
city = scanner.nextLine();
System.out.println("Please enter your zip code: ");
zip = scanner.nextInt();
System.out.println("Please enter the name of the state you live in: ");
state = scanner.nextLine();
System.out.println("Please enter your phone number(format ##########): ");
phone = scanner.nextInt();
System.out.println("Please enter your college major: ");
major = scanner.nextLine();
System.out.println(name + "\n" + address + "," + city + "," + state +
"," + zip + "\n" + phone + "\n" + major);
}
}
The only method that consume newline of the input is nextLine(), so if you use nextInt() and then you want to capture anything else you have to call a nextLine() after you call nextInt().
For example:
System.out.println("please enter your address number: ");
address = scanner.nextInt();
scanner.nextLine();
System.out.println("Please enter the name of the city you live in: ");
city = scanner.nextLine();
Output:
please enter your address number:
567
Please enter the name of the city you live in:
Puerto Montt

Scanner nextLine() occasionally skips input

Here is my code
Scanner keyboard = new Scanner(System.in);
System.out.print("Last name: ");
lastName = keyboard.nextLine();
System.out.print("First name: ");
firstName = keyboard.nextLine();
System.out.print("Email address: ");
emailAddress = keyboard.nextLine();
System.out.print("Username: ");
username = keyboard.nextLine();
and it outputs this
Last name: First name:
Basically it skips letting me enter lastName and goes straight to the prompt for firstName.
However, if I use keyboard.next() instead of keyboard.nextLine(), it works fine. Any ideas why?
Let me guess -- you've got code not shown that uses the Scanner above the attempt to get lastName. In that attempt, you're not handling the end of line token, and so it's left dangling, only to be swallowed by the call to nextLine() where you attempt to get lastName.
For example, if you have this:
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = keyboard.nextInt(); // dangling EOL token here
System.out.print("Last name: ");
lastName = keyboard.nextLine();
You're going to have problems.
One solution, whenever you leave the EOL token dangling, swallow it by calling keyboard.nextLine().
e.g.,
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = keyboard.nextInt();
keyboard.nextLine(); // **** add this to swallow EOL token
System.out.print("Last name: ");
lastName = keyboard.nextLine();

Prompting Multiple inputs on a Single line

I have a question. I know you can prompt a user multiple times with scanner as so
public static void main(String[] args) {
String First;
String Last;
int Age;
Scanner input = new Scanner(System.in);
System.out.print("What is the First name of person?");
First = input.next();
System.out.print("What is the Last name of person?");
Last = input.next();
System.out.print("What is the Age of person?");
Age = input.next();
}
But is there a way there to prompt all in one line?
For example I want to enter
Console-What is the First, Last, and Age of the person?
User- First Last Age
First, Java variables start with a lower case letter by convention (yours look like class names). Second, this
Age = input.next();
gives you a compiler error. Because Age is an int. You can certainly split the single line as others have suggested, but you can also construct a Scanner(String) and use it with something like
Scanner input = new Scanner(System.in);
System.out.println("Please enter the first name last name and age of the person: ");
System.out.println("(first last age)");
String line = input.nextLine();
Scanner scan = new Scanner(line);
String first = scan.next();
String last = scan.next();
int age = scan.nextInt();
System.out.printf("Person: %s, %s (%d)%n", last, first, age);
Grab a line and split the string:
Scanner input = new Scanner(System.in);
System.out.print("What is the First, Last, and Age of the person?");
String line = input.nextLine();
String[] parts = line.split(" ");
if(parts.length < 3){
//error, ask again
}
else{
String first = parts[0];
String last = parts[1];
String age = parts[2];
}

Categories