【问题标题】:How do I read files using the scanner class with a space delimeter?如何使用带有空格分隔符的扫描仪类读取文件?
【发布时间】:2014-03-17 07:11:21
【问题描述】:

在学校,我们正在学习编写一个程序,该程序将从名为“Names.txt”的文本文档中读取一个人的全名。我们必须让文件夹中的名字输出名字的第一个字母,然后是完整的姓氏。所有这些都必须在我们对 while 循环、for 循环、if else 语句和布尔值的基本知识之下。我的代码有问题:

Scanner scFile = new Scanner (new File ("Names.txt"));

    String line =  "", name = "";

    int num, sum = 0;
    while (scFile.hasNext())
    {
        Scanner scLine = new Scanner (line).useDelimiter("#");
        name = scLine.next();
        num = scLine.nextInt();

        scLine.close();


        System.out.println(name.substring(0,1) + "\t" + num);
        sum = sum+ num;
    }
    scFile.close();

    System.out.println("The sum is " + sum);

【问题讨论】:

    标签: java loops output names


    【解决方案1】:

    这很简单,可以从 google 获得,因为您认为作为学生,下面给出了代码来尝试您的工作。它将根据您的要求工作..

        BufferedReader reader = new BufferedReader(new FileReader("D:/Names.txt"));
        String line = null;
    
        while ((line = reader.readLine()) != null)
        {
            System.out.println(line);
            String[] lastName = line.split("\\s");
    
            String firtLetterOfFirstName = lastName[0].substring(0, 1);
            System.out.println("Folder Name : "+firtLetterOfFirstName + lastName[1]);
            File file = new File("D:\\"+firtLetterOfFirstName + lastName[1]);
            if(false== file.exists())
            {
                file.mkdir();
            }
    
        }
    

    【讨论】:

      【解决方案2】:

      \\s

      是空格分隔符。所以试试这个:

          Scanner scLine = new Scanner (line).useDelimiter("\\s");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-14
        • 2015-10-23
        • 1970-01-01
        • 2013-12-04
        • 2014-04-03
        相关资源
        最近更新 更多