I need two outcomes after a Do Else While statement, right now the user can input data and it will be stored in a String, if they want to add anything else they type 'y', if 'n' it will end the program and tell them what they've inputed. If they input neither of those and input 'd' for example it stops the statement running and takes me through to the Else statement
In the Else statement I want two outcomes, either "You have added the following" and "Error, you inputted something wrong"
Here is the Do Else While statement:
do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (input.next().startsWith("y")) {
System.out.println("Enter : ");
list.add(input.next());
} else {
System.out.println("You have added the following:");
System.out.println("Error, you inputted something wrong");
break;
}
} while (true);
What do I write to get two outcomes depending on what the user has done? (said 'n' or wrote something wrong).
Just add another if-else:
do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (input.next().startsWith("y"))
{
System.out.println("Enter : ");
list.add(input.next());
}
else
{
if(//valid input condition)
System.out.println("You have added the following:");
else
System.out.println("Error, you inputted something wrong");
break;
}
} while (true);
Try this:
do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (input.next().startsWith("y")) {
System.out.println("Enter : ");
list.add(input.next());
} else if (input.next().startsWith("n")) {
System.out.println("You have added the following:");
break;
} else {
System.out.println("Error, you inputted something wrong");
}
} while (true);
Introduce another condition in the else. Preferably, use else if:
do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
String userInput = input.next();
if (userInput.startsWith("y")) {
System.out.println("Enter : ");
list.add(input.next());
} elseif (userInput.startsWith("n")) {
// user wants to stop
System.out.println("You have added the following:");
break;
} else {
System.out.println("Error, you inputted something wrong");
break;
}
} while (true);
Try to use "IF" statement inside else statement
if (input.next().startsWith("y")) {
System.out.println("Enter : ");
list.add(input.next());
} else {
if (input.next().startsWith("n")) {
// Your code for "n"
}else{
//else here.
System.out.println("You have added the following:");
System.out.println("Error, you inputted something wrong");
break;
}
}
I think some of the logic and flow of your program is slightly off. I would change it to this.
Code:
boolean keepGoing = true; // can use a boolean to change the while loop condition to false.
while (keepGoing) {
System.out.println("Enter : ");
list.add(input.next());
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (input.next().startsWith("y")) { // 'if' to check if 'y', then execute this code.
keepGoing = true; // don't really need this, but it's here as example
} else if (input.next().startsWith("n")){ // 'else if' to check if 'n'.
System.out.println("You have added the following: " + list);
keepGoing = false; //change to false to stop the loop
} else { // and lastly a single 'else' if the input was invalid based on 2 previous conditions.
System.out.println("Error, you inputted something wrong"); // if for some reason the input isn't accepted this will show.
}
}
It follows a more logical flow and easier to understand. A simple while loop is easier for others to understand being that they can evaluate the condition before they enter the body of the loop.
You also don't need the Boolean and can simply use true in the while loop and break; in the else if portion, but as with do while loops, breaks can create confusion as far as when others need to look at your code once you start writing larger programs.
Related
If a user answers "yes" one of the 4 quotes print, randomly generate a number between 1 out of 4 and not print it, if a user answers "no" it prints "No quotes " and if it's neither it prints "Invalid", Should i use switch? if/else?
This is Java.
public static void main(String[] args) {
Scanner keyedInput = new Scanner(System.in);
String answer;
System.out.println("Do you want to be inspired? (Enter Yes/No)");
var Gen = Math.floor(Math.random() * 4 + 1);
answer = keyedInput.nextLine();
if (answer.equals("Yes")) {
System.out.println("Quote1");
}
else if (answer.equals("Yes")) {
System.out.println("Quote2");
}
else if (answer.equals("Yes")) {
System.out.println("Quote3");
}
else if (answer.equals("Yes")) {
System.out.println("Quote3");
}
if (answer.equals("No")) {
System.out.println("No quotes");
}
else {
System.out.println("Invalid");
}
}
This is a complex task: You want to ask the user yes/no, then if they answer neither 'yes' nor 'no', print something indicating that it's not valid and ask again.
So, make a method! And this method should loop - after all, it needs to keep doing the same thing, over and over again, until the user manages to provide a valid answer.
As a side-note, never use .nextLine(), it doesn't do what you think it does. Only use .next() if you want a string, .nextInt() if you want an int, etcetera. If you want whole lines of input (and you usually do), after making your scanner configure it to read lines at a time with scanner.useDelimiter("\\R");
public static boolean askBoolean(String prompt, Scanner scanner) {
while (true) {
System.out.print(prompt + " (yes/no): ");
String answer = scanner.next();
if (answer.equalsIgnoreCase("Yes")) return true;
if (answer.equalsIgnoreCase("No")) return false;
System.out.println("Please enter yes or no.");
}
}
Let's not use a switch, because equalsIgnoreCase sounds useful here.
and to use:
boolean wantsToBeInspired = askBoolean("Do you want to be inspired?", scanner);
if (wantsToBeInspired) {
showAQuote();
} else {
System.out.println("No quote for you");
}
I believe this is what you are trying to achieve:
int Gen = Math.floor(Math.random() * 4) + 1;
if(answer.equals("Yes")){
switch(Gen){
case 1: System.out.println("Quote 1"); break;
case 2: System.out.println("Quote 2"); break;
case 3: System.out.println("Quote 3"); break;
case 4: System.out.println("Quote 4"); break;
}
}else if(answer.equals("No")){
System.out.println("No quotes");
}else{
System.out.println("Invalid");
}
This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 5 years ago.
In my program I'm trying to get a user to input an int between 1-3 and then do something based off what they type. If it is not a number or not one of the options then it will allow them to reenter a valid option.
The issue I have is I'm having trouble brainstorming how to not have it infinitely loop and just allow them to enter in a number after the console tells them they entered an invalid input.
int i = 0;
while (i < 1) {
try {
int level = scan.nextInt();
i+=1;
if (level == 1) {
System.out.println("You selected level 1!");
//Start the game
} else if (level == 2) {
System.out.println("You selected level 2!");
//Start the game
} else if (level == 3) {
System.out.println("You selected level 3!");
//Start the game
} else {
System.out.println("That's not an option!");
i-=1;
}
} catch(InputMismatchException input) {
System.out.println("That's not an option!");
i-=1;
}
}
When you input an invalid input, you need to clear it. Add scan.next() when input exception triggered so as to clear it with next():
catch(InputMismatchException input) {
System.out.println("That's not an option!");
scan.next();
i-=1;
}
Not quite the answer you were expecting, but: refactor this code. Remember the basics of java, where every functional bit has its own method. So use a method that reads the input, and returns the level selected (or -1 if nothing):
int readInput() {
// your code here, returning either the level or -1 on bad input
}
And then call that for your read loop:
int selected;
do {
selected = readInput();
} while(selected < 1);
You are better off writing the code like this:
while(true){
try{
int level = scan.nextInt();
if(level==1){
System.out.println("You selected level 1!");
break;
}else if(level==2){
System.out.println("You selected level 2!");
break;
}else if(level==3){
System.out.println("You selected level 3!");
break;
}else{
System.out.println("That's not an option!");
continue;
}
}catch(InputMismatchException input){
System.out.println("That's not an option!");
continue;
}
}
continue will immediately resume execution of the loop at the top, and break will immediately jump too the closing brace } of the while. This removes the use of the i counter variable, which was entirely useless to the code. Also, this code will never run indefinitely, unless the user indefinitely enters improper values!
Hope this helped, good luck!
You can proceed in a much simpler way. The 3 valid cases are very similar and can be treated as one, the game can be started only once after the loop because we know that once the loop exits, level has a valid value.
boolean valid = false;
int level;
do {
try {
level = scan.nextInt();
valid = 1 <= level && level <= 3;
if (valid) {
System.out.println(String.format("You selected level %d !",level));
} else {
System.out.println("That's not an option!");
}
} catch(InputMismatchException input) {
scan.next();
System.out.println("That's not an option!");
}
} while (!valid);
// start the game
Hey guys this is my code and what it is doing is going in an loop but what its suppose to do is if the user types in borrow then it will ask the user how much which it does but then they type in a number and it will ask them again would you like to borrow or sell and it is in an infinite loop.
case 3:
do{
System.out.println("What would you like to do? Please type borrow to borrow money or sell to sell assets: ");
b = scan.nextLine().toLowerCase();
if(b.equals("borrow")){
System.out.print("how much would you like to borrow Remmber if you go over 50000 debt its game over.");
try {
input = scan.nextInt();
} catch (Exception e) {
System.err.println("That is not a number!!");
}
account.setdebt(account.getDebt() + input);
account.setBalance(account.getBalance() + input);
System.out.println("Your new Balance is " + account.getBalance());
}
else if(b.equals("sell")){
sellA();
}else{
System.out.println("You didn't input 'borrow' or 'sell'. Reinput please");
}
}while(!b.equals("borrow") || !b.equals("sell"));
break;
You need to change || to && inside while, otherwise the condition is always true. There'll always be at least one of those two values that b is not equal to.
// this is my code. It will only spit out that last bit of information (wallet and name) the second time i put in the players number
String option;
Boolean validChoice = false;
while(!validChoice){
option = gameScanner.nextLine();
try {
selectedPlayer = Integer.parseInt(option);
if (selectedPlayer<0|| selectedPlayer>playerNames.length) {
System.out.println("Invalid choice!: Please pick another number");
}else {
validChoice = true;
}
} catch(Exception ex){
selectedPlayer = -1;
System.out.println("Invalid choice!: Please pick another number");
}
}
System.out.println("");
System.out.println("PLAYER INFO");
System.out.println("Name: " + playerNames[selectedPlayer]);
System.out.println("Wallet: " + playerWallets[selectedPlayer]);
Problem : your if condition is not correct.as you are taking array index value as input(index always starts from 0) you should always check for both greater than or equal of length instead of only greater than of length of the array.
Reason for failure: assume your playerNames array contains 5 items means length = 5. so validChoid would be between 0 to 4 as array index starts from 0.
in the code as you have given wrong condition selectedPlayer>playerNames.length if the user enters 5(invalid) which will not satisfy above condition and then goes to else block setting the validChoice to true though it is invalid choice. as soon as validChoice becomes true it comes out from the while loop.
Solution: change the if condition from this :
if (selectedPlayer<0|| selectedPlayer>playerNames.length)
to this:
if (selectedPlayer<0 || selectedPlayer >= playerNames.length)
Complete Solution:
String option;
Boolean validChoice = false;
while(!validChoice){
option = gameScanner.nextLine();
try {
selectedPlayer = Integer.parseInt(option);
if (selectedPlayer<0 || selectedPlayer>=playerNames.length) {
System.out.println("Invalid choice!: Please pick another number");
}else {
validChoice = true;
}
} catch(Exception ex){
selectedPlayer = -1;
System.out.println("Invalid choice!: Please pick another number");
}
}
System.out.println("");
System.out.println("PLAYER INFO");
System.out.println("Name: " + playerNames[selectedPlayer]);
System.out.println("Wallet: " + playerWallets[selectedPlayer]);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I keep on getting this error and I tried mixing it around. But then when I choose the option, it does the option, but then said "you did not enter 1, 2 or 3".
This is the the full code. How to fix it?
The error is at
} else {
System.out.println("You did not enter 1, 2 or 3");
} else {
System.out.println("The Pin You Entered Was Wrong");
}
This is an incorrect syntax:
}else{
System.out.println("You did not enter 1, 2 or 3");
}else{
System.out.println("The Pin You Entered Was Wrong");
Just do it this way:
else {
System.out.println("You did not enter 1, 2 or 3");
System.out.println("The Pin You Entered Was Wrong");
}
The problem is in the code you provided on your paste bin.
You use two else statements, so Java complains as it doesn't know which to go to after the initial if statement.
You need to enter in another conditional statement using else if, then else. For example:
if (option == 1){
Option_1 Optionone = new Option_1();
Optionone.Withdraw();
}
etc
}else if (nothing entered) {
System.out.println("You did not enter 1, 2 or 3");
}else{
System.out.println("The Pin You Entered Was Wrong");
}
You also have another major problem with your code. You declare the variable option and set it in an if statement, so it only has scope within that if statement. You then come out of the if statement and declare a brand new option variable before the code I provided above. This will not function, as the option integer has no value.
Instead, you need to declare your initial option int outside of your if statement, like so:
int number;
int password = 7123;
int amount = 4000;
int option;
if (number == password) {
etc...
option = userInput.nextInt();
}
Furthermore, you come out of the if statement checking the entered number against the stored password to take input on withdrawing cash etc. This is no good. It means that after the if statement checking number against password is finished, it will automatically proceed to the next block of code.
As the scanner object hasn't been created, the first three if statements will come back false and your else statement will be printed (regardless of whether the input password was correct).
Therefore, I would advise you to put that check in a separare else statement and use a while loop to confirm a correct selection ahs been entered. For example:
System.out.println("Please Enter Your Bank Pin.");
Scanner userInput = new Scanner (System.in);
int number;
int password = 7123;
int amount = 4000;
int option;
number = userInput.nextInt();
if (number == password) {
System.out.println("Pin Accepted");
System.out.println("You Have Now Entered Harry's Bank!");
System.out.println("Press The Number Of The Option You Would Like.");
System.out.println("1.Withdraw Money.");
System.out.println("2.Put In Money");
System.out.println("3.Exit Bank");
Scanner Options = new Scanner (System.in);
option = userInput.nextInt();
while (option != 1 || option != 2 || option != 3) {
System.out.println("You didn't enter a valid number. Try again");
option = userInput.nextInt();
}
if (option == 1){
Option_1 Optionone = new Option_1();
Optionone.Withdraw();
}
else if (option == 2){
Option_2 Optiontwo = new Option_2();
Optiontwo.Deposit();
}
else if (option == 3){
Option_3 Optionthree = new Option_3();
Optionthree.Exit();
}
}
else
System.out.println("The Pin You Entered Was Wrong");
}
your second else statement does not close no if statement.
Also, the option variable is not in the right scope:
try this
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Welcome To Harry's Bank");
//Pin System
System.out.println("Please Enter Your Bank Pin.");
Scanner userInput = new Scanner (System.in);
int number;
int password = 7123;
int amount = 4000;
number = userInput.nextInt();
int option;
if (number == password) {
System.out.println("Pin Accepted");
System.out.println("You Have Now Entered Harry's Bank!");
System.out.println("Press The Number Of The Option You Would Like.");
System.out.println("1.Withdraw Money.");
System.out.println("2.Put In Money");
System.out.println("3.Exit Bank");
Scanner Options = new Scanner (System.in);
option = userInput.nextInt();
}else{
System.out.println("The Pin You Entered Was Wrong");
}
if (option == 1){
Option_1 Optionone = new Option_1();
Optionone.Withdraw();
}
if (option == 2){
Option_2 Optiontwo = new Option_2();
Optiontwo.Deposit();
}
if (option == 3){
Option_3 Optionthree = new Option_3();
Optionthree.Exit();
}else{
System.out.println("You did not enter 1, 2 or 3");
}
}
}
The problem is that you the 'else' statement twice in your if-else construct.
You have:
if { }
else { }
else { }
But you probably want:
if { }
else if { }
else { }
You cannot have TWO else in a if-else case.
Your nested If statement is not proper. Use it as below
if (number == password) {
.....
.....
if (option == 1) {
}
else if (option == 2) {
}
else if (option == 3) {
} else {
System.out.println("You did not enter 1, 2 or 3");
}
} else {
System.out.println("The Pin You Entered Was Wrong");
}
You can't have two else blocks added to an if
} else {
System.out.println("You did not enter 1, 2 or 3");
} else {
System.out.println("The Pin You Entered Was Wrong");
}
Either drop one or club the two println()s into one else block
} else {
System.out.println("You did not enter 1, 2 or 3");
System.out.println("The Pin You Entered Was Wrong");
}
Take a look at how to use the if-then and if-then-else statements.
Alternatively, I suggest you to make use of the Switch statements for better clarity of code.
switch (option) {
case 1: Option_1 OptionOne = new Option_1();
OptionOne.Withdraw();
break;
case 2: Option_2 OptionTwo = new Option_2();
OptionTwo.Withdraw();
break;
case 3: Option_3 OptionThree = new Option_3();
OptionThree.Withdraw();
break;
default: System.out.println("You did not enter 1, 2 or 3");
System.out.println("The Pin You Entered Was Wrong");
}