+ -
当前位置:首页 → 问答吧 → ArrayList的问题

ArrayList的问题

时间:2011-11-27

来源:互联网

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
public class test2 {
  @SuppressWarnings(value={"unchecked"}) public static void main(String[] args) { System.out.println("欢迎光临光复餐厅,本餐厅已开始营业"); System.out.println("今天天气:阳光普照"); ArrayList<Customer> customerList = new ArrayList<Customer>();
    ArrayList pricea = new ArrayList();
    ArrayList priceb = new ArrayList();
    ArrayList passtime = new ArrayList();
    int x = 0;
    int y = 0;
    int m;
    int n;
     while (true)     { String choice = ConsoleIn.readLine();
      String a[] = choice.split("\\s+");
      Scanner scanner = new Scanner(System.in);
  if(a[0].equals("new"))       {  if(a[1].equals("A")) { x++;
        String type = a[1]; String mealPrice = a[2];
        int mealTime = 30;
        pricea.add(a[2]); Customer customer = new Customer(30, type,Integer.parseInt(mealPrice)); customerList.add(customer);
        System.out.println("新来的客人坐到了座位上点了"+pricea.get(x-1)+"元"+"的餐点,并开始用餐");
       }         if(a[1].equals("B")) { y++;
        String type = a[1]; String mealPrice = a[2];
        int mealTime = 40;
        priceb.add(a[2]); Customer customer = new Customer(40, type,Integer.parseInt(mealPrice)); customerList.add(customer);
        System.out.println("新来的客人坐到了座位上点了"+priceb.get(y-1)+"元"+"的餐点,并开始用餐"); } }
      if(a[0].equals("status"))
      {  for(m=1;m<=x;m++)
        {
          System.out.println("一位点"+"\t"+pricea.get(m-1)+"元"+"\t"+"的A类型客人已用餐");
        }
        for(n=1;n<=y;n++)
        {
          System.out.println("一位点"+"\t"+priceb.get(n-1)+"元"+"\t"+"的B类型客人已用餐");
        }
      
        System.out.println(passtime.get(0));
      
      }
      else if (a[0].equals("pass"))       {  String timePassed = a[1];
        System.out.println("经过了"+timePassed+"分钟");
        double e = Double.parseDouble(timePassed); passtime.add(e);
        double k = passtime.get(0);
        for (int i=0;i<x+y;i++)         {  
          Customer c=customerList.get(i); double mealTimeLeft=c.getMealTime(e); System.out.println("点"+c.mealPrice+"元的客人"+"用餐时间还剩下"+mealTimeLeft+"分钟"); }
         System.out.println("-----------------------------------------------------------------------------"); }
      else if (a[0].equals("exit"))       { break; } } }
}

请问为何compile时会出错
他写
test2.java:65 : error : incompatible types
double k = passtime.get(0);
required: double
found: Object

我宣告一个阵列passtime来储存经过的时间
然后宣告一个k来读此阵列
为何不能??

作者: grimmu85155   发布时间: 2011-11-27

1
ArrayList passtime = new ArrayList();

因为宣告 passtime 时只宣告了 Arraylist,但是却没宣告 ArrayList 里面存的内容的形态
所以预设里面会是 Object 型态,当然取出来时用
1
double k = passtime.get(0);

会出现型态不符的例外,因为预期取出来的是 Object 型态,却要用 double 来接

作者: jimwayne   发布时间: 2011-11-27