简体   繁体   English

用字符串Java处理错误

[英]Error handling with strings java

I'm trying to add error handling to my java program if anything but the options and String/char are entered. 我正在尝试将错误处理添加到我的Java程序中,除非输入了选项和字符串/字符。 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. 我试图做while(true),但是我不太明白。 I also added !(kb.hasNextInt()) to my line while (choice < 1 && choice > 4 ) but that didn't work either. 我还把!(kb.hasNextInt())添加到了我的代码行中(choice <1 && choice> 4),但这也不起作用。 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循环情况。

 while (choice < 1 && choice > 4 )

Means loop will work until choice<1 and choice>4 remains true. 均值循环将一直有效,直到choice <1 choice> 4保持为真。

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. 我认为不可以,因为如果输入为5, 对于> 4true,对于<1为false,那么您想要的是,您需要循环操作直到用户输入正确的输入。

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; 我想告诉你的另一件事是,你不认为自己应该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
}
}

You should check out the Java regex: 您应该查看Java正则表达式:

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

else
{
     //error message
}

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). 现在,编写静态方法promptHerogetRandomMonsterfightplayAgain (如果要再次播放,则应返回true )。

Here is what your promptHero method should look like (to properly handle bad input): 这是您的promptHero方法的外观(正确处理错误的输入):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM