gpt4 book ai didi

java - 错误 : Exception in thread "main" java. lang.NullPointerException

转载 作者:行者123 更新时间:2023-11-30 03:20:55 25 4
gpt4 key购买 nike

我的代码出现此错误。

这是我的代码:

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 在 car.main(car.java:10)

最佳答案

您已经定义了 Scanner 对象。使用 Scanner 对象的实例并设置 model 的值。您可以尝试 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

关于java - 错误 : Exception in thread "main" java. lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31355767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com