Need help utilising the while loop for repeating parts of code - java

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);

Related

Exiting While Loop After User Enters Value in String (Java)

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;

While/if statement causing infinite loop, correct input reads wrong

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
}

ATM pin verification in java

I am very new to programming and need some help. I need to write a simple program that verifies an ATM users pin number. The program will either, accept the pin and exit, tell the user it was an incorrect pin and have them try again up to three times, or tell the user their card is locked because they were wrong three times. I have searched for over an hour now and cannot find an example of this. I know i will need to use a scanner and a loop to accomplish this but not much else. Any help is appreciated as it is due by midnight......
for i = 1..3
prompt user for pin
read pin
check pin
if pin is correct, exit
tell user they were wrong and try again
tell user they got it incorrect three times and their card is locked.
I will give one hint which can trip some newbies up. The pin is an integer, right? So you might be tempted to use Scanner.nextInt() to get the input--do not do that! Just get the next line and compare Strings (you may have to use String.trim() to get rid of whitespace). It's more complicated if you try to use Scanner.nextInt() (what if the user enters something that cannot be parsed as an integer).
import java.util.Arrays;
import java.io.Console;
public class atm {
public static void main(String[] args) {
int counter = 3;
int attempt = 3;
char[] ch = null;
Console c=System.console();
System.out.println("Enter PIN: ");
ch=c.readPassword();
String pass=String.valueOf(ch);
if(pass.equals("enigma")){
System.out.println("Correct PIN entered!");
}
while(!pass.equals("enigma") && attempt != 0){
System.out.println("Invalid PIN entered!. " + --attempt + " attempts remaining.");
counter--;
if(attempt != 0){
c=System.console();
System.out.println("Enter PIN: ");
ch=c.readPassword();
pass=String.valueOf(ch);
if(pass.equals("enigma")){
System.out.println("Correct PIN entered!");
}
}
else{
System.out.println("your card has locked!");
break;
}
}
}
}
Note that you can put your PIN code instead of "enigma" string, I hope that will help.
here is the implementation of pseudo code answered by #Jared above
boolean cardLockFlag = false ;
String password;
Scanner scan = new Scanner (System.in);
password = "password" ;
if(!cardLockFlag){
for(int i = 0 ; i < 3 ; i++){
if(password.equals(scan.next().trim())){
System.out.println("Success :) ");
break ;
}else{
if(i==2){
cardLockFlag = true ;
}else{
System.out.println("Wrong Password");
}
}
}
}else{
System.out.println("Card is Locked");
}

Password prompt and calling a method from an if statement

this i my first attempt at asking a question so hopefully it shows correctly. Basically what I need the program to do is to ask the user for a preset account number and password and only allow them 3 attempts. I then want to call up another method when both requirements are met so i can continue with the program. The first problem i have is that when i enter the correct password its is still showing as incorrect and i don't know why, then i would like to know if i have call the method within the if statement correctly. Thanks.
import java.util.Scanner;
public class Part4 {
public static void main(String[] args)
{
String password = "password", passwordattempt = null;
int accnum = 123456789, acctry = 0, tries = 0;
Scanner input = new Scanner (System.in);
while (acctry != accnum){
System.out.println("\nPlease enter your account number");
acctry = input.nextInt();
if (acctry != accnum)
System.out.print("That number is incorrect. Please try again.");
else
if (acctry == accnum)
{
while (tries < 3)
{
System.out.println("\nPlease enter password");
passwordattempt = input.next();
if (passwordattempt != password){
System.out.print("That password is incorrect");
tries++;
}
else
if (passwordattempt == password){
System.out.print("That is correct");
AccountDetails.Details(args);
}
}
System.out.print("\nYou have exceeded the ammount of tries");
}
}
}
public static class AccountDetails {
private static void Details(String[] args){
System.out.print("it works");
}
}
}
two problems.
1: You're executing your while loop regardless of if it is successful or not.
.
while(tries < 3)
should be
while(tries < 3 && !successfulPassword)
You'll need to add the successfulPassword variable, so that you don't get it right the first time and yet continue to have to enter passwords.
2: Your comparison of strings is grossly, umm, well, wrong. There's two things that catch my eye. The first is you can't use == and != and get the results you expect. You must use .equals(). Secondly, you don't need to repeat the opposite clause like you do with a human. For example, I tell my daughter "If you eat your supper, then you may have cookies. Else, if you do not eat your supper, then you may not have cookies." To a computer, you don't need that last "if you do not eat your supper". It's guaranteed to be true (since you're in the else block anyway) and it just clutters it up. So that just becomes
.
if(passwordAttempt.equals(password) {
successfulPassword = true;
} else {
tries++;
}
In the Java language, Strings are objects, and thus comparing them using '==' is testing by reference, and not by equality.
I believe what you are looking for is
if (passwordattempt.equals(password)) {
Check here for more information:
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#equals(java.lang.Object)

infinite for loop...?

I've built this program to read a user name from a file. It checks to see if the user name that the user entered is on the profile file. Now, if it isn't on the file, it asks would you like to create a new user? What I'm trying to do is some input validation from the user - meaning, I want him to be able to answer with only a Y for yes and N for no, and for only 5 attempts.
My problem is that something is not working correctly in my "labeled for" loop. It's suppose to ask the user for his user name only 5 times, but it asks forever, like an infinite loop. Also, I want it to write to the user only once that I couldn't find his profile, so I've put it outside the for loop, but it shows up in every iteration.
any help will be appericiated.
else {
System.out.println("Sorry couldn't find your user profile " + userName + ".");
// If profile wasn't found, ask to create a new one.
search:
for(int i=0; i<5; i++) {
System.out.println("Would you like to create a new user profile now? (Enter Y for yes), (Enter N for no and exit).");
try{
BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
// If user pressed Y than write the new user name to myFile.txt
if (addNewUser.toLowerCase().startsWith("y")) {
if(addNewUser.length() == 1){
System.out.println("Please enter a new user name:");
BufferedReader readNewUser = new BufferedReader(new InputStreamReader(System.in));
String newUserName = readNewUser.readLine();
PrintWriter write = new PrintWriter("d:\\profile.txt");
write.print(newUserName);
write.close();
break search;
} else {
System.out.println("You've mistyped, please enter only one char:");
break;
}
} else {
System.out.println("You've mistyped, the answer can only be Y or N. Try again:");
}
I think that you misunderstand what break does. Break will exit the loop and move on with your code. Breaking to a label allows you to break out of a specific loop, however you only have 1 loop, so that code is just redundant.
The command you're looking for is continue, which will skip to the next iteration of the loop.
I'd suggest reading this Oracle article about break and continue.
First: you have to replace the second break with continue.
Second: correct the end of the method. You have to check if the user has inserted a "n":
if (addNewUser.toLowerCase().startsWith("n")) {
// do something...
}else {
System.out.println("You've mistyped, the answer can only be Y or N. Try again:");
}

Categories