繁体   English   中英

如何使用扫描仪输入读取带有斜杠“/”的 txt 文件并将它们放入数组/字符串中

[英]How to read txt file with slashes “/” with scanner input and put them into arrays/strings

我想知道如何读取带有斜杠的文本文件并将它们放入 arrays 中? 我似乎无法弄清楚如何拆分它们。

TXT 文件内容:

ID      Name                              Price        Stock
00011   / Call of Duty: Modern Warfare    / 2499       / 10 
00012   / The Witcher 3: Wild Hunt        / 1699       / 15 
00013   / Doom Eternal                    / 2799       / 20
00014   / Outlast 2                       / 1999       / 11
00015   / Forza Horizon 4                 / 2799       / 5

这是我获取 ID 的示例代码:

File file1 = new File("stock\\consoles\\consoles.txt");
                    int ctr = 0;
                    try {
                        Scanner s1 = new Scanner(new File(String.valueOf(file1)));
                        while (s1.hasNextLine()) {
                            ctr = ctr + 1;
                            s1.next();
                            s1.nextLine();
                        }
                        String[] ID = new String[ctr];
                        Scanner s2 = new Scanner(new File(String.valueOf(file1)));
                        for (int i = 0; i < ctr; i++) {
                            ID[i] = s2.next();
                            s2.nextLine();

                            System.out.println(Arrays.toString(ID));
                        }
                    } catch (FileNotFoundException ex) {
                        ex.printStackTrace();
                    }
                }

当我运行代码时,我得到了这个:

[00011, null, null, null, null]
[00011, 00012, null, null, null]
[00011, 00012, 00013, null, null]
[00011, 00012, 00013, 00014, null]
[00011, 00012, 00013, 00014, 00015]

预期的 output 将是:

00011
00012
00013
00014
00015

我想将其放入 ID、名称、价格和库存的 arrays 中,形式为:

String[] ID = new String[ctr];
String[] NAME = new String[ctr];
String[] PRICE = new String[ctr];
String[] STOCK = new String[ctr];

任何帮助,将不胜感激。 谢谢你。

尝试这个

        File file = new File("C:\\Users\\***\\Desktop\\name.txt"); 
        Scanner sc = new Scanner(file);
        String[] ids=new String[5]; //---- set your array length
        int counter=0;
        while(sc.hasNext()) {           
            String data=sc.nextLine();
            if(data.contains("/")) { // ignores your data header
                String[] elements=data.split("/");
                ids[counter]=elements[0].trim();
                  // other elements[x] can be saved in other arrays
                counter++;
            }       
}
    for(String i:ids) {
        System.out.println(i);
    }

这将为您提供 output:

00011
00012
00013
00014
00015

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM