大家好,这是我的第一个问题,如果我有任何错误或毛病,对此我感到抱歉。
因此,我正在做我当前一直无法解决的一件事,即如标题中所述,仅从.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]);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句