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:");
}
Related
I want to user to enter menu ID
do {
id = "";
System.out.print("Enter Menu ID : ");
id = sc.nextLine();
correctInput = false;
for (int i = 0; i < menu.length; i++){
if ((id.toUpperCase()).equals(menu[i].getMenuID()) {
correctInput = true;
//codes that comparing the user entered **ID** with **ID** in the array
//and get the quantity that user entered and calculate the total price
}
if (correctInput == false)
System.out.println("\nInvalid ID, please enter again!\n");
} while (correctInput == false);
//codes that ask user whether to add-on
When user wants to repeat to make order, it will always show the error message before user enters anything
Add-on? (Y/N) : y
Enter Menu ID :
Invalid ID, please enter again!
Enter Menu ID :
Can I know what is wrong with my code?
From the input/output snippet you shared, it seems that id = sc.nextLine() isn't waiting for user input. This could happen if you still have input queued - e.g., you read the "Y" for "Add-on? (Y/N)" with next() but didn't handle the newline following the "Y". You could handle it by having another nextLine() before the while loop, and just ignore the result:
// Get rid of the queued newline character - return value can be ignored
sc.nextLine();
// Start the loop for reading the id:
do {
// code...
What I would do is compare the string values without worrying about case sensitivity.
if (id.equalsIgnoreCase(menu[i].getMenuID())){
correctInput = true;
// your code
}
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
}
I'm doing the Java Associate level certification and while we are expressly told we won't be tested on labels, we have been shown them. Looking on here though the advice seems to be never use labels?
I'd like to use them in a catch block/user input console as a means of validating input.
do {//Keep calculator going as long as user wants
numInputCheck:
do {
try {//Force user to input a whole number
System.out.print("\nPlease enter the Mark you want to Calculate\n(Enter marks between " + GradeCalculator.getMIN_MARK() + " and " + GradeCalculator.getMAX_MARK() + " only): ");
mark = Integer.parseInt(scn.nextLine());
}catch(NumberFormatException nfe) {
System.out.println("\nInvalid entry - Please ensure entry is a number only.");
continue numInputCheck;
}
gradeCalc.isValidMark(mark);//Ensure input is within valid range
}while(!gradeCalc.getIsValidMark());
*etc*......
Is this bad coding?
EDIT: The code above wasn't doing what I thought it was/wanted it to do - it wasn't actually jumping back to the label at all.
I ended up changing the code to
do {//Keep calculator going as long as user wants
do {//Force user to enter number within valid range
do {//Force user to enter a whole number
try {
System.out.print("\nPlease enter the Mark you want to Calculate\n(Enter marks between " + GradeCalculator.getMIN_MARK() + " and " + GradeCalculator.getMAX_MARK() + " only): ");
mark = Integer.parseInt(scn.nextLine());
isValidInput = true;
}catch(NumberFormatException nfe) {
System.out.println("\nInvalid entry - Please ensure entry is a number only.");
isValidInput = false;
}
}while(!isValidInput);
}while(!gradeCalc.isValidMark(mark));
which I'm fairly sure is working correctly.
Anyway, I think I answered my own question - labels are discouraged because people like me try to use them.
No this is not actual example because continue can do all the job by itself without the help of the label .
A good example is when you have 2 nested loops and you want to break the outer loop from a condition in the inner loop
outerloop:while(condition1) {
while(condition2) {
if(condition3)
break outerloop;
}
{
Continue statement skips all sentences above, you have to use break sentence for stopping the loop. Labels are useful for more than one loop, for example:
label1:
for (int i = 0 ; i<10; i++){
for (int j = 0 ; j<10; j++){
if (i+j = 3)
break label1;
}
}
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 is my first time on this site. I am taking a course in Java right now and I am having some trouble with this code/program that I am supposed to make that allows the user to select whether they want to see "good monkeys", "bad monkeys" or "show monkeys". It is nowhere near done but I am having trouble returning to the command screen/area after a command is completed. I would like the commands to be used as many times as possible. Secondly, my program treats every input if someone put in "Good Monkey". So if you put in a word like "pineapple", it will still greet you with the output designated for the "Good Monkeys" input.
I've looked online and seen that maybe I should use a "do-while" loop and use "switch". Any input/ help would be greatly appreciated. Thank you so much!
Here is my code: public class and public static and Scanner import are in this code, but for some reason I cannot add them into this post without messing up the formatting of the code.
Scanner jScanner = new Scanner(System.in);
System.out.println("please enter Good Monkeys, Bad Monkeys or Show Monkeys");
String userChoice = jScanner.nextLine();
for (int b= 1; b < 11000; b++)
{
if (userChoice.equalsIgnoreCase("Good Monkeys"));
{
System.out.println("You have selected Good Monkeys");
System.out.println("How many monkeys do you want? Put in a integer between 3 and 20");
Scanner goodMonkeyScanner = new Scanner (System.in);
int userChoiceGood = goodMonkeyScanner.nextInt();
if (userChoiceGood >= 3 && userChoiceGood <= 20)
{
System.out.println("Here you go");
System.out.println("Monkeys (metapohorical)");
break;
}
else if (userChoice.equalsIgnoreCase("Bad Monkeys"))
{
System.out.println("You have selected Bad Monkeys");
System.out.println("How many monkeys do you want? Put in a integer between 3 and 20");
Scanner badMonkeyScanner = new Scanner (System.in);
int userChoiceBad = badMonkeyScanner.nextInt();
if (userChoiceBad >= 3 && userChoiceBad <= 20)
{
System.out.println("Here you go");
System.out.println("Monkeys (metapohorical)");
break;
}
else
System.out.println("Sorry this doesn't work");
}
else if ((userChoice.equalsIgnoreCase("Show Monkeys")))
{
System.out.println("Monkeys");
System.out.println("0");
System.out.println("\\/");
System.out.println(" |");
System.out.println("/\\");
break;
}
else
{
System.out.println(" Wrong Answer. Try again");
}
break;
}
}
}
}
First, you need to define the loop. Second, you need to put the input instruction inside the loop.
I'll include a done variable to detect when the user wants to escape
So, let's code:
Scanner jScanner = new Scanner(System.in);
boolean done = false;
while(!done) {
System.out.println("please enter Good Monkeys, Bad Monkeys or Show Monkeys");
System.out.println("(or enter 'done' to exit");
String userChoice = jScanner.nextLine();
swithc(userChoice.toLowerCase()) {
case "good monkeys":
/*
* The code for this option
*/
break;
case "bad monkeys":
/*
* The code for this option
*/
break;
case "show monkeys":
/*
* The code for this option
*/
break;
case "done":
done = true;
break;
default:
System.out.println("Your input isn't what I expected!\nTry again!");
break;
}
}
The code, explained:
That while(!done) stuff can be read as "while 'not done' do what follows"
userChoice.toLowerCase(): I convert the userChoice to lower-case, to simplify comparissons. That way, I only need to compare the string with other lower-case strings
switch(userChoice.toLowerCase()): ... hmmm... I think you can figure it out yourself ;)
That default block is what happens if no other case is valid
The "done" block will set the done variable to true, and thus it will terminate the loop
Important: ALWAYS end the case blocks with break
Further reading:
The Java Tutorials: Language basics
The while and do-while statements
The switch statement
Also, I recommend you study Flowcharts and, before start coding, try to draw in paper a flowchart of your program. That way, you will have a clear image of your program before you start writing the very first line of code.