当前位置: 首页 > 知识库问答 >
问题:

错误:线程“main”java中出现异常。lang.NullPointerException

卫嘉谊
2023-03-14

我的代码中出现了这个错误。

这是我的代码:

import java.util.*;
public class car{
public static void main(String[]args) throws java.io.IOException{
Scanner v = new Scanner(System.in);

String model = new String(); 
double cost=0;

System.out.print("Enter model: ");
model = System.console().readLine();

if(model == "GL"){
    cost = 420000;
    }

if (model == "XL"){
    cost = 3398000;
    }






System.out.print("Car phone: ");
char phone = (char)System.in.read();

if(phone == 'W'){
cost = cost + 40000;
}

System.out.print("Full or installment: ");
char paid = (char)System.in.read();

if(paid == 'F'){
cost = cost - 0.15 * cost;
}

System.out.print("Cost: " + cost); 

}
}

这就是结果。错误:在线程“main”java中输入model:Exception。lang.NullPointerException在汽车上。主(车.java:10)

共有3个答案

柳威
2023-03-14

这似乎是空的:

System.console()

所以在它上面调用readLine()意味着在null上调用一个方法。

您可能需要在系统上使用扫描仪。相反,对于I/O。

江展
2023-03-14

问题在于以下行:

model = System.console().readLine(); 

在调用readLine()时,系统。console()为null-因此您会得到NullPointerException。你所需要做的就是使用扫描仪。nextLine()方法,即将此行替换为:

model = v.nextLine();
沈树
2023-03-14

您已经定义了Scanner对象。使用Scanner对象的实例并设置模型的值。您可以尝试v.next(),而不是执行System.console()

import java.util.*;

public class car {
    public static void main(String[] args) throws java.io.IOException {
        Scanner v = new Scanner(System.in);

        String model = new String();
        double cost = 0;

        System.out.print("Enter model: ");
        //model = System.console().readLine();
        model = v.next();

        if (model == "GL") {
            cost = 420000;
        }

        if (model == "XL") {
            cost = 3398000;
        }

        System.out.print("Car phone: ");
        char phone = (char) System.in.read();

        if (phone == 'W') {
            cost = cost + 40000;
        }

        System.out.print("Full or installment: ");
        char paid = (char) System.in.read();

        if (paid == 'F') {
            cost = cost - 0.15 * cost;
        }

        System.out.print("Cost: " + cost);

    }
}

输出:

Enter model: GL
Car phone: W
Full or installment: Cost: 40000.0
 类似资料: