【发布时间】:2020-01-26 19:08:08
【问题描述】:
在我对 Java 类的介绍中,我创建了一个方法,该方法采用此列表并输出一个新的排序列表。现在我正在尝试创建一个方法来检查此列表是否已排序(两者都不区分大小写)。我尝试使用简单的方法并使用 this.equals(this.sorted()) 但它不起作用,因为当我比较已经排序的列表时输出的是 false 而不是 true。我需要一些指导。我不能只使用数组或循环递归。
import tester.Tester;
// to represent a list of Strings
interface ILoString {
//prodces a new list, sorted in alphabetical order case insensitive
ILoString sort();
//helps sort() sort a list
ILoString sortHelp(String acc);
//determines whether this list is sorted in alphabetical order,
//in a case-insensitive way.
boolean isSorted();
}
// to represent an empty list of Strings
class MtLoString implements ILoString {
MtLoString(){}
//prodces a new list, sorted in alphabetical order case insensitive
public ILoString sort() {
return this;
}
//helps sort() sort a list
public ILoString sortHelp(String acc) {
return new ConsLoString(acc, this);
}
//determines whether this list is sorted in alphabetical order,
//in a case-insensitive way.
public boolean isSorted() {
return true;
}
}
// to represent a nonempty list of Strings
class ConsLoString implements ILoString {
String first;
ILoString rest;
ConsLoString(String first, ILoString rest){
this.first = first;
this.rest = rest;
}
//determines whether this list is sorted in alphabetical order,
//in a case-insensitive way.
public boolean isSorted() {
return this.equals(this.sort());
}
//prodces a new list, sorted in alphabetical order case insensitive
public ILoString sort() {
return this.rest.sort().sortHelp(this.first);
}
//helps to sort the names in this ConsLoString
public ILoString sortHelp(String acc) {
if ( acc.compareToIgnoreCase(this.first) < 0) {
return new ConsLoString(acc, this);
}
else {
return new ConsLoString(this.first, this.rest.sortHelp(acc));
}
}
}
// to represent examples for lists of strings
class ExamplesStrings{
ILoString mary = new ConsLoString("Mary ",
new ConsLoString("had ",
new ConsLoString("a ",
new ConsLoString("little ",
new ConsLoString("lamb.", new MtLoString())))));
ILoString marySorted = new ConsLoString("a ",
new ConsLoString("had ",
new ConsLoString("lamb.",
new ConsLoString("little ",
new ConsLoString("Mary ", new MtLoString())))));
// test the method sort for the lists of Strings
boolean testSort(Tester t){
return
t.checkExpect(this.mary.sort(),this.marySorted)&&
t.checkExpect(this.marySorted.sort(),this.marySorted);
}
//test the method isSorted
boolean testisSorted(Tester t){
return
t.checkExpect(this.mary.isSorted(),false)&&
t.checkExpect(this.marySorted.isSorted(),true);
}
}
【问题讨论】:
-
我认为您的问题太模糊,无法得到任何答案。我认为您的代码中存在许多无法轻易解决的单一问题。
-
那么,您的问题是如何使用递归而不是迭代方法来实现
isSorted? -
@Lothar 基本上是的
-
在
ILoString中没有方法getFirst我发现很难找到解决方案。您提供的界面是否完整?再想一想,它本质上是sortHelp的实现,以boolean作为返回类型,并为方法中的两个条件提供相应的返回值。