嘿伙计们,这是我的第一个问题,所以如果我有任何错误或过失,我很抱歉。
所以我正在做一件我目前一直失败的事情,那就是,正如标题中所说,只从 .txt 文件中读取字符串和整数。这是我的代码:
File file = new File("C:\\Users\\Enes\\Desktop\\test.txt");
Scanner scn = new Scanner(file);
String[] s = new String[10];
int i = 0;
int[] fruits = new int[10];
while (scn.hasNextInt()) {
fruits[i++] = scn.nextInt();
}while (scn.hasNext()) {
s[i++] = scn.next();
}
for (int elm : fruits) {
System.out.print(elm + "\t");
System.out.println("\n");
}
for (String ele : s) {
System.out.print(ele + "\t");
}
这是 .txt 文件中写入的内容
Apple 5
Pear 3
输出如下:
0 0 0 0 0 0 0 0 0 0
Apple 5 Pear 3 null null null null null null
所以我想得到Apple和Pear,不同数组中的字符串以及5和3,它们是不同数组中的整数。我怎样才能做到这一点?任何帮助将不胜感激。谢谢大家!
最佳答案
首先,我会将您的变量重命名为有用的名称:
String[] names = new String[10];
int[] counts = new int[10];
现在,您正在尝试获取所有 10 个号码,然后获取所有 10 个名称。但这不是您的数据的布局方式。
我会使用扫描仪抓取线,然后将其从那里分开:
Scanner sc = new Scanner(new File(file));
int index = 0;
while(sc.hasNextLine()) {
String line = sc.nextLine();
String[] tokens = line.split(" ");
names[index] = tokens[0];
counts[index] = Integer.parseInt(tokens[1]);
index++;
}
对于输出,我们同时迭代两个循环:
for(int i = 0; i < 10; i++) {
System.out.println(names[i] + "\t" + counts[i]);
}
关于java - 当我用Java中的Scanner类读取.txt文件时,如何只能读取字符串或整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50594135/