【问题标题】:How to read txt file with slashes "/" with scanner input and put them into arrays/strings如何使用扫描仪输入读取带有斜杠“/”的txt文件并将它们放入数组/字符串中
【发布时间】:2020-04-12 06:01:53
【问题描述】:

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

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]

预期的输出是:

00011
00012
00013
00014
00015

我想把它放入 ID、Name、Price 和 Stock 的数组中,格式如下:

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

任何帮助将不胜感激!谢谢。

【问题讨论】:

  • 因格式问题已编辑。

标签: java file java.util.scanner filereader


【解决方案1】:

试试这个

        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);
    }

这将为您提供输出:

00011
00012
00013
00014
00015

【讨论】:

  • 您好!代码工作得很好!请问如何获得相同的项目名称,价格和库存?谢谢。
猜你喜欢
  • 1970-01-01
  • 2012-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-18
  • 2020-03-06
相关资源
最近更新 更多