无法弄清楚为什么我会得到不兼容的类型

时间:2013-03-04 09:03:18

标签: java

我在尝试根据这些指令编写方法时出现了不兼容的类型错误:“一个采用int参数的方法,并在屏幕上显示Cat的详细信息(姓名,出生年份等)存储在该索引位置。此方法必须确保参数是有效的索引位置,如果不是则显示错误消息。“ (程序中有两个相互使用的类别)。我已经评论了下面我收到错误的地方。我将不胜感激。感谢。

import java.util.ArrayList;


public class Cattery
{
// instance variables - replace the example below with your own
private ArrayList <Cat> cats;
private String businessName;

/**
 * Constructor for objects of class Cattery
 */
public Cattery(String NewBusinessName)
{
    cats = new ArrayList <Cat>();
    NewBusinessName = businessName;
}

public void addCat(Cat newCat){

    cats.add(newCat);
}

public void indexDisplay(int index) {
    if((index >= 0) && (index <= cats.size()-1)) {
        index = cats.get(index);                       //incompatible types?
        System.out.println(index);
    }
    else{
        System.out.println("Invalid index position!");
    }
 }

 public void removeCat(int indexremove){
     if((indexremove >= 0) && (indexremove <= cats.size()-1)) {
         cats.remove(indexremove);
        }
    else{
        System.out.println("Invalid index position!");
    }
  }

 public void displayNames(){
   System.out.println("The current guests in Puss in Boots Cattery:");
   for(Cat catNames : cats ){
       System.out.println(catNames.getName());

 }
 }
 }

5 个答案:

答案 0 :(得分:2)

因为你已经定义了这样的猫:

 cats = new ArrayList <Cat>();

这将返回位置index的猫:

cats.get(index);

但是您已将index定义为int并为其分配了一只猫:

 index = cats.get(index);

从列表中获取项目的正确方法是:

Cat cat = cats.get(index);

要打印检索到的猫的名称,只需运行:

System.out.println(cat.getName());

答案 1 :(得分:2)

本声明中的问题:

index = cats.get(index);

cats.get(index)返回一个cat对象。其中index是int类型。 cat对象不能分配给int类型变量。因此它显示类型不兼容。

一种解决方案是:

Cat cat = cats.get(index);

要打印上述语句返回的cat,您可以覆盖Cat类中的toString()

执行以下操作:

public String toString()
{
    return "cat name: " + this.getName();
}

在您的Cattery类中打印Cat的信息,请使用以下声明

System.out.println(cat);

答案 2 :(得分:1)

cats.get()返回Cat,您尝试将结果分配给int

    index = cats.get(index);                       //incompatible types?

目前还不清楚该功能的用途是什么,但您可以将cats.get()的结果存储起来:

    Cat cat = cats.get(index);

答案 3 :(得分:1)

好的,所以在这一行:

index = cats.get(index);      

期待什么 cats.get(index)返回? cats的类型为ArrayList<Cat> - 因此您应找到ArrayList<E>的文档,然后导航到get方法,并看到它的声明如下:

public E get(int index)

因此,在ArrayList<Cat>中,get方法将返回Cat

所以你想要:

Cat cat = cats.get(index);

答案 4 :(得分:0)

声明

 index = cats.get(index);

将返回Cat项,它不会返回int值 这里你将Cat项目分配给int类型,以便获得正确的输出u hava change code as

Cat cat=cats.get(index);
相关问题