不知道为什么我得到不兼容的类型
我尝试编写基于这些指令的方法时出现不兼容的类型错误:“一种方法需要一个int参数并在屏幕上显示细节(名称,出生年份等),该方法必须确保参数是有效的索引位置,如果不是,则显示错误消息。 (在程序中有两个相互使用的类别)。我已经评论我在下面的错误。我希望得到一些帮助。谢谢。不知道为什么我得到不兼容的类型
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());
}
}
}
因为你已经定义的猫是这样的:
cats = new ArrayList <Cat>();
这将在index
位置返回猫:
cats.get(index);
但你已经定义指数为int并assignign一猫去它:
index = cats.get(index);
正确的方法从列表中获得一个产品:
Cat cat = cats.get(index);
要打印检索到的猫的名字,只需运行:
System.out.println(cat.getName());
cats.get()
回报Cat
,和你想分配结果到int
:
index = cats.get(index); //incompatible types?
目前还不清楚该功能的目的是什么,但哟ü可以存储结果的cats.get()
像这样:
Cat cat = cats.get(index);
得到别的东西似乎不起作用。当我调用方法时,它只显示文字参数输入,而不是显示猫的信息。 – 2013-03-04 09:12:43
@JoshuaBaker:你在印刷'索引'还是'猫'? – NPE 2013-03-04 09:13:23
我尝试了两个。当我打印索引时,我得到了文字参数输入。当我输入猫,当调用方法是显示一些奇怪的东西,如“猫@ 68c6fc84” – 2013-03-04 09:17:32
问题在此声明:
index = cats.get(index);
cats.get(指数)返回一个猫的对象。其中索引是int类型。 cat对象不能分配给int类型变量。因此它显示类型不兼容。
一种解决方案是要做到这一点:
Cat cat = cats.get(index);
并打印由上面的语句返回的猫,你可以在猫类中重写toString()
做到以下几点:
public String toString()
{
return "cat name: " + this.getName();
}
使用以下语句打印Cattery信息中的Cat信息
System.out.println(cat);
好了,所以在这条线:
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);
声明
index = cats.get(index);
将返回猫项这里就不再返回int值 乌尔指定目录项为int类型,因此为了得到正确的输出u hava将代码更改为
Cat cat=cats.get(index);
您使用'cats.add( newCat);''你不能指望用'cats.get(index);' – A4L 2013-03-04 09:08:43