This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
The purpose of this application is to get the full name of a user, and split them up. The results are printed.
if(nameParts.length < 2|| nameParts.length > 3) is somehow gaining control from the loop after it runs a 2nd time or beyond. I would assume that name and nameParts should be getting values assigned to them once again. Why is this happening, and how can I fix this?
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String choice = "y";
System.out.println("Welcome to the name parser.\n");
while(choice.equalsIgnoreCase("y")) {
System.out.print("Enter a name: ");
String name = sc.nextLine();
String[] nameParts = nameSeperate(name);
if(nameParts.length < 2|| nameParts.length > 3) {
System.out.println("Please enter your full name or your first and last name.");
continue;
}
else if(nameParts.length == 2) {
System.out.println("First Name: " + nameParts[0]);
System.out.println("Last Name: " + nameParts[0]);
}
else {
System.out.println("First Name: " + nameParts[0]);
System.out.println("Middle Name: " + nameParts[1]);
System.out.println("Last Name: " + nameParts[2]);
}
System.out.println("Would you like to enter another name? (y/n)");
choice = sc.next();
}
}
Here is the output:
Welcome to the name parser.
Enter a name: Alfons Pineda
First Name: Alfons
Last Name: Pineda
Would you like to enter another name? (y/n)
y
Enter a name: Please enter your full name or your first and last name.
Enter a name: Alfons Pineda
First Name: Alfons
Last Name: Pineda
Would you like to enter another name? (y/n)
n
I am not sure, but for your first scan you use sc.nextLine() and for the second one just sc.next(). Maybe using sc.nextLine() also for the second statement would help. It could be, that the \n was not read by sc.next().
Therefore in the second loop only the newline would be read by the first scan.
Related
This question says ask for the 'First Name' and the 'Last Name' from the user and then show the message Welcome with the full name of the user . also make sure that the user does not enter his/her full name in the first Text Field which asks for First Name only
I thought that if the user enters his/her full name in the first text field , we can know that from the fact that he/she entered a space or (' ') or not . If not we can simply show the message Welcome + full name . However it didn't work the way I thought it would ... Can somebody help me with itenter image description here
If I understand you the below will work accomplish what you need by ignoring the data after the space and asking the user for their last name.
code:
public static void main(String[] args) {
// Properties
Scanner keyboard = new Scanner(System.in);
String firstName, lastName
// Ask the user for their first name
System.out.println("What is your first name? ");
System.out.print("--> "); // this is for style and not needed
firstName = keyboard.next();
// Ask the user for their last name
System.out.println("What is your last name? ");
System.out.print("--> "); // this is for style and not needed
lastName = keyboard.next();
// Display the data
System.out.println("Your first name is : " + firstName);
System.out.println("Your last name is : " + lastName);
}
There is actually a few ways you can do this, but if I understand your question correctly a simple way would be below, which is from http://math.hws.edu/javanotes/c2/ex6-ans.html and helped me understand Java more when I was learning it, you just would alter it to your needs.
code:
public class FirstNameLastName {
public static void main(String[] args) {
String input; // The input line entered by the user.
int space; // The location of the space in the input.
String firstName; // The first name, extracted from the input.
String lastName; // The last name, extracted from the input.
System.out.println();
System.out.println("Please enter your first name and last name, separated by a space.");
System.out.print("? ");
input = TextIO.getln();
space = input.indexOf(' ');
firstName = input.substring(0, space);
lastName = input.substring(space+1);
System.out.println("Your first name is " + firstName + ", which has "
+ firstName.length() + " characters.");
System.out.println("Your last name is " + lastName + ", which has "
+ lastName.length() + " characters.");
System.out.println("Your initials are " + firstName.charAt(0) + lastName.charAt(0));
}
}
edit:
If this doesn't make sense I can give a better explanation with a better example with more detail.
More notes on similar problems.
https://www.homeandlearn.co.uk/java/substring.html
The problem with your code is, that you check every single charackter and then do the if/else for every single charackter. which means if the last charackter is not a whitespace it will at the end process the else tree.
The solution is to just check once:
if(fn.contains(' '){
//Do what you want to do, if both names were entered in the first field
}else{
//Everything is fine
}
I am using the scanner in java and am trying to enter a space in my input for option 2 (removing a user from my hashmap) but when I add a space in my answer I get an InputMismatchException. while researching I came across this thread Scanner Class InputMismatchException and Warnings that says to use this line of code to solve the issue: .useDelimiter(System.getProperty("line.separator")); i have added this and now my option 2 goes into a never-ending loop of me inputting data. Here is my code:
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
AddressBook ad1 = new AddressBook();
String firstName="";
String lastName="";
String key="";
int choice=0;
do{
System.out.println("********************************************************************************");
System.out.println("Welcome to the Address book. Please pick from the options below.\n");
System.out.println("1.Add user \n2.Remove user \n3.Edit user \n4.List Contact \n5.Sort contacts \n6.Exit");
System.out.print("Please enter a choice: ");
choice = scan.nextInt();
if(choice==1){
//Add user
System.out.print("Please enter firstname: ");
firstName=scan.next();
System.out.print("Please enter lastname: ");
lastName=scan.next();
Address address = new Address();
key = lastName.concat(firstName);
Person person = new Person(firstName,lastName);
ad1.addContact(key,person);
System.out.println("key: " + key);
}
else if(choice==2){
//Remove user
System.out.println("Please enter name of user to remove: ");
scan.useDelimiter(System.getProperty("line.separator"));
key=scan.next();
System.out.println("name:" + key);
ad1.removeContact(key);
}
else if(choice==3){
//Edit user
}
else if(choice==4){
//List contact
ad1.listAllContacts();
}
else if(choice==5){
//Sort contacts
}
}while(choice!=6);
}
}
The reason why I need to use a space is to remove a user from my hashmap I need to enter their full name as the key is a concatenation of their last and firstname, any help will be appreciated
nextInt() behaves similar to next() that is when it read a line it places the cursor behind it.
Example:
You give 6 as input
6
^(scanner's cursor)
So next time when you call nextLine(). It will return the whole line after that cursor which is empty in this case.
To fix this issue you need to call an extra nextLine() so that the Scanner closes the previous line it was reading and move on to the next line.
You could do this
System.out.print("Please enter a choice: ");
choice = scan.nextInt(); // Reads the int
scan.nextLine(); // Discards the line
And in choice 2 since you want full name of user you could just use nextLine() to get whole line along with space.
//Remove user
System.out.println("Please enter full name of user to remove: ");
key=scan.nextLine();
System.out.println("name:" + key);
ad1.removeContact(key);
Or you could do something similar to what you did in choice 1
System.out.print("Please enter firstname: ");
firstName=scan.next();
System.out.print("Please enter lastname: ");
lastName=scan.next();
key = lastName.concat(firstName);
System.out.println("name:" + key);
ad1.removeContact(key);
scan.nextLine(); // This is will make sure that in you next loop `nextInt()` won't give an input mismatch exception
I want the user to only enter his age. So I did this program :
Scanner keyb = new Scanner(System.in);
int age;
while(!keyb.hasNextInt())
{
keyb.next();
System.out.println("How old are you ?");
}
age = keyb.nextInt();
System.out.println("you are" + age + "years old");
I found how to prevent user from using string by using the while loop with keyb.hasNextInt(), but how to prevent him from using the whitespace or from entering more input than his age ?
For example I want to prevent this kind of typing "12 m" or "12 12"
Also, how can I clear all existing data in the buffer ? I'm facing an infinite loop when I try to use this :
while(keyb.hasNext())
keyb.next();
You want to get the whole line. Use nextLine and check that for digits e.g.
String possibleAge = "";
do {
System.out.println("How old are you ?");
possibleAge = keyb.nextLine();
} while (!possibleAge.matches("\\d+"))
Your problem is that the default behaviour of Scanner is to use any whitespace as the delimiter. This includes spaces. This means that a 3 a is in fact three tokens, not one. You can change the delimiter to a new line so that a 3 a becomes a single token, which will then return false for hasNextInt.
I've also added an initial question, because in your example the first input was taken before asking any questions.
Scanner keyb = new Scanner(System.in);
keyb.useDelimiter("\n"); // You can try System.lineSeparator() but it didn't work in IDEA
int age;
System.out.println("How old are you?");
while(!keyb.hasNextInt())
{
keyb.next();
System.out.println("No really. How old are you?");
}
age = keyb.nextInt();
System.out.println("You are " + age + " years old");
String age = "11";
if (age.matches(".*[^0-9].*")) {
System.out.println("Invalid age");
} else {
System.out.println("valid age");
}
If age contains other then digits then it will print invalid age.
I'm sort of new at working with Java. I'm working on a program that takes in student names and their IDs, and when the correct ID is inputted afterwards, it spits out that student's information. The sample output would sort of look like this: How many students would you like to input? (2) What are their names? (Sally, Jack) What are their IDs? (2332, 5631) Would you like to search for a student? (Y) Please input their ID: (2332) We found Sally!
Here is a snippet of the code that searches back for the Student:
System.out.println("Would you like to search for a student?");
String answer = scan.next();
if (answer.equals("Y")) {
System.out.println("Please enter an ID:");
int id = scan.nextInt();
boolean found = Student.lookupID(list, id);
if(found)
System.out.println("Student was found. This student is: " + studentName + ", Student ID " + id); //fix this
else
System.out.println("Error");
}
else {
System.out.println("Thanks for using this system!");
}
}
}
Right now, I'm trying to loop the code, so that the Output would now look like this: How many students would you like to input? (3) What are their names? (Sally, Jack, Rick) What are their IDs? (2332, 5631, 3005) Would you like to search for a student? (Y) Please input their ID: (2332) We found Sally! Would you like to search for another student? (Y) Please input their ID: (5631) We found Jack! Would you like to search for another student? (N) Thanks for using our system!
Would someone be able to help me with this?
You need to reset id to program be able to get new id.Try correct your code like this :
System.out.println("Would you like to search for a student?");
String answer = scan.next();
int id = 0; //RESET THE ID TO BE ABLE REPLAYIN WORK!
if (answer.equals("Y")) {
System.out.println("Please enter an ID:");
id = scan.nextInt();
boolean found = Student.lookupID(id);
if (found)
System.out.println("Student was found. This student is: " + studentName + ", Student ID " + id); // fix
// this
else
System.out.println("Error");
} else {
System.out.println("Thanks for using this system!");
}
I'm looking for a way to basically give back to the user some console output that looks identical to what they type and then prompt again for more input. The problem is I have a method that modifies each String discovered that does not consist of white space.
At the end of each sentence given by the user, I am trying to figure out a way to get a newline to occur and then for the prompt to output to the console again saying "Please type in a sentence: ". Here is what I have so far...
System.out.print("Please type in a sentence: ");
while(in.hasNext()) {
strInput = in.next();
System.out.print(scramble(strInput) + " ");
if(strInput.equals("q")) {
System.out.println("Exiting program... ");
break;
}
}
Here is what is displaying as console output:
Please type in a sentence: Hello this is a test
Hello tihs is a tset
And the cursor stops on the same line as "tset" in the above example.
What I want to happen is:
Please type in a sentence: Hello this is a test
Hello tihs is a tset
Please type in a sentence:
With the cursor appearing on the same line as and directly after "sentence:"
Hopefully that helps clear up my question.
Try this, I didn't test it but it should do what you want. Comments in the code explain each line I added:
while (true) {
System.out.print("Please type in a sentence: ");
String input = in.nextLine(); //get the input
if (input.equals("quit")) {
System.out.println("Exiting program... ");
break;
}
String[] inputLineWords = input.split(" "); //split the string into an array of words
for (String word : inputLineWords) { //for each word
System.out.print(scramble(word) + " "); //print the scramble followed by a space
}
System.out.println(); //after printing the whole line, go to a new line
}
How about the following?
while (true) {
System.out.print("Please type in a sentence: ");
while (in.hasNext()) {
strInput = in.next();
if (strInput.equals("q")) {
System.out.println("Exiting program... ");
break;
}
System.out.println(scramble(strInput) + " ");
}
break;
}
The changes are:
You should be printing "Please type in a sentence: " inside a loop to have it print again.
I think you want to check if the strInput is "q" and exit BEFORE printing it, i.e. no need to print the "q", or is there?
Use println to print the scrambled strInput so that the next "Please type in a sentence: " appears in the next line, and the cursor appears on the same line as " ... sentence: " because that is output by System.out.print (no ln)