【发布时间】:2021-09-26 02:58:00
【问题描述】:
我需要我的 Java 程序来获取一个文本文件,读取该文本文件,计算并重现该文本文件中的空白数量
这是我目前拥有的代码
import java.io.File; //import the file class
import java.io.FileNotFoundException; //import this class to handle errors
import java.util.Scanner; //import the scanner class to read the file
public class whitespaceReader {
public static void main(String[] args) {
try {
File myFile = new File("aliceInWonderland.txt");
Scanner reader = new Scanner(myFile);
int space = 0;
int i = 0;
String word;
word = reader.nextLine();
while (i < word.length()){
char a = word.charAt(i);
if(a == '//tried to use empty brackets here, did not work') {
space++;
}
i++;
}
System.out.println("amount of white space is: " + space);
} catch (FileNotFoundException e) {
System.out.print("Uh oh! Something went wrong");
e.printStackTrace();
}
}
}
【问题讨论】:
-
您需要仔细阅读作业要求,才能准确理解老师所说的“空白”是什么意思。这是否仅表示
SP字符?TAB(又名HT)或VT呢?CR和NL呢?不间断的空间代码呢?另外,找出TAB是否正好表示一个“空白”,如果CRNL表示一个或两个“空白”。 -
但如果您只需要计算
SP个字符,那么a == ' '就可以了。 (单)引号之间正好是一个空格字符。 -
分配要求没有指定任何这些定义,它只是说计算空白。我以为它的意思是在单词之间?但细节很少。
-
那么你需要>>问你的老师他或她的意思。或者做一个猜测,希望你猜对了。
-
谢谢您,非常感谢您的帮助。我将通过教程进行澄清,您的建议对单引号之间的一个空格字符非常有帮助!
标签: java whitespace