【发布时间】:2017-10-19 19:52:24
【问题描述】:
请帮助找出 IntelliJ 给出 NullPointerException 的原因。
线程“main”中的异常 java.lang.NullPointerException at ex3.Horse.about(Horse.java:16) 在 ex3.Horse.ride(Horse.java:21) 在 ex3.Hippodrome.main(Hippodrome.java:19)
类马:
package ex3;
public class Horse {
String name;
int speed;
String color;
Boolean isMale;
int age;
void eat(){
System.out.println("eating ... ");
}
void about(){
String sex = (isMale) ? "Male" : "Female"; // тернарный оператор
System.out.printf("name: %s, age: %d, sex: %s", name, age, sex);
}
void ride(){
about();
System.out.println("riding at speed: " + speed);
}
}
类竞技场:
package ex3;
import java.util.Random;
public class Hippodrome {
public static void main(String[] args) {
Horse[] horses = new Horse[10];
Random random = new Random();
for (int i = 0; i < horses.length; i++) {
horses[i] = new Horse();
horses[i].name = "Kon " + i;
horses[i].age = 1 + random.nextInt(10);
}
for (Horse horse : horses) {
horse.ride();
}
}
}
【问题讨论】:
-
@JuanCarlosMendoza 我想他知道它是什么,问题在于它发生在哪里:p
-
@ACVM 正确:p
标签: java exception nullpointerexception