0

我在尝试根据这些说明编写方法时遇到不兼容类型错误的问题:“一种采用 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());

 }
 }
 }
4

5 回答 5

2

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

 cats = new ArrayList <Cat>();

这将在位置返回一只猫index

cats.get(index);

但是您已将 index 定义为 int 并为其分配 cat:

 index = cats.get(index);

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

Cat cat = cats.get(index);

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

System.out.println(cat.getName());
于 2013-03-04T09:05:14.150 回答
2

此语句中的问题:

index = cats.get(index);

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

一种解决方案是这样做:

Cat cat = cats.get(index);

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

请执行下列操作 :

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

要在 Cattery 类中打印 Cat 的信息,请使用以下语句

System.out.println(cat);
于 2013-03-04T09:05:56.850 回答
1

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

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

目前尚不清楚该函数的目的是什么,但您可以cats.get()像这样存储结果:

    Cat cat = cats.get(index);
于 2013-03-04T09:05:20.133 回答
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);
于 2013-03-04T09:05:59.300 回答
0

该声明

 index = cats.get(index);

将返回 Cat 项目它不会在这里返回 int 值你将 Cat 项目分配给 int 类型所以为了获得正确的输出你 hava 更改代码为

Cat cat=cats.get(index);
于 2013-03-04T09:11:30.073 回答