按字母顺序比较阵列



我的程序应该从文件中读取动物名称,并确定它们是否在字典中的 walrusdinosaur之间。我认为这个程序是正确的。

但是,我继续接收错误的输出,我认为我的问题正在compare.to方法和我的if语句中发生。

如果有人想知道,这是我使用字符阵列的要求。

有人可以向我解释我的程序有什么问题?

Scanner inFile = null;
try {     
    // will read this file
    inFile = new Scanner (new File("Prog505c.dat"));
}
// will print file not found if no file is found and will also exit the program. 
catch (FileNotFoundException e) {
    System.out.println ("File not found!");
    System.exit (0);
}       
String strLine = " ";
int Scope;
do {
    strLine=inFile.nextLine() ;
    char[] animals = strLine.toCharArray();
    String dino = "Dinosaur";
    char[] dinosaur = dino.toCharArray();
    String wal = "Walrus";
    char[] walrus = wal.toCharArray();
    int ResultOne =animals.toString().compareToIgnoreCase(walrus.toString());
    int ResultTwo =animals.toString().compareToIgnoreCase(dinosaur.toString());
    if (ResultOne > 0&&  ResultTwo < 0) {
        System.out.println(strLine +" Not between");
    } else {
        System.out.println(strLine + "  between");
    } 
}while (inFile.hasNextLine()) ;

我的输出是

Vampire  between
Monkay    between
Elephant  between
Ape Not between
Lion  between
Hippopotamus  between
Ant  between
Zebra  between
Yak  between
Antelope  between
Dingo  between
Whale  between

我的输出应该是

Vampire between
Monkey      between
Elephant    between
Ape     not between
Lion        between
Hippopotamus    between
Ant     not between
Zebra       not between
Yak     not between
Antelope    not between
Dingo       not between
Whale       not between

这一行是您的问题:

if (ResultOne > 0&& ResultTwo < 0)

这是在检查"海象"one_answers"恐龙"之前的弦,这显然是不可能的。该检查永远不会通过,因此它总是转到else块并在"之间"打印。要修复它,只需将&&更改为||

您的代码问题是,它将整个输入字符串与整个字符串(即)将"吸血鬼"与"恐龙"one_answers" Walrus"进行比较:

int ResultOne =animals.toString().compareToIgnoreCase(walrus.toString());
int ResultTwo =animals.toString().compareToIgnoreCase(dinosaur.toString());

这就是为什么它将输出作为"每次"之间的输出给出的原因,因为您的代码在不满足条件时将执行的其他语句中的代码具有"之间"。在您的情况下,海象,恐龙和吸血鬼不等。

实际上,您需要将输入字符串的第一个字符与恐龙和海象的第一个字符进行比较。因此代码应该是这样:

int ResultOne =String.valueOf(animals[0]).compareToIgnoreCase(String.valueOf(dinosaur[0]));
int ResultTwo =String.valueOf(animals[0]).compareToIgnoreCase(String.valueOf(walrus[0]));

您的if条件应该是这样:

if (!(ResultOne > 0 &&  ResultTwo < 0))

希望这会有所帮助!

您有一个不可能的选择,您需要重新组织它:

if (ResultOne < 0 &&  ResultTwo > 0)
{//here between}
else
{here not between}

当您放置if时,永远不会适当,因为您同时需要一个恐龙和海象以下的世界。

1)使用条件 - 或,

2)从char[]转换为String时,请使用new String(charArray)代替toString(),因为数组不会覆盖toString.(P.S.给您的任何人都希望您理解并学习此概念。)

ref>如何将char数组转换回字符串?

最新更新