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);
Related
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
}
Here is link to the problem I am working on: http://programmingbydoing.com/a/adventure2.html
I cannot seem to get it to the downstairs area. We are supposed to use mainly while and if loops, so if there is a possibility to from one area of the loop to the other, that would be great to hear input!
public class Adventure2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int nextroom = 1;
String choice = "";
System.out.println("MITCHELL'S TINY ADVENTURE 2!");
System.out.println("")
while (nextroom != 0) {
if (nextroom == 1) {
System.out.println("You are in a creepy house! Would you like to go to the \"kitchen\" or \"upstairs\"?");
System.out.print("> ");
choice = keyboard.next();
if (nextroom == 1) {
System.out.println("There is a long countertop with dirty dishes everywhere. Off to one side there is, as you'd expect, a refrigerator. You may open the \"refrigerator\" or go \"back\".");
choice = keyboard.next();
if (choice.equals("back")) {
System.out.println("You are in a creepy house! Would you like to go to the \"kitchen\" or \"upstairs\"?");
System.out.println("> ");
choice = keyboard.next();
} else {
System.out.println("The refrigerator falls on you.");
if (nextroom == 2) {
System.out.println("You are in a creepy house! Would you like to go to the \"kitchen\" or \"upstairs\"?");
System.out.println("> ");
choice = keyboard.next();
if (choice.equals("upstairs")) {
System.out.println("Upstairs you see a hallway. At the end of the hallway is the master \"bedroom\". There is also a \"bathroom\" off the hallway. Or you can go back \"downstairs\". Where would you like to go?");
System.out.println("> ");
choice = keyboard.next();
if (choice.equals("downstairs")) {
System.out.println("You are in a creepy house! Would you like to go to the \"kitchen\" or \"upstairs\"?");
}
}
}
}
}
}
}
}
}
Frankly your code is a bit of a mess, but that's not unusual for a beginner.
The trick is to carefully read the code that you have written, and to "run it in your head". In your example, you will come to this point:
System.out.println("You are in a creepy house!...");
System.out.print("> ");
choice = keyboard.next();
You read a choice. But what happens next? What do you do with that choice? Answer .... nothing! Here's what you do next.
if (nextroom == 1) {
System.out.println("There is a long countertop ...;
choice = keyboard.next();
You have ignored the first choice you read, you test nextroom again (which won't have changed because you didn't assign anything new to it.
If you read your code carefully and try to run it in your head (like a computer does), then these problems should leap out at you. If that's too hard, then using a debugger will help.
That brings us back to my original comment. When you start getting your head around what should be happening, you should realise that there general pattern that your program should follow. Something like this
while (not finished):
print description of where I am
print choices of where to go next next
get choice
if choice is valid:
change location
else:
print error message
If you do it right, you should not need to copy-and-paste the pattern in the loop body multiple times.
Hint: think about using array and array indexing.
Hint 2: nextroom could be used as an array index.
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:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
Below is a snippet of code from a class in a simple program I'm writing that plays a simple game of Blackjack. I don't understand why the hit method isn't executing whenever, upon execution of the program, I enter "hit". It goes to the else part of the statement every time regardless of what I enter. I even added a System.out.println statement to make sure that the strings matched. I feel like I must be making a very basic mistake but I just can't seem to figure it out.
System.out.println("Would you like to hit or stand?");
Scanner input = new Scanner(System.in);
String playerDecision = input.nextLine();
//System.out.println(playerDecision);
if(playerDecision == "hit") {
hit();
}
else { System.out.println("ERROR");
}
}
public void hit(){
player.makeHand(deck.draw());
System.out.println("You have the following cards: ");
player.getHand();
System.out.println("Your hand total is ");
System.out.println(player.findHandTotal());
}
Wrong string comparison. Try
if("hit".equals(playerDecision)) {
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.