Can someone edit my code to make it loop the selection menu. If the choice is not one of the 5 options it will prompt the user to re-enter until it is a valid option. If possible an explanation would be helpful as well. Thanks
Here is my code.
import java.util.*;
public class ShapeLoopValidation
{
public static void main (String [] args)
{
chooseShape();
}
public static void chooseShape()
{
while (true){
Scanner sc = new Scanner(System.in);
System.out.println("Select a shape number to calculate area of that shape!");
System.out.print("Circle = 1. \nRectangle = 2. \nTriangle = 3. \nExit = 4. \nINPUT : ");
int shapeChoice = sc.nextInt();
//while (true) {
if (shapeChoice >= 1 && shapeChoice <=4)
{
if (shapeChoice == 1)
{
circle();
}
else if (shapeChoice == 2)
{
rectangle();
}
else if (shapeChoice == 3)
{
triangle();
}
else if (shapeChoice == 4)
{
return;
}
}
else
{
System.out.print("Error : Choice " + shapeChoice + "Does not exist.");
}
}
class Test {
int a, b;
Test(int a, int b) {
this.a = a;
this.b = b;
}
}
}
First: take a look at switch
Second: read a bit about do-while loops (they are usually a good fit for this kind of situations).
Now, how I would implement it (but you should really learn how to make a loop in this scenarios):
public static void chooseShape () {
boolean valid = false;
do {
Scanner sc = new Scanner(System.in);
System.out.println("Select a shape number to calculate area of that shape!");
System.out.print("Circle = 1. \nRectangle = 2. \nTriangle = 3. \nExit = 4. \nINPUT : ");
int shapeChoice = sc.nextInt();
switch (shapeChoice) {
valid = true;
case 1:
circle();
break;
case 2:
rectangle();
break;
case 3:
triangle();
break;
case 4:
return;
default:
valid = false;
System.out.println("Error : Choice " + shapeChoice + "Does not exist.");
System.out.println("Please select one that exists.")
}
} while (!valid)
}
Use do-while flow control until EXIT code entered:
int shapeChoice;
do {
System.out.println("Select a shape number to calculate area of that shape!");
System.out.print("Circle = 1. \nRectangle = 2. \nTriangle = 3. \nExit = 4. \nINPUT : ");
int shapeChoice = sc.nextInt();
// then use if-else or switch
} while (shapeChoice != 4);
OR
use break statement to loop break at your code as bellow:
else if (shapeChoice == 4)
{
break;
}
Related
I am having a problem getting my code to loop with a while statement. I want it to be like when you input 1 in difficulty you get Beginner. Then it would ask if you want beginner. If not then you press 2. Then it would go back into the loop and ask you what difficulty you want. Then eventually break the loop.
The Beginner();, Intermediate();, and Hard(); is there to call something.
Also would it be possible to do option with strings instead?
For example.
System.out.print("\nPlease choose your difficulty (1.Beginner, 2.Intermediate, 3.Hard) ");
Difficulty = option.next();
I initially wanted it to be where you could type out "Hard" and it would ask "You have chosen hard. Is this correct?"
public static void gameSetting() {
String settings = null;
int Difficulty = 0;
int Beginner = 1;
int Intermediate = 2;
int Hard = 3;
System.out.print("\nPlease choose your difficulty (1.Beginner, 2.Intermediate, 3.Hard) ");
Difficulty = option.nextInt();
while(true){if(Difficulty==1) {
System.out.print("You have chosen Beginner. Is this correct?");
System.out.println("\n1.Yes, 2.No");
int choice = option.nextInt();
if (choice == 1) {
Beginner();
}
break;
}
if(Difficulty == 2) {
System.out.print("\n\nYou have chosen Intermediate. Is this correct?");
System.out.println("\n\n1.Yes, 2.No");
int choice = option.nextInt();
if(choice==1) {
Intermediate();
}
break;
}
System.out.print("\nPlease choose your difficulty (1.Beginner, 2.Intermediate, 3.Hard) ");
Difficulty = option.nextInt();
if(Difficulty == 3) {
System.out.print("\n\nYou have chosen Hard. Is this correct?");
System.out.println("\n\n1.Yes, 2.No");
int choice = option.nextInt();
if(choice==1) {
Hard();
}
break;
}
System.out.print("\nPlease choose your difficulty (1.Beginner, 2.Intermediate, 3.Hard) ");
Difficulty = option.nextInt();
}
}
My Loop code that i'm trying to get to work ^
As I mentioned in the comments, move the break statements into your if bodies and only prompt for Difficulty once per iteration. Also, your variable names deviate from Java standard naming conventions. Difficulty should be difficulty, and constants should be in all caps (and you could use the constants you have defined). Like,
public static void gameSetting() {
final int BEGINNER = 1, INTERMEDIATE = 2, HARD = 3;
while (true) {
System.out.println("Please choose your difficulty (1.Beginner,"
+ " 2.Intermediate, 3.Hard) ");
int difficulty = option.nextInt();
if (difficulty == BEGINNER) {
System.out.print("You have chosen Beginner. Is this correct?");
System.out.println("\n1.Yes, 2.No");
int choice = option.nextInt();
if (choice == 1) {
Beginner();
break;
}
} else if (difficulty == INTERMEDIATE) {
System.out.print("\n\nYou have chosen Intermediate. Is this correct?");
System.out.println("\n\n1.Yes, 2.No");
int choice = option.nextInt();
if (choice == 1) {
Intermediate();
break;
}
} else if (difficulty == HARD) {
System.out.print("\n\nYou have chosen Hard. Is this correct?");
System.out.println("\n\n1.Yes, 2.No");
int choice = option.nextInt();
if (choice == 1) {
Hard();
break;
}
}
}
}
Also, you could refactor the common confirmation messages into another method. Like,
private static boolean confirmDifficulty(String difficulty) {
System.out.printf("You have chosen %s. Is this correct?%n", difficulty);
System.out.println("1.Yes, 2.No");
return option.nextInt() == 1;
}
And then your code might look like
public static void gameSetting() {
final int BEGINNER = 1, INTERMEDIATE = 2, HARD = 3;
while (true) {
System.out.println("Please choose your difficulty (1.Beginner,"
+ " 2.Intermediate, 3.Hard) ");
int difficulty = option.nextInt();
if (difficulty == BEGINNER) {
if (confirmDifficulty("Beginner")) {
Beginner();
break;
}
} else if (difficulty == INTERMEDIATE) {
if (confirmDifficulty("Intermediate")) {
Intermediate();
break;
}
} else if (difficulty == HARD) {
if (confirmDifficulty("Hard")) {
Hard();
break;
}
}
}
}
I would like to ask why the program prints already the answer? Even if I select on different Difficulty it is still the same.
import java.util.Scanner;
import java.util.Random;
public class GuessigGame {
public static int level(int y) {
Random ans = new Random();
int easy = 20, medium = 50, hard = 10, x;
Scanner in = new Scanner(System.in);
System.out.println("Choose Difficulty");
System.out.println("1. easy ");
System.out.println("2. medium ");
System.out.println("3. hard ");
x = in.nextInt();
switch (x) {
case 1:
System.out.println("Easy");
y = easy;
break;
case 2:
System.out.println("Medium");
y = medium;
break;
case 3:
System.out.println("Hard");
y = hard;
break;
default:
break;
}
return y;
}
public static void main(String[] args) {
int choice, difficulty = 0, answer = -1;
Scanner in = new Scanner(System.in);
Random rand = new Random();
System.out.println("\n\n1. Play Game");
System.out.println("2. Exit");
System.out.println("");
choice = in.nextInt();
int diff = 0, tries = 0, triesbot = 0, trieshu = 0;
diff = level(difficulty);
difficulty = 1 + rand.nextInt(diff);
boolean win = false;
switch (choice) {
case 1:
while (win != true) {
System.out.println(difficulty);
System.out.println("Tries: " + tries);
answer = in.nextInt();
if (answer == difficulty + 1 || answer == difficulty - 1) {
System.out.println("so close");
} else if (answer == difficulty + 2 || answer == difficulty + 2) {
System.out.println("youre answer was close");
} else if (answer == difficulty + 3 || answer == difficulty - 3) {
System.out.println("try more youre close");
} else if (answer == difficulty + 4 || answer == difficulty - 4) {
System.out.println("try youre best buddy!");
} else if (answer > difficulty + 4 || answer < difficulty - 4) {
System.out.println("so far!");
} else if (tries == 0) {
System.out.print("Game Over!");
win = true;
} else if (answer == difficulty) {
System.out.println("You got the correct answer!!!!");
win = true;
} else {
}
tries++;
}
break;
default:
System.exit(0);
break;
}
}
}
This is the output of the program:
Because you told the computer to print out the difficulty. I suggest having better names.
difficulty = 1 + rand.nextInt(diff);
boolean win = false;
switch(choice) {
case 1:
while(win != true) {
System.out.println(difficulty);
System.out.println("Tries: " + tries);
I have to get my course code to validate. The course code is set to a number 1-7 and the choice has to be within this range. Each course is worth 3 credits. The user can not register for more than 9 credits. The user can not register for the same course more than once. I am having trouble with the repeat course code.
Here is my code:
package u6a1_consoleregisterforcourse;
import java.util.Scanner;
public class U6A1_ConsoleRegisterForCourse {
public static void main(String[] args) {
System.out.println("Quenten's Copy");
Scanner input = new Scanner(System.in);
//choice is the current menu selection
//firstChoice is the first menu selection mande by the user
//secondChoice is the second menu selection mande by the user
//thirdChoice is the third menu selection mande by the user
// a choice of 0 means the choice has not been made yet
int choice;
int firstChoice = 0, secondChoice = 0, thirdChoice = 0;
int totalCredit = 0;
String yesOrNo = "";
do {
choice = getChoice(input);
switch (ValidateChoice(choice, firstChoice, secondChoice, thirdChoice, totalCredit)) {
case -1:
System.out.println("**Invalid** - Your selection of " + choice + " is not a recognized course.");
break;
case -2:
System.out.println("**Invalid** - You have already registerd for this " + ChoiceToCourse(choice) + " course.");
break;
case -3:
System.out.println("**Invalid** - You can not register for more than 9 credit hours.");
break;
case 0:
System.out.println("Registration Confirmed for course " + ChoiceToCourse(choice) );
totalCredit += 3;
if (firstChoice == 0)
firstChoice = choice;
else if (secondChoice == 0)
secondChoice = choice;
else if (thirdChoice == 0)
thirdChoice = choice;
break;
}
WriteCurrentRegistration(firstChoice, secondChoice, thirdChoice);
System.out.print("\nDo you want to try again? (Y|N)? : ");
yesOrNo = input.next().toUpperCase();
} while (yesOrNo.equals("Y"));
System.out.println("Thank you for registering with us");
}
public static int getChoice(Scanner input) {
System.out.println("Please type the number inside the [] to register for a course");
System.out.println("[1]IT4782\n[2]IT4784\n[3]IT4786\n[4]IT4789\n[5]IT2230\n[6]IT3345\n[7]IT3349");
System.out.print("Enter your choice : ");
return (input.nextInt());
}
//This method validates the user menu selection
//against the given registration business rules
//it returns the following code based on the validation result
// -1 = invalid, unrecognized menu selection
// -2 = invalid, alredy registered for the course
// -3 = invalid, No more than 9 credit hours allowed
// 0 = menu selection is valid
public static int ValidateChoice(int choice, int firstChoice, int secondChoice, int thirdChoice, int totalCredit) {
// TO DO - Add Code to:
// Validate user menu selection (the int choice method argument)
// against the given registration business rules
int ValidateChoice;
if ((choice < 1) || (choice >= 8)){
ValidateChoice = -1;}
else if (secondChoice == firstChoice){
ValidateChoice = -2;}
else
{ValidateChoice = 0;}
return ValidateChoice;
}
public static void WriteCurrentRegistration(int firstChoice, int secondChoice, int thirdChoice) {
if (firstChoice == 0)
System.out.println("Current course registration: { none } " );
else if (secondChoice == 0)
System.out.println("Current course registration: { " + ChoiceToCourse(firstChoice) + " }" );
else if (thirdChoice == 0)
System.out.println("Current course registration: { " + ChoiceToCourse(firstChoice) +
", " + ChoiceToCourse(secondChoice) + " }");
else
System.out.println("Current course registration: { " + ChoiceToCourse(firstChoice) +
", " + ChoiceToCourse(secondChoice) + ", " + ChoiceToCourse(thirdChoice) + " }");
}
public static String ChoiceToCourse(int choice) {
String course = "";
switch (choice)
{
case 1:
course = "IT4782";
break;
case 2:
course = "IT4784";
break;
case 3:
course = "IT4786";
break;
case 4:
course = "IT4789";
break;
case 5:
course = "IT2230";
break;
case 6:
course = "IT3345";
break;
case 7:
course = "IT3349";
break;
default:
break;
}
return course;
}
}
The ValidateChoice method is what I am working on. This is for an academic assignment.
It is better to get rid of those firstChoice, secondChoice, thirdChoice variables and use a homogeneous collection instead:
package u6a1_consoleregisterforcourse;
import java.util.*;
public class U6A1_ConsoleRegisterForCourse {
public static final int CREDITS_PER_COURSE = 3;
public static final int MAX_CREDITS = 9;
public static final int MAX_COURSES = MAX_CREDITS / CREDITS_PER_COURSE;
private final List<Integer> registeredCourses = new ArrayList<>(MAX_COURSES);
private int totalCredit;
public static void main(String[] args) {
System.out.println("Quenten's Copy");
U6A1_ConsoleRegisterForCourse registrar = new U6A1_ConsoleRegisterForCourse();
Scanner input = new Scanner(System.in);
//choice is the current menu selection
int choice;
String yesOrNo;
do {
choice = getChoice(input);
switch (registrar.validateChoice(choice)) {
case -1:
System.out.println("**Invalid** - Your selection of " + choice + " is not a recognized course.");
break;
case -2:
System.out.println("**Invalid** - You have already registered for this " + choiceToCourse(choice) + " course.");
break;
case -3:
System.out.println("**Invalid** - You can not register for more than " + MAX_CREDITS + " credit hours.");
break;
case 0:
System.out.println("Registration Confirmed for course " + choiceToCourse(choice));
registrar.totalCredit += CREDITS_PER_COURSE;
registrar.registeredCourses.add(choice);
break;
}
registrar.writeCurrentRegistration();
System.out.print("\nDo you want to try again? (Y|N)? : ");
yesOrNo = input.next().toUpperCase();
} while (yesOrNo.equals("Y"));
System.out.println("Thank you for registering with us");
}
private static final String[] courses = {"IT4782", "IT4784", "IT4786", "IT4789", "IT2230", "IT3345", "IT3349"};
public static String choiceToCourse(int choice) {
return courses[choice - 1];
}
public static int getChoice(Scanner input) {
System.out.println("Please type the number inside the [] to register for a course");
for (int i = 1; i <= courses.length; i++)
System.out.format("[%d]%s%n", i, choiceToCourse(i));
System.out.print("Enter your choice : ");
return (input.nextInt());
}
// This method validates the user menu selection
// against the given registration business rules
// it returns the following code based on the validation result
// -1 = invalid, unrecognized menu selection
// -2 = invalid, alredy registered for the course
// -3 = invalid, No more than 9 credit hours allowed
// 0 = menu selection is valid
public int validateChoice(int choice) {
if ((choice < 1) || (choice > courses.length))
return -1;
if (registeredCourses.contains(choice))
return -2;
if (totalCredit + CREDITS_PER_COURSE > MAX_CREDITS)
return -3;
return 0;
}
public void writeCurrentRegistration() {
StringBuilder sb = new StringBuilder("Current course registration: ");
if (registeredCourses.isEmpty())
sb.append(" { none }");
else {
sb.append("{ ");
boolean first = true;
for (int i : registeredCourses) {
if (first)
first = false;
else
sb.append(", ");
sb.append(choiceToCourse(i));
}
sb.append(" }");
}
System.out.println(sb);
}
}
You need to write 3 different validations in your code:
public static int ValidateChoice(int choice, int firstChoice, int secondChoice, int thirdChoice, int totalCredit) {
//Validation: Choice is in range of 1 and 7
if(choice > 7 || choice < 1){
return -1;
}
// Validation : No 2 course choices have same value
boolean isInvalid = firstChoice!=0 ?
(firstChoice == secondChoice ||firstChoice == thirdChoice):
(secondChoice!=0 && secondChoice==thirdChoice);
if(isInvalid) {
return -2;
}
// Validation : Total credits are not more than 9
else if(totalCredit > 9){
return -3;
}
else{
return 0;
}
}
One of your fellow course mate have also asked this question here,
Validating inputs in a function in java to avoid duplicate data other than non entry with default of 0 (No database )
Be careful of Plagiarism
With the parameters I was given, and only allowed to change the ValidateChoice method, I was able to take John McClane's answer and convert it to make it work. I thank you for the help. What I have done is simple and now makes sense.
Here it is:
public static int ValidateChoice(int choice, int firstChoice, int secondChoice, int thirdChoice, int totalCredit) {
// TO DO - Add Code to:
// Validate user menu selection (the int choice method argument)
// against the given registration business rules
if ((choice < 1) || (choice >7))
return -1;
if ((choice == secondChoice) || (choice == firstChoice))
return -2;
if (totalCredit >= 9)
return -3;
return 0;
}
I have a main menu class which gets a choice from the user and then uses that choice to select other classes from a switch statement pertaining to the menu options. My code is:
public static void main(String[] args) {
int dieOne = 0;
int dieTwo = 0;
int choice = 0;
DiceMaker dice = new DiceMaker(); // class that creates the dice
RollDice roll = new RollDice(); // class that imitates roll
DiceMenu menu = new DiceMenu();
DiceRoller series = new DiceRoller();
System.out.println("Welcome to the Dice Roll Stats Calculator!\n");
while (choice != 4) {
menu.DiceMenu();
choice = menu.getUserChoice();
switch (choice) {
case 1:
dice.diceMaker();
dieOne = dice.DieOne();
dieTwo = dice.DieTwo();
System.out.println(dice.DieOne() + dice.DieTwo());
return;
case 2:
roll.rollDice(dieOne, dieTwo);
roll.displayRoll();
return;
case 3:
series.diceRoller();
series.displayResults();
return;
case 4:
break;
}// switch (choice)
} // while (choice != 4)
}
Case for is the 'Exit' option, so I put the switch statement in a while loop with the boolean condition being not equal to 4 so that when the choice was set to 4 the loop would stop. The proper case executes but the problem I'm having is that the loop, and consequently the program stop after each case that I try, even if the choice was not 4. I tried using break statements after case 1, 2 and 3 as well, and when I did that, it would just repeat the case in an infinite loop. I tried to figure this out on my own cut could never find anything that resembled what I was seeing enough for me to figure out what the problem was. I'm guessing this probably isn't the best way to make a menu in the future. Thank in advance.
The rest of my code is as follows. Please note, DiceRoller class is still under construction, but DiceMaker and RollDice classes seem to be working.
DiceMenu class:
public class DiceMenu
{
public static final int CHOICE_UNKNOWN = 0;
public static final int CHOICE_MAKE_DICE = 1;
public static final int CHOICE_ROLL_ONCE = 2;
public static final int CHOICE_SERIES_ROLL = 3;
public static final int CHOICE_QUIT = 4;
private int choice = 0;
Scanner scan = new Scanner(System.in);
public int DiceMenu()
{
while ( this.choice < 1 || this.choice > 4 ) // while loop keeps choices in range
{
System.out.println(" MAIN MENU\n");
System.out.println("1. Create Your Dice");
System.out.println("2. Roll Your Dice");
System.out.println("3. Perform A Series Of Rolls And Show Stats");
System.out.println("4. Exit\n");
try // avoid invalid input
{
System.out.print("Please choose an option: ");
this.choice = scan.nextInt(); // get number of sides from user
}
catch (InputMismatchException e)
{
//if input is invalid, returns to beginning of loop
System.out.println("Invalid Input. Please try again.\n");
scan.next();
continue;
}
if ( this.choice < 1 || this.choice > 4 ) // if input is out of range
// notify user before continuing
{
System.out.println("Choice must reflect menu options. (1-4)"
+ " Please try again.\n");
this.choice = 0;
}
}//while ( this.choice < 1 || this.choice > 4 )
return 0;
}
public int getUserChoice()
{
return this.choice;
}
}
RollDice class:
public class RollDice
{
private int roll;
private int rollOne;
private int rollTwo;
private int rollTotal;
public int rollDice (int dieOne, int dieTwo)
{
this.rollOne = 1 + (int)(Math.random() * dieOne);
this.rollTwo = 1 + (int)(Math.random() * dieTwo);
this.rollTotal = this.rollOne + this.rollTwo;
return 0;
}
public void displayRoll()
{
System.out.println("You roll a " + rollOne + " and a "
+ rollTwo + " for a total of " +
rollTotal + "!"); //display separate and total
//roll amounts
if ( rollTotal == 2 ) // if/else tests for special rolls
{
System.out.println("Snake Eyes!");
}
else if ( rollTotal == 7 )
{
System.out.println("Craps!");
}
else if ( rollOne == 6 && rollTwo == 6 )
{
System.out.println("Boxcars!");
}
}
}// public class DiceRoller
DiceMaker class:
public class DiceMaker
{
private int sides = 0;
private int dieOne;
private int dieTwo;
public int diceMaker()
{
while ( sides < 4 || sides > 20 ) // while loop keeps sides within range
{
Scanner scan = new Scanner(System.in);
try // avoid invalid input
{
System.out.print("Please enter the number of sides each die "
+ "should have (must be between 4 and 20): ");
this.sides = scan.nextInt(); // get number of sides from user
}
catch (InputMismatchException e)
{
//if input is invalid, returns to beginning of loop
System.out.println("Invalid Input. Please try again.\n");
scan.next();
continue;
}
if (sides < 4 || sides > 20) // if input is out of range
// notify user before continuing
{
System.out.println("Die must have between 4 and 20 sides."
+ " Please try again.\n");
}
}//while ( sides < 4 || sides > 20 )
this.dieOne = sides;
this.dieTwo = sides;
return 0;
}
public int DieOne()
{
return this.dieOne;
}
public int DieTwo()
{
return this.dieTwo;
}
}// public class DiceMaker
Remove the return(s) from cases 1,2 and 3. If you return from main the program terminates. You want to loop so don't do that. However, as pointed out by #ajb in the comments below, you don't want the case(s) to fall through. So you need break(s).
case 1: dice.diceMaker();
dieOne = dice.DieOne();
dieTwo = dice.DieTwo();
System.out.println(dieOne + dieTwo);
// return;
break; // <-- applies to innermost block (switch).
case 2: roll.rollDice(dieOne, dieTwo);
roll.displayRoll();
// return;
break; // <-- applies to innermost block (switch).
case 3: series.diceRoller();
series.displayResults();
// return;
break; // <-- applies to innermost block (switch).
Also, you could use continue (here, which would apply to the innermost loop). Finally, remember that case 4 terminates the loop (because choice is 4) and you don't need case 4 for that reason.
I'm trying to add error handling to my java program if anything but the options and String/char are entered. I mainly need it for if a String is entered. I've tried to do the while(true) but I don't really understand that. I also added !(kb.hasNextInt()) to my line while (choice < 1 && choice > 4 ) but that didn't work either. So I just need help adding error handling to my program. Thanks!
here's my code
import java.util.*;
public class HeroesVersusMonsters
{
private static Hero hero;
private static Monster monster;
private static Random rand = new Random();
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
do
{
System.out.println("---------------------------------------");
System.out.println("\tChoose your type of hero");
System.out.println("---------------------------------------");
System.out.println("\t1. Warrior");
System.out.println("\t2. Sorceress");
System.out.println("\t3. Thief");
System.out.println("\t4. Snake");
System.out.println();
System.out.print("Choice --> ");
int choice = kb.nextInt();
kb.nextLine();
while (choice < 1 && choice > 4 )
{
System.out.println("\n" + choice + " is not an option. Please try again.");
System.out.print("Choice --> ");
choice = kb.nextInt();
kb.nextLine();
System.out.println();
}
switch (choice)
{
case 1:
hero = new Warrior();
break;
case 2:
hero = new Sorceress();
break;
case 3:
hero = new Thief();
break;
case 4:
hero = new Snake();
break;
}
switch (rand.nextInt(3))
{
case 0:
monster = new Ogre("Shrek the Ogre");
break;
case 1:
monster = new Skeleton("Bones the Skeleton");
break;
case 2:
monster = new Gremlin("Dobby the Gremlin");
break;
}
System.out.println();
System.out.println(hero.name + ", you will be fighting against " + monster.getName() + "!!!");
System.out.println();
while (hero.getHits() > 0 && monster.getHits() > 0)
{
hero.attack(monster);
monster.attack(hero);
}
System.out.print("Would you like to play again? (yes / no) ");
String play = kb.nextLine().toLowerCase();
play = play.trim();
if (play.equals("no"))
break;
else
System.out.println();
}
while (true);
}
}
Please look closly to your condition of inner while loop.
while (choice < 1 && choice > 4 )
Means loop will work until choice<1 and choice>4 remains true.
Is it exactly what you want?
I think No because what if input is 5 it is true for >4 but false for <1 what you want is you need to loop things until user enters correct input.
Am I right?
So what you need to do is just change condition like this
while(choice<1 || choice>4)
As Jared stated.
One more thing I want to suggest you don't you think you should break; external loop while user enters wrong input.(No problem)
You can do one this also.
ArrayList<Integer> ar=new ArrayList<Integer>(4);
ar.add(1);
ar.add(2);
ar.add(3);
ar.add(4);
while(true)
{
if(ar.contains(choice))
{
//Go On
}
else
{
//Print old stuff
}
}
Here is what your main method should look like:
public static void main(String ...args){
final Scanner scanner = new Scanner(System.in);
while(true){
final Hero hero = promptHero(scanner);
final Monster monster = getRandomMonster();
fight(hero, monster);
if(!playAgain(scanner))
break;
}
}
Now write the static methods promptHero, getRandomMonster, fight, and playAgain (which should return true if you want to play again).
Here is what your promptHero method should look like (to properly handle bad input):
private static Hero promptHero(final Scanner scanner){
while(true){
System.out.println("---------------------------------------");
System.out.println("\tChoose your type of hero");
System.out.println("---------------------------------------");
System.out.println("\t1. Warrior");
System.out.println("\t2. Sorceress");
System.out.println("\t3. Thief");
System.out.println("\t4. Snake");
System.out.println();
System.out.print("Choice --> ");
try{
final int choice = scanner.nextInt();
if(choice < 1 || choice > 4)
System.out.println("\n" + choice +
" is not an option. Please try again.");
else
return getHero(choice); //return the hero
} catch(InputMismatchException ime){
final String line = scanner.nextLine();// need to advance token
System.out.println("\n" + line +
" is not an option. Please try again.");
}
}
}
private static Hero getHero(final int choice){
switch (choice){
case 1:
return new Warrior();
case 2:
return new Sorceress();
case 3:
return new Thief();
case 4:
return new Snake();
}
return null;
}
You should check out the Java regex:
if(choice.toString().matches("[0-9]+"))
{
//continue
}
else
{
//error message
}