How would you validate multiple data in a while loop? - java

so I am using a while loop to check if the string entered by a user is an empty string, and if it is it results in an error, and then asks a question again and if it is valid does not repeat. I got this, but how would I also check for a string longer then 60 characers that does the same as as the empty string and also check to see if the string ends in a question mark. As in how would I implement the multiple checks within the loop
while ( x.length() == 0||x.length >100){
System.out.println("empty string not allowed .");
System.out.print( "ask another question: " );
x = scan.nextLine();
}
So I have a loop which checks multiple conditions where I have the error message for empty string and this prints out if the string entered is empty, greater than 100 characters, or doesn't end in question mark. it will continue through until a valid question is input. How would I implement the error messages for just if the empty string is entered or a string that is greater than 100 or a string that doesnt end with a question mark

you can use 'or' in the condition checking.
while ( x.length() == 0 || x.length<60 || [Any other condition comes here]){
System.out.println("empty string not allowed .");
System.out.print( "ask another question: " );
x = scan.nextLine();
Hope this answers your question.

This should solve your purpose
while( x.trim().length()==0 || x.length()>60 || !x.endsWith("?")
||(x.length().trim()==1 && x.endsWith("?")) ) {
System.out.println("empty string not allowed .");
System.out.print( "ask another question: " );
x = scan.nextLine();
}
The last condition is to check if the user just enters a "?", then loop again so as to make him ask a question with content. So in effect this loops runs if :
The user enters empty string
The user enters more than 60 characters
The user does not end the question with '?'
The user just enters '?' without any content

Related

Java, How do I validate input when using scanner?

I am currently working on Java code. Basically, the int input works. However, if I type in a character, the whole system crashes. My question is as to what needs to be changed in the below code in order for the user to receive a message stating that only an int is the valid input, and to try again if they input a character.
do {
System.out.println("How many players would like to participate in this game?\t(2-4 players)");
numberOfPlayers = in.nextInt();
} while(in.hasNextInt());
numberOfPlayers = in.nextInt();
I personally prefer to use a while loop for this sort of thing rather than the do/while. Not that there is anything wrong with the do/while, I just feel it's more readable to use the while loop.
I agree with others here, accept String digits from the User instead of Integer. In my opinion it saves you other possible problems down the road and you have no need to purposely apply a try/catch mechanism should the User supply an invalid entry. It also allows you to easily apply a mechanism to quit the application which, again IMHO, should be made available to all Console app's.
You've got your answer for carrying out the task using a do/while loop but I would like to show you another way to do this sort of thing:
Scanner in = new Scanner(System.in);
String ls = System.lineSeparator();
int numberOfPlayers = 0;
String userInput = "";
while (userInput.equals("")) {
// The Prompt to User...
System.out.print("How many players would like to participate in this game?" + ls
+ "2 to 4 players only (q to quit): --> ");
userInput = in.nextLine();
// Did the User enter: q, quit (regardless of letter case)
if (userInput.toLowerCase().charAt(0) == 'q') {
// No, the User didn't...
System.out.println(ls + "Quiting Game - Bye Bye.");
System.exit(0); // Close (exit) the application.
}
/* Did the User supply a string representation of a numerical
digit consiting of either 2, 3, or 4. */
if (!userInput.matches("[234]")) {
// No, the User didn't...
System.out.println("Invalid input! You must supply a number from 2 to 4 "
+ "(inclusive)." + ls + "Try again..." + ls);
userInput = "";
continue; // Loop again.
}
// Convert numerical string digit to an Ingeger value.
numberOfPlayers = Integer.parseInt(userInput);
}
System.out.println(ls + "The Number of players you provided is: --> "
+ numberOfPlayers);
You will notice that the Scanner#nextLine() method is used to accept User input as a String. This now means that we need to validate the fact that a string representation of a Integer numerical digit (2 to 4 inclusive) was supplied by that User. To do this you will notice that I used the String#matches() method along with a small Regular Expression (RegEx) which consists of the following string: "[234]". What this does in conjunction with the String#matches() method is it checks to see if the string value in the userInput variable contains either a single "2", a single "3", or a single "4". Anything else other than any one of those three digits will display this message:
Invalid input! You must supply a number from 2 to 4 (inclusive).
Try again...
and, force the User make yet another entry.

Method won't return an updated String

I have a method that is supposed to get the input of a String from a user and validate 4 things:
that its only 1 word, doesn't contain spaces, doesn't contain numbers, and isn't blank/had the enter key pressed.
If any of these issues occur then an error msg is printed and the method is called again to re-prompt the user for input. If the string meets the requirements than the method returns the String.
In most cases the method works as intended, however, if I enter an incorrect repsonse the first time around then even after it prompts me with the error and I enter the correct response it returns the incorrect response I entered the first time. Can someone please explain why this is happening?
public static String getName() {
//Prompt User for Name and Store it as the tmp String
System.out.print("Please enter the target string here: ");
String tmp = in.nextLine();
//Check to see if the string is blank, contains more than one word, or contains numbers. If so, give error and re-prompt
if(tmp.equals("") || tmp.contains(" ") || tmp.contains("1") || tmp.contains("2") || tmp.contains("3") || tmp.contains("4")
|| tmp.contains("5") || tmp.contains("6") || tmp.contains("7") || tmp.contains("8") || tmp.contains("9") || tmp.contains("0")) {
System.out.println("\nYou entered an invalid response, please try again\n");
getName();
}
//Return the String
return tmp;
}
You must assign the string:
tmp = getName();

Loop until valid input is reached [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed last year.
It executes correctly the first time, but:
It keeps printing "Please try again (Y/N)?" no matter what the
input is after asking to continue.
I am unsure if != is appropriate to use for String comparison. I want to say while
loopChoice "is not" Y or N, keep asking.
while(isLoop) {
// Ask for user input
System.out.print("Enter hours worked: ");
hoursWorked = scn.nextInt();
System.out.print("Enter rate per hour: ");
payRate = scn.nextInt();
scn.nextLine();
// Call functions to compute stuff
...
// Print results
...
System.out.print("\nDo you want to continue (Y/N)? ");
loopChoice = scn.nextLine().toUpperCase();
while(loopChoice != "Y" || loopChoice != "N") {
System.out.print("\nPlease try again (Y/N)? ");
loopChoice = scn.nextLine().toUpperCase();
}
switch(loopChoice) {
case "Y":
isLoop = true;
System.out.print("\n");
break;
case "N":
isLoop = false;
System.out.println("Terminating program...");
scn.close();
System.exit(0);
break;
default:
System.out.println("Your input is invalid!");
isLoop = false;
System.out.println("Terminating program...");
scn.close();
System.exit(0);
break;
}
}
You should compare with String equals
while (!loopChoice.equals("Y") && !loopChoice.equals("N"))
Also, replace the or operator with and operator
That's not how you compare strings in Java.
There is also a logical error in your code, as the string can't be both Y and N at the same time, you have to use && instead of ||. As long as the choice is neither Y or N, you want to continue the loop. If it is any of them, you want to stop. So && is the correct choice here.
To check if two strings are equal, you have to use .equals(obj)
while (!loopChoice.equals("Y") && !loopChoice.equals("N")) {
The reason for this is that == compares object references, and two Strings are most often not the same object reference. (Technically, they can be the same object reference, but that's not something you need to worry about now) To be safe, use .equals to compare Strings.
To avoid a possible NullPointerException in other situations, you can also use:
while (!"Y".equals(loopChoice) && !"N".equals(loopChoice)) {
You cannot use loopChoice != "Y", since "Y" is a String. Either use:
loopChoice != 'Y', or
"Y".equals(loopChoice)
Alternatively, use "Y".equalsIgnoreCase(loopChoice).
Case switching is also not possible for Strings if you use Java 1.6 or earlier. Be careful.
You need to know that OR Operation will return true if one of the two condition is true , so logically if you Enter Y , so you ask if the input is not equal Y so the answer is false then you will go to the next part in your condition if the input not equal N so the answer is True , so your finally result will be (True || False = True ) and then you will entered to while loop again
so the true condition is (the input not equal Y && not equal N)
You have fallen into the common early gap between checking equality of objects versus the values of objects. (You can see a quick list of string comparison information [here]
(http://docs.oracle.com/javase/tutorial/java/data/comparestrings.html)
What you wrote asks whether the object loopChoice is the same object as the string constant "Y" or the string constant "N" which will always return false. You want to ask whether the value of object loopChoice is the same as the value of string constant "Y".
You could rewrite your code as follows:
System.out.print("\nDo you want to continue (Y/N)? ");
// get value of next line, and trim whitespace in case use hit the spacebar
loopChoice = scn.nextLine().trim();
while (!("Y".equalsIgnoreCase(loopChoice) || "N".equalsIgnoreCase(loopChoice)) {
System.out.print("\nPlease try again (Y/N)? ");
loopChoice = scn.nextLine().toUpperCase();
}
Note, I like to put the constant value first for clarity. The general form for determining whether the value of two strings is the same is String1.equalsIgnoreCase(String2).

Java: do/while loop repeating even though condition has been met

I'm trying a simple do while loop that is suppose to run if the input is less than 1, and greater than 1000. It should ask for the user to input a correct number, on loop otherwise. What it seems to be doing now is repeating the loop one additional time, asking for the correct input, and then display the ending message. Unsure why it's repeating it, if the condition is met
String name = JOptionPane.showInputDialog(null,
"Please enter students lastname");
int input = Integer.parseInt(JOptionPane.showInputDialog(null,
"Please enter students ID"));
do {
JOptionPane.showMessageDialog(null,
"Please enter a student ID within the correct parameters");
input = Integer.parseInt(JOptionPane.showInputDialog(null,
"Please enter students ID"));
} while (input < 1 && input > 1000);
// Output dialog with user input
JOptionPane.showMessageDialog(null, "StudentID: " + input
+ "\nStudent Last: " + name);
You're presenting the dialog at least twice -- once before the loop, once within the loop.
The do-while does not test the condition until after the loop has executed at least once.
You could either:
Eliminate the first call to show the input dialog.
Or change your do-while loop to a while loop.
In addition, see #GrailsGuy's comments on the loop test. Your current test will always fail.
I think you while CONDITION is not correct as I read comments in print statement I believe you need
while (input > 1 && input < 1000);
Because ID must not negative number.
Remember this condition is true if ID value is between 2 to 999.
As you commented: Just to clarify, if the user inputs a number outside of the range (1-1000),i.e. 2005, I want the loop to cycle, asking the user to input a number within the range,until that condition is met
do like, read comments to understand what My code is:
input = -1;
while(input < 1 || input > 1000){
// ^ ^ OR greater then 1000
// either small then 1
}
notice: I have punted OR instead of AND because either one condition fail you loop should be continue.
I would change it with a while:
int input = Integer.parseInt(JOptionPane.showInputDialog(null,
"Please enter students ID"));
while(input < 1 || input > 1000) {
// Your stuff
}
The explanation
What I think was wrong is that, in the first place, there's no way any number can be (at the same time) less than 1 and more than 1000, so obviously, the valid input should be outside the specified range (that is, from -Infinity to 0 OR from 1001 to Infinity).
Secondly, what was mentioned in another answer: The do...while loop always runs at least once, and it repeats as long as the while condition is true. Since the input is being read before entering the loop, the 'confirmationalways takes place... What's the need to request a correction on a possibly correctinput` value?
What I think was wrong is a misunderstanding on the sense of the validation rule:
I'm trying a simple do while loop that is suppose to run if the input is less than 1, and greater than 1000
What does the and word means? I think it means that the input must be outside the given range.

How do I avoid StringIndexOutOfBoundsException when char has no value?

Sorry if the title made no sense but I did not know how to word it.
The problem:
I'm making a multiple choice quiz game that gets either a, b, c or d from the user. This is no problem if they do as they are told, however if they don't type anything and just hit enter I get a StringIndexOutOfBoundsException. I understand why this is happening, but I'm new to Java and can't think of a way to fix it.
What I have so far:
System.out.println("Enter the Answer.");
response = input.nextLine().charAt(0);
if(response == 'a')
{
System.out.println("Correct");
}
else if(response == 'b' || response == 'c' || response == 'd')
{
System.out.println("Wrong");
}
else
{
System.out.println("Invalid");
}
Of course the program will never make it past the second line of code if the user types nothing, because you can't take the charAt(0) value of an empty String. What I'm looking for is something that will check if the response is null, and if so ask go back and ask the question to the user again.
Thanks in advance for any answers.
You can use a do-while loop. Just replace
response = input.nextLine().charAt(0);
with
String line;
do {
line = input.nextLine();
} while (line.length() < 1);
response = line.charAt(0);
This will continue to call input.nextLine() as many times as the user enters a blank line, but as soon as they enter a non-blank line it will continue and set response equal to the first character of that non-blank line. If you want to re-prompt the user for the answer, then you could add the prompt to the inside of the loop. If you want to check that the user entered a letter a–d you could also add that logic to the loop condition.
Either handle the exception(StringIndexOutOfBoundsException) or break this statement
response = input.nextLine().charAt(0);
as
String line = input.nextLine();
if(line.length()>0){
response = line.charAt(0);
}
Exception Handling:
try{
response = input.nextLine().charAt(0);
}catch(StringIndexOutOfBoundsException siobe){
System.out.println("invalid input");
}
Simple:
Get the input initially as a String, and put it into a temporary String variable.
Then check the String's length.
then if > 0 extract the first char and use it.
In addition #HovercraftFullOfEels' (perfectly valid) answer, I'd like to point out that you can "catch" these exceptions. For example:
try {
response = input.nextLine().charAt(0);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("You didn't enter a valid input!");
// or do anything else to hander invalid input
}
i.e. if a StringIndexOutOfBoundsException is encountered when executing the try-block, the code in the catch-block will be executed. You can read more about catching and handling exceptions here.
StringIndexOutofBoundException will occur in the following situation also.
Searching a string which is not available
Match with the string which is not available
for ex:
List ans=new ArrayList();
temp="and";
String arr[]={"android","jellybean","kitkat","ax"};
for(int index=0;index < arr.length;index++ )
if(temp.length()<=arr[index].length())
if(temp.equlsIgnoreCase((String)arr[``index].subSequence(0,temp.length())));
ans.add(arr[index]);
the following code is required to avoid indexoutofboundexception
if(temp.length()<=arr[index].length())
because here we are cheking the length of src string is equal or greater than temp .
if the src string length is less than it will through "arrayindexoutof boundexception"

Categories