当我从键盘向令牌生成器输入一行时,它没有问题。然而, 我试图通过文件行输入我的输入,文件行的名称在两个单词之间有一个空格。那是我收到NoExplolementException错误的时候。我不确定是否需要关闭文件?但是该文件具有更多需要读取的信息。感谢您抽出宝贵时间阅读我的问题:)
这是代码:
System.out.println("Enter your first and last name");
line = sc.nextLine();
System.out.println(line);
StringTokenizer lineTok = new StringTokenizer(line);
first = (String) lineTok.nextToken();
last = (String) lineTok.nextToken();
答案 0 :(得分:0)
对我来说很好。
package tryouts;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.StringTokenizer;
public class StringTokenizerTest {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new FileInputStream("/usr/projects/tryouts/src/tryouts/test.txt"));
String line = sc.nextLine();
System.out.println(line);
StringTokenizer lineTok = new StringTokenizer(line);
String first = (String) lineTok.nextToken();
System.out.println(first);
String last = (String) lineTok.nextToken();
System.out.println(last);
sc.close();
}
}
在文件夹“ / usr / projects / tryouts / src / tryouts /”中创建一个名为“ test.txt”的文件,其单行内容为“ first second,third,fourth”,并打印第一和第二个。
答案 1 :(得分:0)
下面的代码将打印出该行中的所有单词。
package tryouts;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.StringTokenizer;
public class StringTokenizerTest {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new FileInputStream(
"/usr/projects/tryouts/src/tryouts/test.txt"));
String line = sc.nextLine();
System.out.println(line);
StringTokenizer lineTok = new StringTokenizer(line);
while (lineTok.hasMoreTokens()) {
System.out.println(lineTok.nextToken());
}
sc.close();
}
}