尝试获取文件的输入,评估它并ouptut某些信息

时间:2018-06-08 18:01:25

标签: java java.util.scanner

private void evaluateActionPerformed(java.awt.event.ActionEvent evt) {                                         

       Scanner sc = new Scanner("salesrep.txt");       

       while (sc.hasNext())
        {
            try {
            readID = sc.next();
            readFName = sc.next();
            readLName = sc.next();
            readSupplies = Double.parseDouble(sc.next());
            readBooks = Double.parseDouble(sc.next());
            readPaper = Double.parseDouble(sc.next());
            readDistrict = sc.next();
            readMOC = sc.next();           

            total = sum(readSupplies, readBooks, readPaper);
            } catch (NumberFormatException e) 
            {
                textArea.setText("Error: ");
            }

            if(total >= 8000)
            {   
                try {
                    PrintWriter stars;
                    stars = new PrintWriter(new FileOutputStream(new File("stars.txt"), true));
                    String newLine = System.lineSeparator();
                    String newRecord = (readID + newLine + readFName + newLine + readLName + newLine + readSupplies + newLine + readBooks + newLine + readPaper + newLine + readDistrict + newLine + readMOC);
                    stars.append(newRecord);
                    stars.flush();
                    stars.close();
                    textArea.append("Sales Representatives Information Successfully Evaluated");
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(salesRepresentativeData.class.getName()).log(Level.SEVERE, null, ex);
                    textArea.setText("Error: File not found");
                }
            }
        }
    }

我在点击第二个变量时收到错误NoSuchElement。无法弄清楚为什么或如何绕过它。

1 个答案:

答案 0 :(得分:0)

这是因为您初始化Scanner对象的方式( sc )。要阅读文件,请使用:

Scanner sc = new Scanner(new File("salesrep.txt"));

您的方式 Scanner.next()方法只会看到一个字符串,当然" salesrep.txt" 。毕竟,扫描程序类也可以对提供的字符串起作用。您需要告诉它它是您想要阅读的文件。

在旁注上,请记住,姓名可以是Double-barrelledCompound Surnames,名字和姓氏都可以包含两个或多个字词( Otto Von Schnitzel 或< em> Jacques Le Roux )并且可以应用中间名或初始名称。使用Scanner.next()方法时需要考虑这一点,因为此方法仅检索下一个以空格分隔的标记。