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();
Related
I'm writing a word-guessing game code. The main calls the inputTake method, which asks for input of a word consisting 5 English letters only, and returns is. Before returning the word, it calls another method, checkInput, to make sure the input is valid. If the input isn't valid, the checkInput method prints an error message and calls inputTake to let the user try again.
But when the first input is invalid, checkInput calls inputTake and then the second input is valid everything seems to work alright. The problem is that the method returns the first, invalid input, and not the valid input.
I tried initializing Scanner in the main and giving it to the method as parameter, but that doesn't help.
Below is the code I wrote, any thoughts? Any help is welcome
Main:
Board board1 = new Board();
String guess = board1.inputTake();
Board:
// take input - print a message and calls the checkInput method with the String inputed.
public String inputTake(){
Scanner scan = new Scanner(System.in);
String guess;
System.out.println("choose a word, pick carefully: ");
guess = scan.next();
// we gotta check whether the input's valid before we return it!
checkInput(guess);
return guess;
}
/* checks whether a given String is made out of 5 english language letters.
* if it is, program continues normally.
* if not, it prints error message and calls the InputTake method again.
*/
public void checkInput(String input) {
boolean isGood = true;
// check if 5 letters
if(input.length() != 5)
isGood = false;
// check if all are english
if(!input.matches("[a-zA-Z]+"))
isGood = false;
if(isGood == false) {
System.out.println("make sure your guess consists of 5 english letters, try again.");
inputTake();
}
}
As mentioned in the comments, the problem is that your inputTake() call inside checkInput() doesn't do what you want. You can try this:
// take input - print a message and calls the checkInput method with the String inputed.
public String inputTake(){
Scanner scan = new Scanner(System.in);
String guess;
System.out.println("choose a word, pick carefully: ");
guess = scan.next();
// we gotta check whether the input's valid before we return it!
if(!isGoodInput(guess)) {
System.out.println("make sure your guess consists of 5 english letters, try again.");
guess = inputTake();
}
return guess;
}
/* checks whether a given String is made out of 5 english language letters.
* if it is, program continues normally.
*/
public boolean isGoodInput(String input) {
return input.length() == 5 && input.matches("[a-zA-Z]+");
}
I'm trying to make my program validate between the use of two single characters that are input by the user, which must be A or M.
Here's my code I have thus far:
static char getCustomerType() {
System.out.println("Please enter the term for the Policy the client would like");
System.out.println("A for Annual or M for Monthly. Annual provides the user with a 10% discount");
String s = inputs.next();
while (s != 'A' && s != 'M') {
System.out.println("Incorrect, please try again");
s = inputs.next();
}
}
Netbeans however, does not like this stating the inputs.next is never used when I have set it to be used before the while statement?
It also doesn't like the while statement producing incompatible string type referencing boolean to string.
I assume this is because I have declared s as a String?
You can have single characeter input from user using below code assuming inputs is your scanner object:
char c = inputs.next(".").charAt(0);
and then you can compare it using != or .equals() or .equalsIgnoreCase()
why not write
while ( ("A".equalsIgnoreCase(s) || "M".equalsIgnoreCase(s)) == false)
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
This question already has answers here:
Loop user input until conditions met
(3 answers)
Closed 7 years ago.
I'm currently working my way through a Udemy Java course and am practicing what i have learnt thus far.
I have the following simple program which i am planning on using to get the user to input his name.
import java.util.Scanner;
public class Adventure {
public static final int menuStars = 65;
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
String firstName = "";
String lastName = "";
boolean validName = false;
while(!validName){
//Entering first name
System.out.println("Please enter your first name.");
try {
firstName = input.nextLine();
if(firstName.length() == 0){
throw new Exception("Please enter a first name of at least 1 character.");
}else{
//Entering last name
System.out.println("Please enter your last name.");
lastName = input.nextLine();
if(lastName.length() == 0){
throw new Exception("Please enter a last name of at least 1 character");
}else{
System.out.println("You have entered " + firstName +" " + lastName);
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
continue;
}
//Used to terminate loop when both first & last names are valid
validName = true;
}
}
}
I want to make the program repeat the error message when the user inputs a blank name instead of restarting the entire program from the beginning.
E.g When the user enters a blank first name, i want the program to keep repeating "Please enter a first name of at least 1 character" and when the user enters a blank last name, for it to keep repeating "Please enter a last name of at least 1 character" until the user enters a valid name.
However, currently when the user enters a blank first name or last name, my program will repeat itself from the very beginning instead of repeating just the error message.
How would i go about making the program repeat just the error message?
Use a boolean variable that stores true when "Please enter your first name." is printed. Check before printing this string each time if this variable is false or not. Also, initialize it to false before the loop. Same idea goes for last name.
if(!printed)
{
System.out.println("Please enter your first name.");
printed=true;
}
havent tested that but i am guessing it can be like that, with out try/catch though, it just makes no sense to me using it in the way you have it on your code
String firstName = "";
String lastName = "";
System.out.println("Please enter your first name.");
firstName = input.nextLine();
while(firstName.length<1){
System.out.println("Please enter a first name of at least 1 character.");
firstName = input.nextLine();
}
lastName=input.nextLine();
while(firstName.length<1){
System.out.println("Please enter a last name of at least 1 character.");
lastName = input.nextLine();
}
System.out.println("You have entered " + firstName +" " + lastName);
Edit, some basic info about exceptions
try catch is used when something unexpected happens and you try to find a way round it. for example if an array of 10 positions is expected at some point and a smaller array (lets say 4 positions) is being used. Then this would cause an exception causing the program to terminate with no further information.
With try catch you can check what the problem is, and try to either inform the user to do something(if they can) or close the program in a better way, using System.exit() for example and saving all the work that was done till that point
An other example is that if you ask for 2 numbers to do an addition. if the user enters letters instead of number the int sum=numbA+numbB; would throw and exception. This of course could be handled using an if. but even better would be something like this
A whitespace is actually considered a character, so the check of (length == 0) doesn't work for your purposes.
Although the following code below is incomplete (ex: handles the potentially undesirable case of firstname=" foo", (see function .contains()), it does what the original post asks - when the user enters a blank first/last name, it keeps repeating "Please enter a first/last name of at least 1 character" until the user enters a valid first/last name.
import java.util.Scanner;
public class Adventure {
public static final int menuStars = 65;
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
String firstName = "";
String lastName = "";
boolean firstNameLegal = false;
boolean lastNameLegal = false;
// Entering first name
while (!firstNameLegal) {
System.out.println("Please enter your first name.");
firstName = input.nextLine();
if (!firstName.equals(" "))
firstNameLegal = true;
else
System.out.println("Please enter a first name of at least 1 character.");
}
// Entering last name
while(!lastNameLegal){
System.out.println("Please enter your last name.");
lastName = input.nextLine();
if(!lastName.equals(" "))
lastNameLegal = true;
else
System.out.println("Please enter a last name of at least 1 character.");
}
System.out.println("You have entered " + firstName +" " + lastName);
}
}
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"