Hello fellow StackOverflowers, I hope all of your days are going well.
I'm relatively new to Java programming and have found myself in a bit of pickle.
What I'm attempting to do is;
Input Validation in Java - I want to make sure that the JOptionPane.showInput pane continues to re-appear (using a while loop) until the user has entered a value which is captured in the "this.accountName" String and;
From there once the user has entered something in the JOptionPane.showInput pane I want to exit the loop and proceed to the other methods I have inside my OO program.
Unfortunately my while loop below exits after the first instance and doesn't continue in my code example below;
public String getAccountName() {
this.accountName = JOptionPane.showInputDialog(null, "Please enter a nick name for your new account (e.g. Savings Account)");
if (this.accountName!= null) {
while (this.accountName != null) {
this.accountName = JOptionPane.showInputDialog(null, "Error! Please enter a valid name for your new account");
if (this.accountName.contains("")){return this.accountName;
}
}
}
return this.accountName;
}
What would be the best way to go about fixing this?
I appreciate your help in advance!
Use StringUtils.isBlank method (https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html) to check accountName value:
this.accountName = JOptionPane.showInputDialog(null, "Please enter a nick name for your new account (e.g. Savings Account)");
while (StringUtils.isBlank(this.accountName)) {
this.accountName = JOptionPane.showInputDialog(null, "Error! Please enter a valid name for your new account");
}
return this.accountName;
Related
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'm working on my final project for my java class and I'm having a slight issue with the opening. I need to make an authorization screen with username & password, and each user has a specific screen that is accessed with their combinations.
I've been focusing on the first user name/password since I know getting that one right will make the rest easier. However, while the username is read corrected when I put in the correct password it brings up the "incorrect login" loop, which then goes into an infinite loop even after imputing the correct password.
I've included the code below. I have the import java.util.Scanner already set up.
Scanner scnr = new Scanner (System.in);
String userName = "";
String userPassword = "";
System.out.println("Enter username: ");
userName = scnr.next();
while (userName.equals("griffin.keyes")) { //multiple users names
System.out.println("Enter password: "); //easier method?
userPassword = scnr.next(); //to be looked into
if (userPassword.equals("alphabet soup")){
System.out.println("Hello, Zookeeper!"); //broken up to increase readability
System.out.print("As zookeeper, you have access to all");
System.out.print(" of the animals' information and their");
System.out.print("daily monitoring logs. This allows you to");
System.out.print(" track their feeding habits, habitat");
System.out.println(" conditions, and general welfare.");
}
else {
System.out.println("Login failed"); //needs to be fixed
System.out.println("Enter password: "); //needs to repeat three times
userPassword = scnr.next(); //issue with while statement?
}
}
}
Your username will never change so the while (userName.equals("griffin.keyes")) is the same as while (true)). There are a few workarounds this, here's one:
int reties=3;
while (userName.equals("griffin.keyes")&&retires!=0) { //multiple users names (keep condition like this)
System.out.println("Enter password: "); //easier method?--Not sure what that means
userPassword = scnr.next(); //to be looked into
if (userPassword.equals("alphabet soup")){
System.out.println("Hello, Zookeeper!"); //broken up to increase readability
System.out.print("As zookeeper, you have access to all");
System.out.print(" of the animals' information and their");
System.out.print("daily monitoring logs. This allows you to");
System.out.print(" track their feeding habits, habitat");
System.out.println(" conditions, and general welfare.");
break;
}
else {
System.out.println("Login failed"); //Fixed
System.out.println("Enter password: "); //3x Done
userPassword = scnr.next();
retries--;
}
}
or you could modify your while's condition so suit it better and have the zookeeper's job details outside the while loop (it depends on how you want to approach it).
The problem is your while condition is always true. The user name never changes so it keeps going through the loop. Also use scnr.nextLine() if you are trying to read a line with spaces in it, as next() only reads in one token at a time rather than the whole line you want for your multi-word passwords.
In your while condition, userName.equals("griffin.keyes") will always be true, as the variable userName is not modified.
You probably need to change your while condition to something like
while (numOfRetries <= MAX_ALLOWED) {
... do the logic
numOfRetries++; // when password fails
}
This question already has answers here:
What is the "continue" keyword and how does it work in Java?
(12 answers)
Closed 6 years ago.
I am programming a simulated online banking client in java. I need the ability (or an alternative) to be able to continue from a label. This is a snippet from my code so far.
Main:
{
for ( ; ;) {
System.out.println("Welcome to TamarinĀ© online banking!");
System.out.println("Select register or login:");
choice = scan.nextLine();
if (choice.equalsIgnoreCase("register")) {
register:
{
System.out.println("Welcome to register! Please type your username:");
userreg = scan.nextLine();
if (accounts.contains(userreg)) {
System.out.println("Username taken! Try again.");
continue register;
Java is giving me a "continue cannot be used outside of loop" error. Any ideas as to (if the registration fails) I could bring the user back to the last step ('registration' label)? And if not, how could I get this code to work?
(I obviously have closing braces down at the end).
Well you shouldn't be using a goto in the first place (which currently doesn't exist in Java), the reason for this being that using labels promotes badly structured and difficult to maintain code (also called spaghetti code).
Instead you should add a nameTaken boolean and loop while it is true.
while(nameTaken) {
System.out.println("Welcome to register! Please type your username:");
userreg = scan.nextLine();
if (accounts.contains(userreg))
System.out.println("Username taken! Try again.");
else {
// do stuff
nameTaken = false;
}
}
First of all, thanks for using labels and taking us all back to C programming from so long ago. Second, you can easily simulate the behavior you currently have with labels by using appropriately constructed loops, e.g.
do {
System.out.println("Welcome to TamarinĀ© online banking!");
System.out.println("Select register or login:");
choice = scan.nextLine();
if (choice.equalsIgnoreCase("register")) {
do {
System.out.println("Welcome to register! Please type your username:");
userreg = scan.nextLine();
if (!accounts.contains(userreg)) {
System.out.println("Creating username " + userreg + " ...");
break;
}
else {
System.out.println("Username taken! Try again.");
}
} while (true);
}
// the rest of your logic goes here
} while (true);
I am trying to use the while loop for re-running parts of code in my simple program. In this program, the user makes a simple account, types in a verification number, then signs in. Once signed in, I wish to allow the user to sign out, edit his profile settings and more. However I have a small problem.
Say the user has just edited their account settings. Instead of the program terminating, I want them to be able to return to the "menu".
The problem lies with how to do that. As there is no goto statement in java, from what I have read, I must use the while loop. I have no idea of how to go about that. I just can't wrap my head around it. Loops have always confused me. Also, should I even use the while loop? Would it be better to use the for or do-while loops? And what expression should I use? Will I need the break statement?
I know it isn't a concrete question, but any help that puts me on the right path is well appreciated.
Below is the full code for reference.
public static void main(String[] args) {
System.out.println("Hi! To begin please choose your username.");
System.out.println("To do this, please enter your username below. ");
System.out.println("This name must be at least three characters.");
Scanner userInput = new Scanner(System.in);
String userName = userInput.next();
int nameLength = userName.length();
if (nameLength > 2) {
System.out.println("Now please enter your password.");
System.out.println("This password must be at lease five characters");
String passWord = userInput.next();
int passLength = passWord.length();
if (passLength > 4) {
System.out.println("Signup alost complete.");
Random rand = new Random();
int randm = rand.nextInt(100000) + 1;
System.out.println("To confirm you are not a robot, please enter this code: " + randm);
int code = userInput.nextInt();
if (code == randm) {
System.out.println("Thank you, " + userName);
System.out.println("You may now login. Begin by entering your username");
//Where I would go if the user signed out
String name = userInput.next();
if (name.equals(userName)) {
System.out.println("Now please enter you password");
String pass = userInput.next();
if (pass.equals(passWord)) {
System.out.println("Thank you. You have now successfully logged in");
//Where the "main menu" will be
//Rest of code will also go here
}
else {
System.out.println("Password is incorrect");
}
}
else {
System.out.println("Username is incorrect");
}
}
else {
System.out.println("The code entered is incorrect.");
}
}
else {
System.out.println("Invalid Password");
}
}
else {
System.out.println("Invalid Username");
}
}
You have placed a comment //where would I go if the user signed out?
The answer is, You will show the message to sign in when he is signed out, so that he can sign in again. You can do this by using for loop or loop or whatever loop you want. That means the part of user login will be in a loop, if the user logged in then the menu will be shown up. If the user sign out, the sign in form will be shown up infinitely.
You can put your code inside do. It will not break and will keep looping.
do{
}
while(true);
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);
}
}