我的目标是从给定的输入文件中读取每行的第一个元素/术语,然后根据第一个元素是什么来决定要做什么(使用 if-else
构造)。 IE。如果第一个元素/单词恰好是“the”(如下面的代码中所述),那么我必须跳过该行并移至下一行。
到目前为止,我已经编写了以下代码,但我不确定如何仅读取我作为输入传递的文本文件的每一行的第一个元素。
public static void main(String[] args) {
BufferedReader br = null;
try {
String line;
br = new BufferedReader(new FileReader("input.txt"));
while ((line = br.readLine()) != null) {
System.out.println(line);
StringTokenizer stringTokenizer = new StringTokenizer(line, " ");
while (stringTokenizer.hasMoreTokens()) {
String term = stringTokenizer.nextElement().toString();
if (term.equals("the")) {
//Code on what to do depending on the first character of each line.
}
StringBuilder sb = new StringBuilder();
System.out.println(sb.toString());
}
}
System.out.println("Done!");
}
catch (IOException e)
{
e.printStackTrace();
}
finally {
try {
if (br != null)
br.close();
}
catch(IOException ex) {
ex.printStackTrace();
}
}
}
最佳答案
下面是打印 the
作为输出的简单代码。您可以使用它,无需创建额外的数组或使用 StringTokenizer。
String s = "The a an the abcdef.";
System.out.println(s.contains(" ") ? s.substring(0, s.indexOf(" ")) : s);
关于java - 如何在Java中读取一行的第一个元素/术语?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40694988/