我在运行这个的时候会抛出NullPointerException。。
run:
Ints:
* Has 2? true
* Has 7? false
Strings:
* Has one? true
* Has One? false
Exception in thread "main" java.lang.NullPointerException
at Application.main(Application.java:32)
Java Result: 1
我只知道问题出在这个地方
Item[] cart = new Item[1];
cart[0].name = "Banana";
cart[0].price = 1.00;
该如何解决呢?不能修改Application,只能在我的自定义类里添加代码。
(表达可能不是太准确。。我还搞不清楚这些东西学名叫什么。。)
以下是代码:
public class Application {
public static <T> boolean contains(T key, T[] array) {
return Arrays.asList(array).contains(key);
}
public static void main(String[] args){
Integer[] ints = {1, 2, 3};
System.out.println("Ints:");
System.out.printf(" * Has 2? %b%n", contains(2, ints));
System.out.printf(" * Has 7? %b%n", contains(7, ints));
System.out.println();
String[] words = {"one", "two", "three"};
System.out.println("Strings:");
System.out.printf(" * Has one? %b%n", contains("one", words));
System.out.printf(" * Has One? %b%n", contains("One", words));
System.out.println();
//
Item[] cart = new Item[1];
cart[0].name = "Banana";
cart[0].price = 1.00;
//
Item banana1 = new Item();
banana1.name = "Banana";
banana1.price = 1.00;
//
Item banana2 = new Item();
banana2.name = "Premium Banana";
banana2.price = 2.00;
//
Item banana3 = new Item();
banana3.name = "Banana";
banana3.price = 1.25;
//
System.out.println("Items:"); //true, false, false
System.out.printf(" * Has 1st? %b%n", contains(banana1, cart));
System.out.printf(" * Has 2nd? %b%n", contains(banana2, cart));
System.out.printf(" * Has 3rd? %b%n", contains(banana3, cart));
}
}
public class Item {
public String name;
public double price;
public Item(){
name = "";
price = 0.0;