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.
Related
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.
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
I have found a way to make my program recognize if something is a palindrome or not, but when it is not, the program will not repeat.
I already have the boolean section of this implemented before my provided code.
Originally was set with if statements, wanted to replace with while but something like while (!yespalin(potentialp)) doesn't work either
Scanner scan = new Scanner(System.in);
String potentialp;
System.out.println("Please enter a potential palindrome: ");
potentialp = scan.nextLine();
while (yespalin(potentialp))
{
System.out.println("That string is a palindrome");
}
while (!yespalin(potentialp))
System.out.println("That string is not a palindrome, please enter another: ");
potentialp = scan.nextLine();
}
I want the program to repeat if not a palindrome
For starters I see you are missing "{" on your second while.
However I do not undetstand exactly why do you need 2 while loops.
If you would read your code line by line, you can understand why that the first loop is the only one who prints the "correct" line.
However if you enter a bad palindrome, it will never enter the first loop, therefore won't print the desired sentence.
You want 1 loop which will end if you put the correct value if im not mistaken
Which would look something like this:
Scanner scan = new Scanner(System.in);
String potentialp;
System.out.println("Please enter a potential palindrome: ");
potentialp = scan.nextLine();
while (!yespalin(potentialp)){
System.out.println("That string is not a palindrome, please enter another: ");
potentialp = scan.nextLine();
}
System.out.println("That string is a palindrome");
Hope it was helpful.
Can someone please advise why the inner loop of the code below will not exit?
I've added an inner loop to check if input from the user of of a particular value and if not prompts for the correct input. When debugging the code and passing in a value which should force the loop to end it doesn't although I can see the correct value in the variable:
while (finished.equalsIgnoreCase("n")) {
System.out.println("Enter a persons name");
names = in.nextLine();
writer.println(names);
System.out.println("Finished? (Y/N)");
finished = in.nextLine();
while( !finished.equalsIgnoreCase("y") || !finished.equalsIgnoreCase("n")) {
System.out.println("Invalid choice; (Y/N)");
finished = in.nextLine();
}
}
Every string is either not not equal to y or not equal to n. You probably meant to use the && operator:
while(!finished.equalsIgnoreCase("y") &&
!finished.equalsIgnoreCase("n")) {
// Code...
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.