我的程序允许用户更改汽车的品牌。我想制作一组2辆车。我使用Car[] driving = new Car[2]
声明了一个数组。然后在构造函数中创建对象driving[0] = new Car()
和driving[1] = new Car()
。我不确定这是否是正确的方法,因为运行我的程序会给我一个NullPointerException。
驱动程序类:
import java.util.Scanner;
public class Driver
{
static Scanner sc = new Scanner(System.in);
static int choice;
static Car[] driving = new Car[2];
public Driver(){
driving[0] = new Car();
driving[1] = new Car();
}
public static void main(String args[]){
changeSettings();
}
static public void changeSettings(){
System.out.println("Enter the make");
driving[0].setMake(sc.nextLine());
System.out.println("Done.");
}
}
汽车类:
public class Car
{
private String make;
public Car(){
make = "Mercedes";
}
public String getMake(){
return make;
}
public void setMake(String make){
this.make = make;
}
}
错误讯息:
java.lang.NullPointerException
at Driver.changeSettings(Driver.java:23)
at Driver.main(Driver.java:18)
看起来错误在第18行和第23行,但我想不出解决方案。我的方法是让汽车对象可以接受吗?
答案 0 :(得分:4)
您在不调用Driver构造函数的情况下调用changeSettings方法。但是你的主要问题来自混合静态代码和非静态代码。
例如:
import java.util.Scanner;
public class Driver
{
// static Scanner sc = new Scanner(System.in);
// static int choice;
// static Car[] driving = new Car[2];
private Car[] driving = new Car[2];
public Driver(){
driving[0] = new Car();
driving[1] = new Car();
}
public static void main(String args[]){
Driver driver = new Driver();
driver.changeSettings();
}
public void changeSettings(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the make");
driving[0].setMake(sc.nextLine());
System.out.println("Done.");
}
}