input mismatch exception while using space in between words - java

I'm working on a project and I already finished it, I have really simple problem which makes me really confused. I'm trying to ask a user to enter a number from a menu and depending on that different things happen, but I get input mismatch exception whenever I type space in between words. I get that error on the last line of the code, please check my code below, Thanks.
System.out.println("Enter: " + "\n1.Enter Name" +"\n2.Enter another name" + "\n3.Exit");
int userChoice = kb.nextInt();
while(userChoice != 3) {
if(userChoice == 1) {
System.out.println("Enter name");
String name = kb.next();
}
if(userChoice == 2) {
System.out.println("Enter anohter name");
String anotherName = kb.next();
}
if(userChoice == 3)
break;
System.out.println("Enter: " + "\n1.Enter Nmame" +"\n2.Enter another name" + "\n3.Exit");
userChoice = kb.nextInt();
}

The issue is with your usage of Scanner#next(), in combination with wanting to input multiple "words" sepearted by a whitespace for example. (Disclaimer: I understand your question in the way that you want to enter multiple words for the "name" input, this answer takes that as a prerequisite)
See following excerpt from the Scanner#next() Javadoc:
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. So when you request a name from the user, and the user wants to enter "John Doe", only "John" will be read, and "Doe" will be left, most likely causing the error you are seeing.
The workaround I would propose is to use nextLine() to read the whole line while providing each input line by line.
However, be aware of this issue: Scanner is skipping nextLine() after using next() or nextFoo()?
Keeping that in mind, I would modify your code as follows:
String name = "";
String anotherName = "";
System.out.println("Enter: " + "\n1.Enter Nmame" +"\n2.Enter another name" + "\n3.Exit");
int userChoice = kb.nextInt();
while(userChoice != 3) {
kb.nextLine(); // consumes the newline character from the input
if(userChoice == 1) {
System.out.println("Enter name");
name = kb.nextLine(); // reads the complete line
// do something with name
} else if (userChoice == 2) {
System.out.println("Enter another name");
anotherName = kb.nextLine(); // reads the complete line
// do something with anotherName
}
System.out.println("Enter: " + "\n1.Enter Nmame" +"\n2.Enter another name" + "\n3.Exit");
userChoice = kb.nextInt();
}
Sidenotes:
I moved the declaration of your name and anotherName variables, as they don't have to be re-declared everytime.
However you should actually do something with them (e.g. save them in a list, or create some object with them) otherwise they will be lost on the next loop iteration.
You can omit the check for if (userChoice == 3) since this would never happen in combination with the while (userChoice != 3).
Example input:
Enter:
1.Enter Nmame
2.Enter another name
3.Exit
1
Enter name
John Doe
1.Enter Nmame
2.Enter another name
3.Exit
3

Related

How to ask user for ONLY one word string input and produce error prompt in a try-catch block

EDIT: I figured it out! I got rid of the try-catch block because it just didn't work the way I wanted it to. The code below is my final one. Thank you to everyone who responded to this question.
I am trying to code a to-do list program. One function of this program is to search for the entries inside the string array. The user should only input a ONE WORD keyword so if the user inputs more than one word or none, a prompt should show telling the user to try again. The code I've written so far is inside a try-catch statement. Using next() scanner only takes the first word and disregards the rest when inputting a multiple-word keyword, instead of producing an Exception. Here is my code for it:
case 2:
String searchKeyword;
int success = 0;
while(success==0) {
System.out.print(">> Enter 1 keyword: ");
searchKeyword = sc.nextLine();
String splitSearchKeyword[] = searchKeyword.split(" ");
if (splitSearchKeyword.length == 1) {
if(Quinones_Exer2.searchToDoList(searchKeyword, todoList)==-1) {
System.out.println(">> No item found with that keyword!");
System.out.println();
}
else {
System.out.println(">> Found one item!");
System.out.println("("+(Quinones_Exer2.searchToDoList(searchKeyword, todoList)+1)+")"+" "+todoList[Quinones_Exer2.searchToDoList(searchKeyword, todoList)]);
System.out.println();
}
success++;
}
else {
System.out.println(">> Please input a single word keyword!");
System.out.println();
}
}
break;
}```
Use Scanner.nextLine() then split the supplied string. If the length of array is greater than 1 or the supplied string is empty then issue an invalid entry message and have the User enter the string over again:
while(tries2 == 0) {
searchKeyword = "";
while (searchKeyword.isEmpty()) {
System.out.println("Enter 1 keyword: ");
searchKeyword = sc.nextLine().trim();
if (searchKeyword.isEmpty() || searchKeyword.split("\\s+").length > 1) {
System.out.println("Invalid Entry! {" + searchKeyword
+ "You must supply a single Key Word!");
searchKeyword = "";
}
}
tries2++;
// ... The rest of your code ...
}
From the docs of Scanner.next():
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
You would need to call next() again to get the the rest of the input.
Much simpler would be to use Scanner.nextLine() to get entire line and then use String.split() with whatever delimiter you are using to get an array of all inputted keywords.
Edit: Scanner.next(pattern) may do what you are looking for. It throws InputMismatchException if the input does not match provided pattern(regex). Example:
scanner.next("^[a-zA-Z]+$")
This requires the entire line to consist of lower and/or upper case letters and nothing else.

How to prevent Java scanner from inputing spaces

I'm trying to prevent the user from inputting spaces or no values.
but nothing works. Even with no entered values program goes further without printing my error. What am I doing wrong?
my code example
Scanner nameScan = new Scanner(System.in);
System.out.print("Input your name: ");
String newcomer = nameScan.nextLine();
player.setName(newcomer);
String userName = player.getName();
userName = userName.trim();
if (userName.length()==0) {
System.out.println(" ");
System.out.println("You have to set up a player name first... ");
System.out.println(" ");
}
else {...
As #11thdimension said, you have to validate the input.
You can do something like:
if (newcomer.isEmpty()) {
System.out.println("Please write something");
}
Or you can do a while loop and keep asking for a correct input.
Your code
if(username.length() == 0)
will not check whether the username contains space because space is counted towards the length of the String.
To check for empty String input(which may contain space(s)), you can do:
if("".equals(username.replaceAll("\\s+",""))) //or
if("".equals(username.trim()) //or
if(username.isEmpty())
Further more, you would want to use a do-while loop for validation instead of using an if-statement.

A loop that lets a user enter strings until "q" for quit

Kind of stumped. I need the following to loop from the validation point(checks for a comma) so a user can enter text over and over again until "q" is pressed for quitting. I tried putting two loops in there, but I don't know how to repeat the same thing over and over again. I need the parsing to stay in there for the assignment.
Thanks.
p = 1;
while(!userName.contains(",")){
System.out.println("Error: No comma in string ");
System.out.println("Enter input string: ");
userName = scnr.nextLine();
p++;
}
userName = userName.replace(",", "");
inSS = new Scanner(userName);
firstName = inSS.next();
lastName = inSS.next();
System.out.println("First word: " +firstName );
System.out.println("Second word: " +lastName);
p++;
}
}
Have you considered using an if statement and break?
The break statement leaves the current loop. So, for example, you could add
if(scnr.nextLine().equals("q")){
break;}
That will leave the while loop, if that's what you're asking.

Scanner input skipping next input

I am now having a difficult time fixing this problem.
So, I have this code snippet here which asks 3 input from the user.
case 0:
String accnum,pin,name;
System.out.print("Enter account name: ");
name = input.nextLine();
System.out.print("Enter account number: ");
accnum = input.next();
System.out.print("Enter account PIN: ");
pin = input.next();
atm.set_accinfos(name,accnum,pin);
//System.out.print(atm.return_acc() + "\t" + atm.return_pin() + "\n");
break;
But everytime I run it, it always skips the input for the String "name", I tried using input.next(); on it and it works but then it will now skip the input for String "accnum".
EDIT: It also just happens if the input from "name" has a space on it, for example : John Doe.
Am I missing something here?
The nextLine() gobbles the newline character produced by the next() of account pin (when you hit enter). So, it won't ask for name. Add input.nextLine() after pin = input.next(); and try
Try This. i think problem with next(). since next reads input as tokens with default delimiter(i think space is the default delimiter).:
case 0:
String accnum,pin,name;
System.out.print("Enter account name: ");
name = input.nextLine();
System.out.print("Enter account number: ");
accnum = input.nextLine();
System.out.print("Enter account PIN: ");
pin = input.nextLine();
atm.set_accinfos(name,accnum,pin);
//System.out.print(atm.return_acc() + "\t" + atm.return_pin() + "\n");
break;
If you're using input anywhere before this block of code, then you need to be sure to call nextLine earlier on.
If you use next instead, then your input stream will still contain a new line character (\n). Thus, when you start this block of code with nextLine, that call will take the previous \n and not the name which was just entered.
In general, if your Scanner is reading System.in, then you should use nextLine everywhere. next, nextInt, and the other next methods are meant for more predictable data.
Okay, thats for the help everyone, I managed to fix it by adding "input.nextLine();" before "name = input.nextLine();"

How to check entered String in a loop with condition?

I want to write a program, which is checks an entered String of the user for a given char limits (10 chars for instance). If entered String is more than 10 chars, then the system should re-prompt again and again the user to enter the valid String (a word of 10 chars) until the user enter a valid string.
I have already some piece of code for it, but its not works yet, because I've no idea how to move process up to start (to the line 1) for re-prompt the user or there is other simple way?
System.out.print("Input: ");
String inputChars = Input.readString();
while (inputChars.length() > 10){
System.out.print("Input: ");
String inputChars = Input.readString(); // here is mistake now
}
System.out.print("Output: ");
System.out.print("The enter has 10 chars");
I just want to check the entered word, if is more than 10 chars, then just skip it and prompt the user again for entering a word which is not more than 10 chars. I'm not yet good in java, so if this question is stupid just explain me how to solve it. Thanks in advance
Look at your loop:
while (inputChars.length() > 10){
System.out.print("Input: ");
String inputChars = Input.readString();
}
The second line of the loop body redeclares the inputChars variable. You can't do that, as it's already in scope. You want to just replace the previous value:
inputChars = Input.readString();
You should also consider restructuring your code to avoid the duplication though:
String inputChars;
do {
System.out.print("Input: ");
inputChars = input.readString();
} while (inputChars.length() > 10);
Note how I've also renamed the Input variable to input to follow normal Java naming conventions. I'd actually probably change both input and inputChars to be more descriptive - in particular, there's no indication of what the input data is meant to mean at the moment.
Just remove the String in beginning:
while (inputChars.length() > 10){
System.out.print("Input: ");
inputChars = Input.readString(); // here is mistake now
}
By having String in beginning, you are attempting the redefine the same name variable again.
Change to:
String inputChars = ""
do {
System.out.print("Input: ");
inputChars = Input.readString();
} while (inputChars.length() > 10)
System.out.print("Output: ");
System.out.print("The enter has 10 chars");
Before, inputChars had already been declared before the loop, so you didn't need to redeclare the variable.
A do-while loop is a better construct here because it makes your intentions more clear and makes your code more clean.

Categories

Resources