日期:2014-05-20 浏览次数:20820 次
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;
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;