0

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);
   }
}
4
  • 3
    How can choice both be less than 1 and greater than 4? Commented Apr 14, 2014 at 2:19
  • And what are you going to do when they enter something like ad;lkfjasdf;alksdf as their choice? Commented Apr 14, 2014 at 2:20
  • The while(true) goes on forever unless you break. The breaks you have only exit the switch statements, not the do/while loop. Commented Apr 14, 2014 at 2:20
  • If you would break this up into methods, it would be a lot easier to write and debug. Commented Apr 14, 2014 at 2:38

3 Answers 3

1

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
}
}
Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

Comments

0

You should check out the Java regex:

if(choice.toString().matches("[0-9]+"))
{
      //continue
}

else
{
     //error message
}

4 Comments

int cannot be dereferenced
if(choice. toString() .equals("[0-9]+"))
you're missing the closing parenthesis, too.
the nextInt method is more than capable of catching bad input--you shouldn't be using regular expressions here (it's already done for you in the Java native library).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.