java - 当我用 Java 中的 Scanner 类读取 .txt 文件时,如何只读取字符串或整数
问题描述
嘿伙计们,这是我的第一个问题,所以如果我有任何错误或错误,我很抱歉。
所以我正在做一件我目前一直失败的事情,那就是,正如它在标题中所说,只从 .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]);
}
推荐阅读
- php - 当值为空时,我想在页面上打印其他内容
- reactjs - 如何保存我最近用 axios 创建的 firebase 中的数据并做出反应?
- python - 从 PySpark 中的某个日期开始计算周数、天数和月数
- kotlin - 如何在 Kotlin 中为具有默认值 true 或 false 或 null 的变量传递值
- oracle11g - ORACLE APEX 创建登录触发器
- python - ReportLab 目录
- mysql - 如何在不重复计算的情况下执行 SQL
- c - MSBuild 无法从 CLI 构建。无效的静态调用语法
- wpf - keyDown 事件在按下并释放第二个键后停止触发
- python - 转换数据帧的 2 列,在对应的 uint16_t 的列中存储两个 uint8_t