我在尝试编写一个计算升序单词数量的程序时遇到了很多麻烦。我尝试了几种不同的方法来解决这个问题,但似乎无法让它发挥作用。
如果有人可以帮助我修改代码以使其正常工作,将不胜感激。
借助Commons IO读取文件非常简单:
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class AscendingWords {
public static void main(String[] args) throws IOException {
List<String> strings = FileUtils.readLines(new File("file.txt"));
for (String string : strings) {
if (ascending(string)) {
System.out.println(string);
}
}
}
public static boolean ascending(String string) {
if (string.length() <= 1) return true;
else return string.charAt(0) < string.charAt(1)
&& ascending(string.substring(1));
}
}
您应该使用 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;
}
}
}