2015-10-18 70 views
-3

我想解决本网站上的问题:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=979。但我的代码的一部分引发运行时错误:Java 1.7运行时错误

class Main { 

static String ReadLn (int maxLg) // utility function to read from stdin 
{ 
    byte lin[] = new byte [maxLg]; 
    int lg = 0, car = -1; 
    String line = ""; 

    try 
    { 
     while (lg < maxLg) 
     { 
      car = System.in.read(); 
      if ((car < 0) || (car == '\n')) break; 
      lin [lg++] += car; 
     } 
    } 
    catch (IOException e) 
    { 
     return (null); 
    } 

    if ((car < 0) && (lg == 0)) return (null); // eof 
    return (new String (lin, 0, lg)); 
} 

public static void main(String[] args){ 
    Main jollyJumper = new Main(); 
    jollyJumper.start(); 
} 

public void start(){ 

    String input; 
    while((input = ReadLn(3000)) != null){ 
     System.out.println(answer(input)); 
    } 
} 

public String answer(String line){ 
    // The error comes from this function !!! 
    String[] items = line.split(" "); 
    int[] array; 
    try { 
     array = new int[items.length - 1]; 
    } 
    catch(NegativeArraySizeException e){ 
     return "Not jolly"; 
    } 

    for(int i = 0; i < array.length; i++){ 
     array[i] = Integer.parseInt(items[i +1]); 
    } 
    return "Jolly"; 

} 
} 

但判断系统不会告诉我哪里是错误,并在我的电脑上一切工作正常。有任何想法吗?

+1

请告诉我们堆栈跟踪 – user

+0

没有足够的代码来告诉你程序在哪里出错。它会很容易崩溃。请提供isJolly()。 – laune

+0

@user:该站点的在线判断系统不提供堆栈跟踪,它实际上只提供字符串“运行时错误”。 –

回答

1

这段代码崩溃的一个简单原因将是一行中包含多个空格的输入行。通过修剪阵列并分割一系列空白字符来防止这种情况发生。

String[] items = line.split("\\s+").trim(); 

由于它是,两个空间连续产生转换误差:

java.lang.NumberFormatException: For input string: "" 

编辑在Q.实质性编辑

另一个错误后(根据规格)正在使用

byte[3000] 

用于读取行tha t可以包含一个计数和多达3000个整数。即使只有一半的整数必然要求超过3000个字符或字节。只需使用扫描仪。

最后方法answer没有解决问题。它只是转换数字,但需要的处理 - 检查连续的数字相差不超过一个限制,从1到极限的所有值都存在 - 没有完成。