how to prompt user to loop the code yes to loop no to exit and wrong input print wrong input and go back to statement ie. "do you want to enter another name:"
import java.util.Scanner;
public class loop {
public static void main(String[] args){
Scanner kbd = new Scanner (System.in);
String decision;
boolean yn;
while(true){
System.out.println("please enter your name");
String name = kbd.nextLine();
System.out.println("you entered the name" + name );
System.out.println("enter another name : yes or no");
decision = kbd.nextLine();
switch(decision){
case "yes":
yn = false;
break;
case "no":
yn = true;
break;
default :
System.out.println("please enter again ");
return default;
}
}
}
}
If you don't use Java 7 you can't use switch-strings
Change while (true) with while (yn) so it will stop when he type "no", and change boolean yn; to boolean yn = true;
And change the rules inside the cases too.
case "yes":
yn = false;
break;
case "no":
yn = true;
break;
yn = true; if "yes";
yn = false; if "no";
You could change the condition inside the while, with while (!yn) but is more intuitive to let yn true if yes; false if no.
return default; don't make much sense, if you want to let user repeat in case of error well.. you should do a new while (true) to repeat until he writes a correct one. I would write another method.
This is how you could do it
Scanner kbd = new Scanner (System.in);
String decision;
boolean yn = true;
while(yn)
{
System.out.println("please enter your name");
String name = kbd.nextLine();
System.out.println("you entered the name" + name );
System.out.println("enter another name : yes or no");
decision = kbd.nextLine();
switch(decision)
{
case "yes":
yn = true;
break;
case "no":
yn = false;
break;
default:
System.out.println("please enter again ");
boolean repeat = true;
while (repeat)
{
System.out.println("enter another name : yes or no");
decision = kbd.nextLine();
switch (decision)
{
case "yes":
yn = true;
repeat = false;
break;
case "no":
yn = repeat = false;
break;
default:
repeat = true;
}
}
break;
}
}
Yes it will repeat decision code, but how it is created i think it is the only way to do it.
Yes, but you'd want while(yn), not while(true), which goes on forever. The break only breaks from the switch statement.
Alright, try this:
import java.util.Scanner;
public static void main(String args[]){
Scanner s = new Scanner(System.in);
boolean checking = true, valid = true;
String[] names = new String[50];
int i = 0;
while(checking){
System.out.println("Enter name...");
me = s.nextLine();
System.out.println("You entered " + me + ".");
while(valid){
System.out.println("Enter another? y/n");
you = s.nextLine();
if(you.equals("n")){
valid = false;
checking = false;
}else if you.equals("y")){
names[i] = you;
i++;
valid = false;
}else{
System.out.println("Sorry, try again (y/n)...");
}
}
}
}
boolean input = true;
while(input){
//ask for name
//print message saying you entered xyz
//ask if user wants to enter other name
//if user enters no
//set input = false;
//else continue
}
try doing this
Rather then break and while(true), you need to say while(!yn) as you set yn to false when the user input yes.
I just created a small class YesNoCommandPrompt that does just that:
private String prompt;
private Supplier<T> yesAction;
private Supplier<T> noAction;
public YesNoCommandPrompt(String prompt, Supplier<T> yesAction, Supplier<T> noAction) {
this.prompt = prompt;
this.yesAction = yesAction;
this.noAction = noAction;
}
// example usage
public static void main(String[] args) {
YesNoCommandPrompt<String> prompt = new YesNoCommandPrompt<>(
"Choose",
() -> {return "yes";},
() -> {return "no";});
System.out.println(prompt.run());
}
public T run() {
final String yesOption = "y";
final String noOption = "n";
try (Scanner scanner = new Scanner(System.in)) {
while (true) {
System.out.print(prompt + " [" + yesOption + "/" + noOption + "]: ");
String option = scanner.next();
if (yesOption.equalsIgnoreCase(option)){
return yesAction.get();
}
else if (noOption.equalsIgnoreCase(option)){
return noAction.get();
}
}
}
}
Related
I am trying to figure out where to put the loop that when the user enters any value other than "rock", "paper" or "scissors" the program stays in the loop and displays "Invalid entry" while requesting the user to enter again.
Any help is much appreciated.
As it stands now, the program will display "Invalid entry" but then continues without asking the user to try again.
import java.util.Scanner; // Import the Scanner class
import java.util.Random; // Import the random class for game
/**
*/
public class Challenge17
{
// Method to determine the random choice of computer
public static String getComputerChoice(Random random)
{
int number;
number = random.nextInt(3) + 1;
String computerChoice;
switch (number)
{
case 1:
computerChoice = "rock";
break;
case 2:
computerChoice = "paper";
break;
case 3:
computerChoice = "scissors";
break;
default:
computerChoice = "";
}
return computerChoice;
}
// Method to display the menu for choices
public static void displayChoice( )
{
System.out.println("Game Options\n----------\n"
+ "1: rock\n2: paper\n3: scissors");
}
// Method to request and hold user choice for game
public static String getUserInput(Scanner keyboard)
{
String userInput;
System.out.println("Enter your choice: ");
userInput = keyboard.nextLine();
return userInput;
}
// Method to determine winner
public static String determineWinner(String computerChoice, String userInput)
{
String winner = "Tie Game!"; // Default display Tie game
String message = ""; // To determine the message for winner
String displayMessage; // To display the message for winner
// Custom messages below
String rockMessage = "Rock smashes scissors";
String scissorsMessage = "Scissors cuts paper";
String paperMessage = "Paper wraps rock";
boolean loop = false;
if(computerChoice.equals("rock") && userInput.equalsIgnoreCase("scissors"))
{
winner = " Computer wins!";
message = rockMessage;
loop = true;
}
else if (userInput.equalsIgnoreCase("rock") && computerChoice.equals("scissors"))
{
winner = "You win!";
message = rockMessage;
loop = true;
}
if(computerChoice.equals("scissors") && userInput.equalsIgnoreCase("paper"))
{
winner = " Computer wins!";
message = scissorsMessage;
loop = true;
}
else if (userInput.equalsIgnoreCase("scissors") && computerChoice.equals("paper"))
{
winner = "You win!";
message = scissorsMessage;
loop = true;
}
if(computerChoice.equals("paper") && userInput.equalsIgnoreCase("rock"))
{
winner = " Computer wins!";
message = paperMessage;
loop = true;
}
else if (userInput.equalsIgnoreCase("rock") && computerChoice.equals("scissors"))
{
winner = "You win!";
message = paperMessage;
loop = true;
}
else
{
System.out.println("Invalid entry.");
loop = false;
}
displayMessage = winner + " " + message;
return displayMessage;
}
// Main method to initiate and execute game
public static void main(String[] args)
{
Random random = new Random(); // To call the random class
Scanner keyboard = new Scanner(System.in); // To call the scanner class
String computerChoice; // Hold computer input
String userInput; // Hold user input
String input; // Hold input for repeat
char repeat; // Character for repeat
do
{
displayChoice(); // Call method to display the choices
computerChoice = getComputerChoice(random); // Hold the PC random choice
userInput = getUserInput(keyboard); // To get the user input
System.out.println("You chose: " + userInput + " computer chose: \n"
+ computerChoice);
System.out.println(determineWinner(computerChoice, userInput));
// Does the user want to play again
System.out.println("Would you like to play again?");
System.out.print("Enter Y for yes, or N for no: ");
input = keyboard.nextLine();
repeat = input.charAt(0);
}
while (repeat == 'Y' || repeat == 'y');
}
}
From my understanding i'm pretty sure you want this kind of a loop
public static String getUserInput(Scanner keyboard)
{
String userInput;
System.out.println("Enter your choice: ");
userInput = keyboard.nextLine();
while(!userInput.equals("rock")&&!userInput.equals("paper")&&!userInput.equals("scissors"))
{
System.out.println("Invalid Entry, Please re-enter your choice:");
userInput = keyboard.nextLine();
} //It wont go out of the loop unless it's one of the 3 choices
return userInput;
}
You could create a Boolean method.
private Boolean checkUserInput(String input) {
if(!input.equalsIgnoreCase("rock") && !input.equalsIgnoreCase("paper") && !input.equalsIgnoreCase("scissors")) return false;
return true;
Then you do the check before you determine the winner like if true then run the determineWinner(computerChoice, userInput) code else it doesn't.
That way, you can edit the code and add functionalities in the future if need be.
i wanna know how can i skip my try again part if my input in 'input' is invalid. for example, I enter 'o' as my choice. it should display "invalid input" and it should display the menu part (skipping the try again). help me please.
public class Menu {
public static void MainMenu() {
Part1 call1 = new Part1();
Part2 call2 = new Part2();
Part3 call3 = new Part3();
Part4 call4 = new Part4();
Scanner in = new Scanner(System.in);
String yn = null;
do {
System.out.println("\t\t---HOMEWORK---");
System.out.println("\tI for PART 1");
System.out.println("\tII for PART 2");
System.out.println("\tIII for PART 3");
System.out.println("\tIV for PART 4");
System.out.print("\tEnter input: ");
String input = in.next();
do {
switch (input) {
case "I":
call1.one();
break;
case "II":
call2.two();
break;
case "III":
call3.three();
break;
case "IV":
call4.four();
break;
case "V":
System.exit(0);
break;
default:
System.out.println("invalid input");
break;
}
System.out.print("try again? -Y- || -N- : ");
yn = in.next();
} while (yn.equalsIgnoreCase("y"));
} while (yn.equalsIgnoreCase("n"));
}
}
public class Menu {
public static void MainMenu() {
Part1 call1 = new Part1();
Part2 call2 = new Part2();
Part3 call3 = new Part3();
Part4 call4 = new Part4();
boolean inputWasValid = false;
Scanner in = new Scanner(System.in);
String yn = null;
do {
System.out.println("\t\t---HOMEWORK---");
System.out.println("\tI for PART 1");
System.out.println("\tII for PART 2");
System.out.println("\tIII for PART 3");
System.out.println("\tIV for PART 4");
System.out.print("\tEnter input: ");
String input = in.next();
do {
switch (input) {
case "I":
call1.one();
break;
case "II":
call2.two();
break;
case "III":
call3.three();
break;
case "IV":
call4.four();
break;
case "V":
System.exit(0);
break;
default:
inputWasValid = true;
System.out.println("invalid input");
break;
}
if (inputWasValid) {
break;
}
System.out.print("try again? -Y- || -N- : ");
yn = in.next();
} while (yn.equalsIgnoreCase("y"));
} while (yn.equalsIgnoreCase("n"));
}
}
as #Kevin say, you can try this.
My understanding is that you want something like this:
...
Scanner in = new Scanner(System.in);
String yn = null;
boolean retry;
do {
System.out.println("\t\t---HOMEWORK---");
System.out.println("\tI for PART 1");
System.out.println("\tII for PART 2");
System.out.println("\tIII for PART 3");
System.out.println("\tIV for PART 4");
System.out.print("\tEnter input: ");
String input = in.next();
retry = true;
switch (input) {
...
default:
System.out.println("invalid input");
break;
}
System.out.print("try again? -Y- || -N- : ");
yn = in.next();
// might want to do check & loop here to see if user enters just Y or N
if(retry && yn.equalsIgnoreCase("N")) retry = false;
} while (retry);
With this, you get the following results:
Input I try again Y will run through loop again
Input I try again N will terminate loop
Input P try again Y will run through loop again (invalid input displayed, but give user choice of continuing)
Input P try again N will terminate loop (invalid input displayed, user decides to not continue)
import java.util.Scanner ;
public class Mal {
public static void main (String []args) {
System.out.println("Welcome") ;
Scanner myinput=new Scanner (System.in) ;
System.out.println("Make your choice. \n 1.Check a card number \n 2.Quit.");
int choise=myinput.nextInt();
switch(choise) {
case 1:System.out.println("Enter your credit card number: ");
break;
case 2:System.out.println("Are you sure?") ;
String answer=myinput.next();
if(answer.equals("yes")){
System.out.println("Byee :)") ;
System.exit(0);
}
break;
default: System.out.println("Idiot!") ;
break;
}
}
}
i want a program which starts again if user types something different than "yes"
Here's what you can do
have a flag like this
boolean quit = false;
and a while enclosing your options
while(!quit){
...
...
}
and
set quit = true if the user wants to quit.
EDIT:
Something like this
public static void main(String a[]) {
System.out.println("Welcome");
Scanner myinput = new Scanner(System.in);
boolean quit = false;
while (!quit) {
System.out
.println("Make your choise. \n 1.Check a card number \n 2.Quit.");
int choise = myinput.nextInt();
switch (choise) {
case 1:
System.out.println("Enter your credit card number: ");
break;
case 2:
System.out.println("Are you sure?");
String answer = myinput.next();
if (answer.equals("yes")) {
System.out.println("Byee :)");
quit= true;
}
break;
default:
System.out.println("Idiot!");
break;
}
}
package thecashmachin;
import java.util.Scanner;
public class TheCashMachin {
public static void main(String[] args) {
int pin, proceed2=0, withdraw, dailydraw, Proceed, proceed3 = 0;
double balance;
Scanner pinnumber = new Scanner(System.in);
Scanner proc2 = new Scanner(System.in);
Scanner withd = new Scanner(System.in);
Scanner Next = new Scanner(System.in);
Scanner proc3 = new Scanner(System.in);
balance = 9999.99;
dailydraw = 1000;
System.out.println(
"text .");
System.out.println("1)Proceed");
System.out.println("2)Return Card");
Proceed = Next.nextInt();
switch (Proceed) {
case 1:// Proceed
System.out.println("Please enter your 5 digit pin below.");
Scanner Pin = new Scanner(System.in);
int Pincode = Pin.nextInt();
if (Pincode > 9999 && Pincode < 99999) {
System.out.println("1)Display Balance");
System.out.println("2)Withdraw Cash");
System.out.println("3)Other services");
proceed2 = proc2.nextInt();
} else {
System.err.println(
"text");
}
break;
case 2:// Return Card
System.err.println("text");
break;
default:
System.err.println(
"text");
break;}
switch (proceed2) {
case 1:
System.out.println("Your balance today is: 9999.99");
/*
* so right here the balance is shown and in real life you would have a go back button to display the other options but on my code after the balance is displayed you cant do anything else have to re run the the script i want a code that if selected goes back to the last option*/
break;
case 2:
System.out.println("Amount to withdraw");
withdraw = withd.nextInt();
System.out.println("Please take the cash");
System.out.println("Current Balance" + " " + (balance - withdraw));
System.out.println("Daily withdraw left:" + (dailydraw - withdraw));
if (withdraw > dailydraw) {
System.err.println("text");
}
case 3:
System.out.println("Would you like to;");
System.out.println("1)Order a check");
System.out.println("2)Order a Statement");
proceed3 = proc3.nextInt();
break;
default:
System.out.println("text");
}
switch (proceed3) {
case 1:
System.out.println("Your check has been orderd");
break;
case 2:
System.out.println("Your Statement has been orderd");
break;
}
}
}
DO
BOOLEAN = TRUE;
SWITCH() // WITH THE DIFFERENT CASES
DEFAULT BOOLEAN = FALSE;
WHILE BOOLEAN IS FALSE;
This should do. Use a simple do while loop.
Before entering the switch, your boolean is set to TRUE and if it comes to the default it turns it to FALSE and you loop until the boolean stays TRUE
An easy way I know is just making a Boolean before which is kept same as default..
boolean test = True;
while (test)
{
switch(Proceed)
{
case 1://Proceed
System.out.println("Please enter your 5 digit pin below.");
Scanner Pin=new Scanner(System.in);
int Pincode=Pin.nextInt();
test = false;
break;
case 2://Return Card
System.err.println("Your card is being ejected.\n Please Wait..");
test = false;
break;
default:
System.err.println("Sorry your request could not be processed.\n Please enter the pin again.\n")
// when neither case is true, keeps loop running.
break;
}
}
import java.util.Scanner ;
public class Mal {
public static void main (String []args) {
System.out.println("Welcome") ;
Scanner myinput=new Scanner (System.in) ;
System.out.println("Make your choice. \n 1.Check a card number \n 2.Quit.");
int choise=myinput.nextInt();
switch(choise) {
case 1:System.out.println("Enter your credit card number: ");
break;
case 2:System.out.println("Are you sure?") ;
String answer=myinput.next();
if(answer.equals("yes")){
System.out.println("Byee :)") ;
System.exit(0);
}
break;
default: System.out.println("Idiot!") ;
break;
}
}
}
i want a program which starts again if user types something different than "yes"
Here's what you can do
have a flag like this
boolean quit = false;
and a while enclosing your options
while(!quit){
...
...
}
and
set quit = true if the user wants to quit.
EDIT:
Something like this
public static void main(String a[]) {
System.out.println("Welcome");
Scanner myinput = new Scanner(System.in);
boolean quit = false;
while (!quit) {
System.out
.println("Make your choise. \n 1.Check a card number \n 2.Quit.");
int choise = myinput.nextInt();
switch (choise) {
case 1:
System.out.println("Enter your credit card number: ");
break;
case 2:
System.out.println("Are you sure?");
String answer = myinput.next();
if (answer.equals("yes")) {
System.out.println("Byee :)");
quit= true;
}
break;
default:
System.out.println("Idiot!");
break;
}
}