如何使用Java的Scanner类读取.txt文件中的字符串与整数
解决Scanner读取交替字符串与整数的问题
嘿,我来帮你梳理下问题出在哪~
你当前的代码逻辑是先尝试读取所有整数,再读取字符串,但你的文件开头是字符串Apple,第一个while (scn.hasNextInt())条件从一开始就不成立,所以fruits数组完全没被赋值,全是默认的0。紧接着第二个循环把文件里的所有内容(包括数字5、3)都当成字符串读进了s数组,这就是你看到奇怪输出的原因。
你的文件格式是字符串 整数交替出现的,所以应该每次循环先读一个字符串,再读一个整数,直到没有更多内容。这里给你两种实现方案:
方案1:用固定数组实现(贴合你原本的数组思路)
如果确定元素数量,直接对应数组长度即可,也可以保留你原来的10位长度:
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ReadFile { public static void main(String[] args) throws FileNotFoundException { File file = new File("C:\\Users\\Enes\\Desktop\\test.txt"); Scanner scn = new Scanner(file); String[] fruitsNames = new String[10]; int[] fruitsCounts = new int[10]; int index = 0; // 循环交替读取:先读字符串,再读整数 while (scn.hasNext()) { // 读取水果名称 fruitsNames[index] = scn.next(); // 读取对应的数量 if (scn.hasNextInt()) { fruitsCounts[index] = scn.nextInt(); index++; } } // 输出整数数组 System.out.println("整数数组内容:"); for (int i = 0; i < index; i++) { System.out.print(fruitsCounts[i] + "\t"); } System.out.println("\n"); // 输出字符串数组 System.out.println("字符串数组内容:"); for (int i = 0; i < index; i++) { System.out.print(fruitsNames[i] + "\t"); } scn.close(); } }
方案2:用ArrayList(更灵活,无需固定长度)
如果文件里的元素数量不确定,用集合会更省心,不用提前考虑数组长度:
import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public class ReadFile { public static void main(String[] args) throws FileNotFoundException { File file = new File("C:\\Users\\Enes\\Desktop\\test.txt"); Scanner scn = new Scanner(file); ArrayList<String> fruitsNames = new ArrayList<>(); ArrayList<Integer> fruitsCounts = new ArrayList<>(); // 交替读取字符串和整数 while (scn.hasNext()) { fruitsNames.add(scn.next()); if (scn.hasNextInt()) { fruitsCounts.add(scn.nextInt()); } } // 输出结果 System.out.println("水果名称:"); for (String name : fruitsNames) { System.out.print(name + "\t"); } System.out.println("\n"); System.out.println("水果数量:"); for (int count : fruitsCounts) { System.out.print(count + "\t"); } scn.close(); } }
这两种方案都能把Apple、Pear单独存入字符串容器,5、3存入整数容器,你可以根据自己的需求选择~
内容的提问来源于stack exchange,提问作者Enes Çalışkan
相关产品推荐
相关产品推荐

