gpt4 book ai didi

java - 字符串日志混淆接口(interface)

转载 作者:行者123 更新时间:2023-11-30 04:13:51 25 4
gpt4 key购买 nike

我正在阅读《使用 Java 的面向对象的数据结构》一书,正在读第 2 章。我决定尝试一下他们在那里的练习之一,但代码似乎对我不起作用,尽管它们是直接的从书中。有人能澄清一下吗?

package chapter2;

public interface StringLogInterface
{
void insert(String element);
boolean isFull();
int size();
boolean contains(String element);
void clear();
String getName();
String toString();
}

该项目使用三个文件,我在下面发布其余两个文件。

package chapter2;

public class ArrayStringLog
{
protected String name;
protected String[] log;
protected int lastIndex = -1;

public ArrayStringLog(String name, int maxSize)
{
log = new String[maxSize];
this.name = name;
}

public ArrayStringLog(String name)
{
log = new String[100];
this.name = name;
}

public void insert(String element)
{
lastIndex++;
log[lastIndex] = element;
}

public boolean isFull()
{
if (lastIndex == (log.length - 1))
return true;
else
return false;
}

public int size()
{
return (lastIndex + 1);
}

public boolean contains(String element)
{
int location = 0;
while (location <= lastIndex)
{
if (element.equalsIgnoreCase(log[location])) // if they match
return true;
else
location++;
}
return false;
}

public void clear()
{
for (int i = 0; i <= lastIndex; i++)
log[i] = null;
lastIndex = -1;
}

public String getName()
{
return name;
}

public String toString()
{
String logString = "Log: " + name + "\n\n";

for (int i = 0; i <= lastIndex; i++)
logString = logString + (i+1) + ". " + log[i] + "\n";

return logString;
}
}

最后一部分:

package chapter2;

public class UseStringLog
{
public static void main(String[] args)
{
StringLogInterface sample;
sample = new ArrayStringLog("Example Use");
sample.insert("Elvis");
sample.insert("King Louis XII");
sample.insert("Captain Kirk");
System.out.println(sample);
System.out.println("The size of the log is " + sample.size());
System.out.println("Elvis is in the log: " + sample.contains("Elvis"));
System.out.println("Santa is in the log: " + sample.contains("Santa"));
}
}

最后一部分让我感到困惑。已上线,

sample = new ArrayStringLog("Example Use");

NetBeans 说“无法比较的类型,必需:StringLogInterface,找到:ArrayStringLog。

它们都构建成功,但是最后一个带有三个 println 语句的文件不应该打印出一些东西吗?

最佳答案

使ArrayStringLog实现StringLogInterface

public class ArrayStringLog implements StringLogInterface {
// ...
}

只有这样才有可能:

StringLogInterface sample;
sample = new ArrayStringLog("Example Use");

关于java - 字符串日志混淆接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18935569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com