我的代码中的java.lang.NullPointerException

时间:2015-09-09 06:17:33

标签: java

  

线程中的异常" main" lab2.Test.main上的java.lang.NullPointerException(Test.java:23)

package lab2;

import java.io.Console;

public class Test {

    public static void main(String []args) {

        Console cnsl = null;
        String  payload = null;



        // creates a console object
        cnsl = System.console();

        // read line from the user input
        its a run time error , it shows the null exception 

        payload = cnsl.readLine("Enter weight of the payload in lb: ");

        // prints

        pay = Float.parseFloat(payload);;

从用户输入读取行             double hello =((8 * pay * POUNDINKILO * ACCELERATION_GRAVITY)/(PI * ROWDENSITY * 0.75 * VOLUME * VOLUME));

        D = Math.sqrt(hello);

        System.out.println("For a payload of : " + payload);
        System.out.println("\nFor a payload of : " + payload);

        System.out.println("Radius is : " + D);
    }
}

3 个答案:

答案 0 :(得分:1)

payload = cnsl.readLine("Enter weight of the payload in lb: ");

这取决于您的环境。

你可以试试这个。

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
         System.out.print("Enter weight of the payload in lb: ");
         String s = br.readLine();

答案 1 :(得分:0)

而不是

cnsl = System.console();
payload = cnsl.readLine("Enter weight of the payload in lb: ");

使用java.util.Scanner之类的

Scanner in = new Scanner(System.in);
System.out.println(("Enter weight of the payload in lb: "));
payload = in.nextLine();

以下是使用扫描仪的完整程序

import java.util.Scanner;
public class Test{

public static void main(String[] args) {
    String payload = null;
    final double ACCELERATION_GRAVITY = 9.81;
    final double PI = 3.14;
    final double ROWDENSITY = 1.22;
    final int VOLUME = 3;
    final double POUNDINKILO = 0.453592;
    double D;
    double pay;

    Scanner in = new Scanner(System.in);

    System.out.println(("Enter weight of the payload in lb: "));
    payload = in.nextLine();

    pay = Float.parseFloat(payload);

    double hello = ((8 * pay * POUNDINKILO * ACCELERATION_GRAVITY) / (PI
            * ROWDENSITY * 0.75 * VOLUME * VOLUME));

    D = Math.sqrt(hello);

    System.out.println("For a payload of : " + payload);
    System.out.println("\nFor a payload of : " + payload);
    System.out.println("Radius is : " + D);
    }
}

答案 2 :(得分:0)

Java docs说,

  

如果此虚拟机具有控制台,则它由此类的唯一实例表示,可以通过调用System.console()方法获取该实例。如果没有可用的控制台设备,那么该方法的调用将返回null。

在IDE上运行代码时通常就是这种情况。

我现在该怎么办? 查看Scanner中的java.util课程。有关此here

的更多信息