【问题标题】:Try/Catch exception so i can return an array value and print out an exception?尝试/捕获异常,以便我可以返回一个数组值并打印出一个异常?
【发布时间】:2013-01-21 09:23:45
【问题描述】:

您好,我正在编写一个彩票方法,用户必须输入两个数字 n 和 k 作为参数。彩票被一个随机队列填满,该队列最多为 k。因此,如果我输入 k=10,则队列将容纳 1、2、3、4、5、6、7、8、9、10。参数 n 是必须随机删除的项目数。所以如果我选择 3 那么它可以返回 4,6,8 或者它可以是 1,3,10。

现在如果 n 大于 k,它必须抛出一个错误,说明队列中没有足够的项目可以拉取。因此,如果我输入 n=5 和 k=3,队列中仍有 3 个项目,但我无法从队列中选择 5,因为这太多了。

现在我的问题是我必须返回仍在队列中的项目。所以 n=5 和 k=3 将返回 1,3,2 或 2,3,1 等等。但是我必须在返回该数组后打印一个异常。到目前为止,我能够返回数组,但我无法让 try catch 异常工作。是否有另一种方法我可以尝试返回数组,然后打印出异常,所以它看起来像这样:

%java Lottery 5 2 //calls the method with the arguments n=5 k=2
2  1    //still prints the items in the queue
java.lang.Exception: Not enough items in your queue. // returns the error as well
at Lottery.pickNumbers(Lottery.java:29) //dont pay attention to these line numbers, this was a test case given to us
at Lottery.main(Lottery.java:56)

这是我的代码:

import java.util.*;
import java.math.*;
public class Lottery{
    RandomizedQueue rq;
    Random Rnum = new Random();
    int [] Larray;

    // constructs a Lottery class
    public Lottery(){
    }


    // picks the numbers and store them in an array of integers
    // int n: number of items to pick
    // int k: maximum integer to be picked

   public int [] pickNumbers(int n, int k) throws Exception{

        rq = new RandomizedQueue();

        int [] remainQueue = new int [k];


        if(n>k) 
        {
            for(int i=1; i<=remainQueue.length;i++)
            {
                rq.enqueue(i);
            }
                for(int i=0; i<remainQueue.length;i++)
                {
                    remainQueue[i] = rq.dequeue();
                }
                return remainQueue; 
        }  





        for(int i =1;i<=k;i++)
        {
            rq.enqueue(i);
        }

        Larray = new int[n];
        for(int i = 0;i< Larray.length;i++)
        {
            Larray[i] = rq.dequeue();
        }

        return Larray;


    }



    // Do not change main().
    public static void main(String [] args) throws Exception{
        if (args.length<2){
           System.out.println("Please enter your input values.");
           System.out.println("e.g. java Lottery [number of integers to pick] [Maximum integer to be picked]");
       }else{
           int n = Integer.parseInt(args[0]);
           int k = Integer.parseInt(args[1]);
           Lottery l = new Lottery();
           try{
           int [] picked = l.pickNumbers(n,k);
           for (int i = 0; i< picked.length; i++){
               System.out.print(picked[i]+" ");
           }
           System.out.println();
           }catch (Exception e){
           e.printStackTrace();
           }
       }



    } 

}

【问题讨论】:

  • 您只想打印异常消息或完整堆栈跟踪。

标签: java arrays exception try-catch


【解决方案1】:

为此,您需要创建自己的自定义异常。 按照步骤。 -> 创建一个扩展异常的类 -> 编写自己的异常和处理 说,

public class MyException extends Exception {
// special exception code goes here
}

把它当作:

throw new MyException ("Something happened")

Catch as:

catch (MyException e)
{
// something
}

在你的情况下 如果(n

【讨论】:

    【解决方案2】:

    更改您的主要方法,如下面的代码。在没有异常的情况下,您将按预期获得 Result,如果出现异常,则会获取先前填充的 Array 并显示它。通过这种方式,您将获得填充结果和异常。

    import java.util.*;
    import java.math.*;
    public class Lottery{
        RandomizedQueue rq;
        Random Rnum = new Random();
        int [] Larray;
    
        // constructs a Lottery class
        public Lottery(){
        }
    
    
        // picks the numbers and store them in an array of integers
        // int n: number of items to pick
        // int k: maximum integer to be picked
    
       public int [] pickNumbers(int n, int k) throws Exception{
    
            rq = new RandomizedQueue();
    
            int [] remainQueue = new int [k];
    
    
            if(n>k) 
            {
                for(int i=1; i<=remainQueue.length;i++)
                {
                    rq.enqueue(i);
                }
                    for(int i=0; i<remainQueue.length;i++)
                    {
                        remainQueue[i] = rq.dequeue();
                    }
                    return remainQueue; 
            }  
    
    
    
    
    
            for(int i =1;i<=k;i++)
            {
                rq.enqueue(i);
            }
    
            Larray = new int[n];
            for(int i = 0;i< Larray.length;i++)
            {
                Larray[i] = rq.dequeue();
            }
    
            return Larray;
    
    
        }
    
    
    
        // Do not change main().
        public static void main(String [] args) throws Exception{
            if (args.length<2){
               System.out.println("Please enter your input values.");
               System.out.println("e.g. java Lottery [number of integers to pick] [Maximum integer to be picked]");
           }else{
               int n = Integer.parseInt(args[0]);
               int k = Integer.parseInt(args[1]);
               Lottery l = new Lottery();
               try{
               int [] picked = l.pickNumbers(n,k);
               for (int i = 0; i< picked.length; i++){
                   System.out.print(picked[i]+" ");
               }
               System.out.println();
               }catch (Exception e){
                   int [] picked = l.Larray;
                   for (int i = 0; i< picked.length; i++){
                       System.out.print(picked[i]+" ");
                   }
                   System.out.println();
    
    
               e.printStackTrace();
               }
           }
    
    
    
        } 
    
    }
    

    【讨论】:

      【解决方案3】:

      你不能。这样做甚至没有意义。异常用于异常行为。据我了解,要求比队列中更多的项目是预期的行为(即,您有一个用例说“返回剩余的队列”。因此,如果您想处理错误,您应该简单地执行类似的操作。

      if (picked.length != k)
      {
        System.out.println("You are attempting to choose more numbers than there are items (left) in the pool");
      }
      

      或者,由于您预先知道值 n 和 K,您可以简单地进行一些输入验证

      if (k>n)
      {
        System.out.println("The amount of available numbers is smaller than the amount of numbers you wish to draw.")
      }
      

      此外,您可能应该使用 Set 而不是 Array。

      【讨论】:

        【解决方案4】:

        我会这样做。完整的工作代码:

        import java.util.ArrayList;
        import java.util.List;
        import java.util.Random;
        
        public class Lottery {
            public void pickNumbers (int n, int k, List<Integer> values)
                throws Exception
            {
                RandomizedQueue <Integer> rq = new RandomizedQueue <Integer> ();
        
                for (int i = 0; i < k; i++)
                    rq.enqueue (i);
        
                if (n <= k)
                {
                    for (int i = 0; i < n; i++)
                        values.add (rq.dequeue ());
                }
                else
                {
                    for (int i = 0; i < k; i++)
                        values.add (rq.dequeue ());
        
                    throw new Exception ("N > K");
                }
            }
        
            public static void main (String [] args)
            {
                int n = Integer.parseInt (args [0]);
                int k = Integer.parseInt (args [1]);
                Lottery l = new Lottery ();
                List <Integer> picked = new ArrayList <Integer> (n);
                try
                {
                    l.pickNumbers (n, k, picked);
                } 
                catch (Exception e)
                {
                    e.printStackTrace();
                }
        
                for (int i = 0; i < picked.size (); i++){
                    System.out.print (picked.get (i) + " ");
                }
                System.out.println();
            }
        
            private static class RandomizedQueue <T> extends ArrayList <T>
            {
                private final Random r = new Random ();
        
                public void enqueue (T x)
                {
                    add (x);
                }
        
                public T dequeue ()
                {
                    return remove (r.nextInt(size ()));
                }
            }
        }
        

        【讨论】:

          【解决方案5】:

          试试这个方法:

          1. main()中创建一个列表
          2. 将该列表传递给pickNumbers()
          3. 使pickNumbers() 返回void 并将结果添加到列表中。
          4. 遇到错误时,抛出异常
          5. main() 中,捕获异常。然后该列表将包含迄今为止计算的所有结果。

          或者,编写您自己的异常,接受现有结果作为参数。 main() 然后可以从异常中读取它们。

          【讨论】:

          • 我认为即使从方法中抛出异常,也不要依赖更改传递的参数是一种好习惯。
          • @SpaceTrucker:我同意,但 Java 没有提供很多其他选项,我可以用几句话来解释。
          【解决方案6】:

          你可以从方法中返回 throw Exception 的值,两者不能同时完成。

          您可以创建自定义 Exception 类,并在其中保存处理结果并在出现异常时抛出该结果。

          public class MyException extends Exception{
               private int[] processedResult;
               public MyException(String str,int[] result){
                  this.processedResult = result;
               }
               ...
               @override
               public String toString(){
                 ....
               }
          } 
          

          ...

          public int [] pickNumbers(int n, int k) throws MyException{
              int[] larray = new int[n];
              try{
                 ...
              }catch(Exception ex){
                  new MyException("...",larray );
              }
          }
          

          【讨论】:

            【解决方案7】:
            • 您可以创建自己的 Exception 类型,它会覆盖 setMessage

            • 或者简单的而不是e.printStackTrace()使用e.getMessage()

            【讨论】:

              【解决方案8】:

              你不能同时抛出异常和返回值。

              退后一步,看看您想要实现的目标。您需要从您的方法中返回多个值 - 一个数字列表和一个状态 - 这会建议我返回一个包含这些值的复杂对象,而不是简单的 int[]

              public class LotteryPick {
                  public int status;
                  public int[] numbers;
              }
              
              public LotteryPick pickNumbers(int n, int k) {
              ...
              }
              

              实际上,我会为numbers 使用Set&lt;Integer&gt;,为status 使用枚举,并且可能为字段使用getter/setter。

              或者,如果您必须抛出异常,请创建一个自定义异常类 (... extends IllegalArgumentException ?),该类还有一个 int[] 字段来保存选取的数字。不过我不推荐这种方法,无论如何它在功能上都等同于上述方法。

              【讨论】:

                猜你喜欢
                • 2010-10-03
                • 2019-09-30
                • 1970-01-01
                • 2014-07-25
                • 2011-11-28
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多