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);
}
}
Related
This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 3 years ago.
I have to make a store that has items for purchase. After choosing an item, I prompt the user to enter the quantity of the item they would like to buy.
// 'input' is my Scanner object
int quantity;
quantity = input.nextInt();
If the user enters a non-integer (i.e. decimal, char...), it breaks the program.
Is there a way I can validate for this non-integer input?
Thank you
Sure, accept a String value instead of an int, check to see if you can parse that String value to an int, if you can, then do so. If not, sent a message stating that then entered value must be an number.
This could be done in a while loop.
import java.util.Scanner;
public class ScannerInputInt {
public static void main(String... args) {
Scanner in = new Scanner(System.in);
Integer input = null;
do {
System.out.println("Please enter number: ");
String s = in.nextLine();
try {
input = Integer.parseInt(s);
} catch (NumberFormatException e) {
System.out.println("ERROR: " + s + " is not a number.");
}
} while (input == null);
}
}
If you don't wanna use Exceptions method. You can try this.
This piece of code will continue to ask user input until user has entered correct input.
System.out.print("Enter quantity: ");
Scanner input = new Scanner(System.in);
boolean isInt = input.hasNextInt(); // Check if input is int
while (isInt == false) { // If it is not int
input.nextLine(); // Discarding the line with wrong input
System.out.print("Please Enter correct input: "); // Asking user again
isInt = input.hasNextInt(); // If this is true it exits the loop otherwise it loops again
}
int quantity = input.nextInt(); // If it is int. It reads the input
System.out.println("Quantity: " + quantity);
input.close();
Output:
Enter quantity: 12.2
Please Enter correct input: 12.6
Please Enter correct input: s
Please Enter correct input: s6
Please Enter correct input: as
Please Enter correct input: 2
Quantity: 2
I think it is slightly better approach because I think controlling flow of your program with Exceptions is bad practice and should be avoiding when there are other things that you can use.
I'm not the best programmer and am quite new to it. I've been trying for hours to get this program correct but I can't seem to come up with a way to make it work out the way I'd like to. Here's what I want to do:
Write a program that prompts a user for their name and then displays "Hello, [Name Here]!"
If the user does not enter anything but pressed Enter anyways, you should re-prompt for the user's name. This flow should look like the following:
Whats is your name?
Please Enter your name:
Please Enter your name: Programming Practice
Hello, Programming Practice!
Here's how I'm thinking of the program before I start writing anything in my IDE:
Ask the user for their name
Give them a chance to enter their name
If their entry is not in name format, give them output saying incorrect format
Give them a chance to enter in proper format
Repeat steps 4 and 5 as many times as it takes for them to enter proper format
Print "Hello, [Name Here]!"
END
Here's what I've got so far:
package lol;
import java.util.Scanner;
public class Whatever {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.printf("What is your name?\n");
String name = sc.nextLine();
if (name != "Programming Practice")
{
System.out.println("Please enter a valid name");
String name2 = sc.nextLine();
System.out.println("Hello, " + name2 );
}
else
{
System.out.println("Hello, " + name );
}
}
}
Right now the output I'm getting regardless of my entries are:
What is your name?
Please enter a valid name
Hello,
You can throw the sc.nextLine() into a while(true) loop and break out when you get a result you deem valid.
String name = "";
while(true) {
name = sc.nextLine();
if (name.equals("Programming Practice")) {
System.out.println("Hello, " + name);
break;
} else {
System.out.println("Please enter in the correct format");
continue;
}
}
A better way of approaching this problem would be by using do-while loop.
do {
// Your processing
} while (checkCondition());
The logic is based on the idea that the user will be prompted to enter details at least once.
I wrote a name checker that uses a for loop to check if each individual character in the string is a letter, and I wrote an if statement within the for loop stating that if the if statement conditions are met, print "Your name is valid!" and break. But if the conditions are not met, rerun the loop.
public static void nameValid() {
Scanner in = new Scanner(System.in);
System.out.println("Enter your name");
String name = in.nextLine();
int q = name.length();
for (int i = 0; i < name.length(); i++) {
if (Character.isLetter(name.charAt(i)) && q >= 2) {
System.out.println("Your name is valid!");
break;
} else {
System.out.println("Your name is invalid! Please enter a valid name!");
nameValid();
}
}
}
If I enter a valid string the first time around, everything is fine, and it moves on to the second method. If I enter an invalid String, it gives me the expected error message and reruns the loop. But then when I enter a valid string after that, it continuously runs the loop. The output I get is this:
Enter your name
123
Your name is invalid! Please enter a valid name!
Enter your name
fred
Your name is valid!
Your name is invalid! Please enter a valid name!
Enter your name
It's not re-running the loop... it's entering a recursive function call.
(Use a debugger next time please.)
In your else block, you're calling the nameValid function recursively within a loop. Thus, when you finally do enter a valid name and hit the break line, the loop that originally called the function continues.
Essentially the idea of this program is to test user input and throw exceptions that I've created when invalid data is entered. For example: name cannot be empty and must be all alpha characters (no special or numeric). I have embedded this in a do-while loop that will continue so long as q is not entered to quit. I'm reading in the user input via scanner line and then sending the string inputted to a function that validates whether it meets the criteria. If it does not, then the function throws my custom exceptions. It all works fine EXCEPT when the exception is thrown it still takes that string and puts it in the new Person object.
How do I throw the exception to the user but THEN require them to re-enter the name or age until it's entered correctly?
do{
Scanner input = new Scanner(System.in);
System.out.println("Enter person info or q to quit.");
System.out.print("Please enter the name of this person:");
String name = input.nextLine();
if(name.equalsIgnoreCase("q"))
{
break;
}
try{
isName(name);
}catch (InvalidNameException n){
System.out.println(n);
}
System.out.print("Please enter an age for this person:");
String age = input.nextLine();
try{
isValidAge(age);
}catch(InvalidAgeException a){
System.out.println(a);
}
public static void isName(String name) throws InvalidNameException
{
if(name.isEmpty())
{
throw new InvalidNameException("You did not enter a name.");
}
String[] namez = name.split(" ");
for(int i=0;i<namez.length;i++)
{
char[] charz = namez[i].toCharArray();
for (char n : charz)
{
if(!Character.isLetter(n))
{
throw new InvalidNameException("You have entered an invalid name.");
}
}
}
}
Put a continue; in your exception handling. It will break the loop an reenters it.
I would assume that the error lies within the compatibility of your isName() method and the method loop shown. It probably happens after it sets the name to a variable too. I cant tell you anything really specific because I cant see the isName method though.
The easiest way I know of doing this is to validate the obtained String using a regular expression. You can do something like this:
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = input.nextLine();
String regex = "[A-Z a-z]+(\\s)[A-Z a-z]+";
System.out.println(name.matches(regex)? "matches": "does not match");
The expression regex is used to evaluate a sequence of alpha characters (no numbers or special characters) separated by a space. So, something like: "Joe Smith" will pass validation, but something like "Joe 123Klkjsd" will not.
You can take this code and test the input String in a while() loop:
while(!name.matches(regex))
{
// Prompt the user to re-enter a valid name and assign to name variable
}
Something like that should work.
It would be better to evaluate each variable within a do-while loop. Thus if there is an error in the variable age would not necessarily re-enter the name.
Scanner input = new Scanner(System.in);
String name;
String age;
System.out.println("Enter person info or q to quit.");
do{
System.out.print("Please enter the name of this person: ");
name = input.nextLine();
if(name.equalsIgnoreCase("q")) break;
try{
isName(name);
break;
}catch (InvalidNameException n){
System.out.println(n);
continue;
}
} while (true);
if(!name.equalsIgnoreCase("q"))
do{
System.out.print("Please enter an age for this person: ");
age = input.nextLine();
if(age.equalsIgnoreCase("q")) break;
try{
isValidAge(age);
System.out.printf("Nombre; %s\nEdad: %s",name,age);
break;
}catch (InvalidAgeException a){
System.out.println(a);
continue;
}
} while (true);
For my project I need to input a first and last name with no numbers but I simply can't find anything online. If you could help, that would be terrific.
Also if you have the time, I need to flip the first and last name with a comma when the user inputs them.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class PhoneListr {
public static void main (String[] args) throws IOException {
String firstName;
String lastName;
System.out.println ("Please enter your first name:");
firstName = PhoneList ("");
System.out.println ("Please enter your last name:");
lastName = PhoneList ("");
System.out.println ("Your full name is: " + lastName + "," + firstName);
}
public static String PhoneList (String input) throws IOException {
boolean continueInput = false;
while (continueInput == false) {
BufferedReader bufferedReader = new BufferedReader (new InputStreamReader (System.in));
input = bufferedReader.readLine();
continueInput = true;
if(input.matches("[a-zA-Z]+")) {
continueInput = true;
}
else {
System.out.println ("Error, you may only use the alphabet");
continueInput = false;
}
}
return input;
}
}
use String.matches(regex):
if(input.matches("[a-zA-Z]+")) {
System.out.println("your input contains no numerics");
}
else {
System.out.println("only alphabets allowed");
}
the above regex checks a through z, or A through Z, inclusive (range).
For this type of string matching you need to use Regular Expressions, or "RegEx"es. It is a very big topic to cover but here's an introduction. RegExes are tools used to test whether strings match certain criteria, and/or to pull certain patterns out of that string or replace certain parts that match those patterns with something else.
Here is an example using a RegEx to test whether your input contains a digit:
if(input.matches("\\d")) {
// matched a digit, do something
}
Based on OP problem and clarification here are few suggestions.
Chaitanya solution handles the check for only alphabets perfectly.
About the neglected areas of problem :
i would advice you to make two variable firstName and lastName inside the main()
String firstName;
String lastName;
Change retun type of method phoneList() to String
return the entered name input insted of number inside the method phoneList ( dont actually see why you are returning number) and store it inside the firstName and lastName
System.out.println ("Please enter your first name:");
firstName = PhoneList (0);
System.out.println ("Please input your last name:");
lastNamr =PhoneList (0);
now to print it in the "comma format" use
System.out.println("full name is: " +lastName+ "," +firstName);
As i read your program again , its a mess!!
About the method phoneList()
Use regex condition to set continueInput to true/flase and not exploit execptions.
P.s. I would appreciate "editing" to post , if any fellow member find any mistakes above, using a mobile, not sure about formatting etc. Thanks. :-) (y)
You can also use
if(input.matches("[^0-9]"))
{
System.out.println("Don't input numbers!");
continueInput = false;}
Can't understand what 2nd question asks. For answer what I get from your 2nd question is like this.
In main function change the code like this
String first_name = null;
String last_name = null;
System.out.println ("Please enter your first name:");
first_name = PhoneList();
System.out.println ("Please input your last name:");
second_name = PhoneList();
System.out.println (second_name+","+first_name);
then in PhoneList function last line should be changed to
return input;
Please check for a link! for more info
You can add a check by passing the argument to method StringUtils.isNumeric
This returns true if the String entered is numeric