尝试捕获异常时程序崩溃

时间:2016-10-29 06:04:26

标签: java

我试图制作一个方法,让用户输入6个数字并将它们添加到树的整数集中。我试图尝试并捕获异常,因此如果用户不小心输入了一封信,它会抓住异常并要求他们输入一个号码。现在,当您尝试输入一封信时,程序崩溃了。它会打印出来"无效"然后崩溃了。我不知道最近发生了什么。谁能提供一些见解?

public static Set<Integer> getTicket()
{
    int userInput;
    TreeSet<Integer> getNumbers = new TreeSet<Integer>();
    Scanner input = new Scanner(System.in);
    System.out.println("Enter your 6 numbers between 1-40: ");
    for (int i = 0; i<6 ; i++)
    {
        try
        {
            System.out.print(i+1 + ": ");
            userInput = input.nextInt();
        }
        catch (InputMismatchException e)
        {
            System.out.println("Invalid");
            userInput = input.nextInt();
        }
    getNumbers.add(userInput);
    }
    System.out.println("Your ticket was: " + getNumbers);
    return getNumbers;
}

2 个答案:

答案 0 :(得分:0)

关于一些变化的几点说明。从你的原始代码中,我注意到的一件事并不是真正的错误,而是一个令人头疼的问题。您的两种方法(getWinning Numbers()getTicket())都返回了Set<integer>集,但是您没有在main中使用它。所以我只是从方法中获取输出并将它们放在main方法中,它们应该是恕我直言。像这样的方法应该做一件事,在这种情况下返回一组整数。没有印刷或其他任何事情。

我更改了getTicket()方法中的逻辑。我只是设置了一个循环,直到你有6个有效数字。在该循环内部,我使用try语句来清除无效输入。 try语句的设置方式是您可以实现此目标的众多方法之一。正如您可以看到tryguess = Integer.parseInt(userInput);)之后的语句,可能会弹出无效输入问题并抛出NumberFormatException。如果输入无效,则立即删除我们输出消息的catch并继续。如果输入有效,那么我们只需检查重复项和数字的范围。如果数字正常,则将其添加到pickedNumbers并增加numberCount。

public class Lottery
{
   public static Set<Integer> generateWinningNumbers()
   {
      Random rndNumbers = new Random();   
      TreeSet<Integer> winningNumbers = new TreeSet<Integer>();
      int max = 40;
      int min = 1;
      int range;
      int sixNum;

      for (int i = 0; i < 6; i++)
      {
        range = max - min + 1;
        sixNum = rndNumbers.nextInt(range) + min;

        while (winningNumbers.contains(sixNum))
        {
          sixNum = rndNumbers.nextInt(range) + min;
        }
        winningNumbers.add(sixNum);
      }
      return winningNumbers;
    }


   public static Set<Integer> getTicket(Scanner input)
   {
     String userInput;
     int guess;
     TreeSet<Integer> pickedNumbers = new TreeSet<Integer>();
     System.out.println("Enter your 6 numbers between 1-40: ");
     int numberCount = 1;
     while(numberCount < 7)
     {
       System.out.print(numberCount +  ": ");
       userInput = input.nextLine();
       try
       {
          guess = Integer.parseInt(userInput); 
          if( guess > 0 && guess < 41 && (!pickedNumbers.contains(guess)) )
          {
             pickedNumbers.add(guess);
             numberCount++;
          }
          else
          {
            if (pickedNumbers.contains(guess))
            {
              System.out.println("Number already picked: " + guess);
            }
            else
            {
               System.out.println("Invalid number. Pick a number between 1-40: " + guess);
            }
          }
        }
        catch (NumberFormatException e)
        {
          // bad input  
          System.out.println("Invalid input: " + userInput);
        }
    }
    return pickedNumbers;
  }
}

Main中的更改现在利用为我们返回Set整数的方法。我们创建了两个Set<Integer>变量(winningTicketuserTicket)然后我们只是从方法中获取返回的集合并输出结果,而不是从方法中打印结果。

public static void main(String[] args) throws IOException
{
  Scanner userInput = new Scanner(System.in);
  boolean done = false;
  String yesNo;
  Set<Integer> winningTicket;
  Set<Integer> userTicket;
  while(!done)
  {
    winningTicket = Lottery.generateWinningNumbers();
    userTicket = Lottery.getTicket(userInput);
    System.out.println("Your ticket was: " + userTicket);
    System.out.println("Winning Numbers: " + winningTicket);
    System.out.print("\nWould you like to try again? ");
    yesNo = userInput.nextLine();
    if(!yesNo.equalsIgnoreCase("y"))
    {
       System.out.println("Done");
       done = true;
    }
 }
 userInput.close();
}   

希望这有帮助

答案 1 :(得分:-1)

这是因为你没有在cath块内捕获异常。 for循环在这里看起来不太好,尝试时:

public static Set<Integer> getTicket()
{
    int userInput;
    TreeSet<Integer> getNumbers = new TreeSet<Integer>();
    Scanner input = new Scanner(System.in);
    System.out.println("Enter your 6 numbers between 1-40: ");
     int correct = 0;
    while(correct < 6)
    {
        try
        {
            System.out.print((correct+1) + ": ");
            userInput = input.nextInt();
            getNumbers.add(userInput);
            correct++;
        }
        catch (InputMismatchException e)
        {
            System.out.println("Invalid input");
        }
    }
    System.out.println("Your ticket was: " + getNumbers);
    return getNumbers;
}

另外,你不能打印那么简单的收藏品:

System.out.println("Your ticket was: " + getNumbers);

你可以做的是使用流:

System.out.println("Your ticket was: " + getNumbers.stream().map(Object::toString).collect(Collectors.joining(" ")));