我在尝试编写一个计算单词上升量的程序时遇到了很多麻烦。我尝试了几种不同的方法来解决此问题,但似乎无法使其正常工作。

如果有人可以帮助我修改代码以使其正常工作,将不胜感激。

最佳答案

您应该使用hasNext()和next()作为输入,因为如果使用nextLine(),它将占用文件中的整行(或直到找到换行符)。

尝试这个:

i=0; //i should start from 0
while(inputFile.hasNext()){
    theWord = inputFile.next();
    ascending = true; //remember to reset ascending to be true as default
    i = 0; //reset i to 0 again
    if(theWord.length() >= 2){
        while(i < theWord.length() - 1){
            if(theWord.charAt(i) > theWord.charAt(i + 1)){
                 ascending = false;
                 break; //since we know that its not ascending, just move on to the next word
            }
            i++;
        }
        //if after the check ascending still true that means the word is ascending
        if(ascending==true){
            System.out.println("+ " + theWord);
            totalNum = totalNum + 1;
        }
    }
}

08-04 23:45