【问题标题】:Java exit code: 137 and nothing printedJava退出代码:137并且没有打印
【发布时间】:2014-05-07 20:39:41
【问题描述】:

我下面的代码应该打印 int 'numComb'。但是,事实并非如此。当我运行它时,在我停止程序之前什么都没有发生,然后正确的答案出现在“退出代码:137”中。我读过 137 意味着它可能是 JVM 的问题。但是,我也知道它可能是其他事情的结果,所以我想知道它在我的代码中的原因,以及它是否与它有任何关系,而不是打印答案。那可能是JVM错误。谢谢你,山姆。

代码:

public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int o = 0;
        int numRem = 0;
        int numLim = 0;
        while((sc.hasNextInt())&&(o<1)) {
            int numT = sc.nextInt();
            numLim = sc.nextInt();
            numRem = sc.nextInt();
            o++;
        }
        List<Integer> persons = new ArrayList<Integer>();
        int nextPer;
        while(sc.hasNextInt()){
            nextPer = sc.nextInt();
            if(nextPer<=numLim) {
                persons.add(nextPer);
            }
        }
        int ns = persons.size();

        int numComb = (factorial(ns)) / ((factorial(numRem)) * (factorial(ns - numRem)));//replace with '1' in reply to comment
        System.out.println(numComb);
        System.exit(0);
    }
    public static int factorial(int n) {
        int f = 1;
        for (int i = 1; i <= n; i++) {
            f *= i;
        }
        return f;
    }

这是整个程序,因为我是在评论中要求的。另外,我的测试输入是:

3 2 2 1 2 3

【问题讨论】:

  • 我的假设是您的扫描仪正在以某种方式耗尽您的所有系统资源......
  • 有趣,你认为是什么原因造成的。
  • 使用调试器找出它在哪一行停止,这可能是您的机器独有的。
  • 在上述代码的第 2、3、4 行之后失败。我会尝试添加一个 hasextInt() 方法。
  • 当我尝试添加 if 语句以检查第 2、3、4 行中的每一行的下一个 int 时,这不起作用。

标签: java jvm exit-code


【解决方案1】:

你的错误可能在这里:

    int o = 0;
    int numRem = 0;
    int numLim = 0;
    while((sc.hasNextInt())&&(o<1)) {
  ----> int numT = sc.nextInt();  // You are re-declaring numT
        numLim = sc.nextInt();
        numRem = sc.nextInt();
        o++;
    }

您可以通过在适当的情况下添加更多空白来避免此类编码错误。

例如,我会以这种格式编写您的代码:

int o =         0;
int numRem =    0;
int numLim =    0;

while( sc.hasNextInt() && (o < 1) )
{
    int numT =  sc.nextInt();
    numLim =    sc.nextInt();
    numRem =    sc.nextInt();

    o++;
}

通过遵循编码风格/指南,不仅可以让您自己更轻松地阅读代码,也可以让其他人更轻松地阅读代码。

【讨论】:

  • 我尝试在外部声明它并进行修改,但结果相同。
  • 我的意思是你不需要它。 sc.nextInt() 将数字分配给下一个使用的变量。我想这将改变程序的运行方式。我对3 2 2 1 2 3 的输入导致numLine == 2,而不是3。
  • 我不完全确定你的意思。很抱歉,您能否尝试解释一下我能做什么以及它为什么会起作用。
  • 尝试注释掉int numT = sc.nextInt();这一行,或者如果它不会被使用就删除它。您正在做的是将3 2 2 1 2 3 序列中的一个值添加到numT 变量中,然后它永远不会被使用。
  • 即使不使用它,我也需要将其丢弃,因为以下整数具有它们自己的含义,正如您在我的代码中看到的那样。另外,感谢您的提示。我已经把它带到船上了。 :)
猜你喜欢
  • 2018-02-27
  • 1970-01-01
  • 1970-01-01
  • 2020-04-30
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 2019-06-06
  • 1970-01-01
相关资源
最近更新 更多