Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
错误:线程“中出现异常”;“主要”;java.lang.NullPointerException_Java_Exception_Nullpointerexception_Main - Fatal编程技术网

错误:线程“中出现异常”;“主要”;java.lang.NullPointerException

错误:线程“中出现异常”;“主要”;java.lang.NullPointerException,java,exception,nullpointerexception,main,Java,Exception,Nullpointerexception,Main,我的代码中出现了这个错误 这是我的密码: 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 =

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

这是我的密码:

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.lang.NullPointerException中输入model:Exception
在car.main(car.java:10)

中,这似乎是空的:

System.console()
因此,对其调用readLine()意味着对null调用方法

您可能希望在System.in上使用扫描仪来代替I/O。

System.console()可以返回null。看

当您通过IDE运行java程序时,console将不可用,在这种情况下,
System.console()
返回
null
。从termainl运行java程序时,
System.console()
不会返回
null


因此,最好的做法是检查您已定义的扫描仪对象是否为空。使用Scanner对象的实例并设置模型的值。您可以尝试v.next()而不是执行System.console()

输出:

Enter model: GL
Car phone: W
Full or installment: Cost: 40000.0

以下行有问题:

model = System.console().readLine(); 
在调用readLine()时,System.console()为空-因此您会得到一个NullPointerException。您只需使用Scanner.nextLine()方法,即将此行替换为:

model = v.nextLine();

答案解释了问题的原因,但可以通过向用户提供一些关于如何解决问题的指导来扩展…非常感谢!model=v.next();工作。但是我没有得到我想要的输出,但是我现在可以处理它了。谢谢,谢谢!!
model = v.nextLine();