java - Ideone Java 程序运行时错误

标签 java object split runtime

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */

class time
{
    int h,m,sec;
    void getdata()throws IOException
    { /*Scanner in = new Scanner(System.in);`
      h=in.nextInt();
      m= in.nextInt();
      s=in.nextInt();*/
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String s= br.readLine();
        String str[] = s.split(" ");

        h=Integer.parseInt(str[0]);
        m=Integer.parseInt(str[1]);
        sec=Integer.parseInt(str[2]);
    }
    int calc_time(time t1,time t2)
    { return ((t2.h - t1.h)*3600 + (t2.m - t1.m)*60 + (t2.sec - t1.sec));
    }
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        time t = new time();
        t.getdata();
        time te = new time();
        te.getdata();
        time tt = new time();
        int val = tt.calc_time(t,te);
        if(val>=0&&val<=99) System.out.println("S");
        else if(val>99&&val<=199) System.out.println("C");
        else if(val>199 && val<=299) System.out.println("S");
        else if(val>299 && val<=399) System.out.println("C");

    }
}

尽管这个特定程序在我的电脑上运行良好,但我在 Ideone 上遇到了运行时错误。 它指示第二个对象的 split 函数和 getdata() 函数调用出现错误。

最佳答案

http://ideone.com/qpOO9R

已到达 STDIN 流的末尾,这意味着运行以下命令后:

  String s = br.readLine();

s 仍然为 null,这会导致以下行出现 NPE:

String str[] = s.split(" ");

要解决此问题,请检查 null 并执行一些合理的操作,并提供一些输入供 Ideone 使用。此外,您的 BufferedReader 每次执行时只应创建一次,如以下 ideone 草图所示:http://ideone.com/VtQrxk

相关javadoc:

public String readLine() throws IOException

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

Returns:

A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine()

关于java - Ideone Java 程序运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20780972/

相关文章:

arrays - 将 char[] 与逗号分开

regex - 批处理 : how to split string on uppercase letter

java.lang.IllegalStateException : InputStream has already been read - do not use InputStreamResource if a stream needs to be read multiple times 错误

Java 对象类 MYSTERY

java - 平滑移动 LibGdx

javascript - Shadowbox 永远不会激活;链接只能正常使用

javascript - 将 JS 对象与 HTML ID 相关联

string - 在批处理文件中最后一个分隔符实例之后提取字符串

java - 如何在 Struts 2 表单页面上添加 CSS

java - Android - 布局性能 : Programmatic vs XML