在同一行中读取多个字符串

时间:2014-03-15 10:00:08

标签: java string java.util.scanner

好的家伙所以我一直得到一个没有这样的元素异常代码,并且无法弄清楚如何调试它我很确定问题出现在我的可实例化的类中

list.add(new Fan(
    scanFile.nextInt(), 
    scanFile.nextLine(),
    scanFile.nextLine(),
    scanFile.nextLine()
));  

编辑下面的代码现在可以正常工作

任何想法如何超越这个?

public class Fan {

//fields
private static final String fileName = "fans.txt";
private String name;
private String email;
private String promo;
private int age;

//constructor
private Fan(int age, String name, String email,String promo){
    this.name=name;
    this.email=email;
    this.age=age;
    this.promo = promo;
}

//get name
public String getName() {
    return name;
}

//get age
public int getAge() {
    return age;
}

//get email
public String getEmail() {
    return email;
}
 //get subscription
public String getPromo(){
    return promo;
}

//get existing Fan Information
public static ArrayList<Fan> getSubscribingFans() {
    //local variables
    File FanFile = new File(fileName);
    ArrayList<Fan> list = new ArrayList<>();
    //create file if it doesn't exist
    if (!FanFile.exists()) {
        try {
            FanFile.createNewFile();
            return list;
        } catch (IOException ioe) {
            return null;
        }
    }
    //read file, save each line as an Fan object, store in ArrayList
    try (Scanner scanFile = new Scanner(FanFile)) {
    //edited now works
while (scanFile.hasNext()) {
            list.add(new Fan(scanFile.nextInt(), scanFile.nextLine(),null,null));
        }
    } catch (IOException ioe) {
        return null;
    }
    //return list
    return list;
}
    //add a new Fan
    public static boolean addFanSubscriber(int age, String name, String email, String promo) {
        //append to file
        try (PrintWriter pw = new PrintWriter(new FileWriter(fileName, true))) {
//edited spacing inside qoutes              
pw.println(age + "    " + name + "    "+ email + "    " + promo);
        } catch (IOException ioe) {
            return false;
        }
        return true;
    }   
}

这是我的JFrame代码

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                FanControl frame = new FanControl();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public FanControl() {
    txtEmail.setHorizontalAlignment(SwingConstants.CENTER);
    txtEmail.setColumns(8);
    txtName.setHorizontalAlignment(SwingConstants.CENTER);
    txtName.setColumns(8);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 484, 326);
    contentPane = new JPanel();
    contentPane.setBackground(Color.BLACK);
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    contentPane.setLayout(new BorderLayout(0, 0));
    setContentPane(contentPane);
    panel.setBackground(Color.BLACK);

    contentPane.add(panel, BorderLayout.NORTH);
    lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
    lblNewLabel.setFont(new Font("Monotype Corsiva", Font.BOLD, 36));
    lblNewLabel.setForeground(new Color(0, 255, 255));

    panel.add(lblNewLabel);
    panel_1.setBackground(Color.BLACK);

    contentPane.add(panel_1, BorderLayout.SOUTH);
    lblAge.setFont(new Font("Tahoma", Font.BOLD, 11));
    lblAge.setForeground(Color.CYAN);
    lblAge.setHorizontalAlignment(SwingConstants.CENTER);

    panel_1.add(lblAge);
    spnAge.setModel(new SpinnerNumberModel(18, 0, 100, 1));

    panel_1.add(spnAge);
    lblName.setFont(new Font("Tahoma", Font.BOLD, 11));
    lblName.setForeground(Color.CYAN);
    lblName.setHorizontalAlignment(SwingConstants.CENTER);

    panel_1.add(lblName);

    panel_1.add(txtName);
    lblEmail.setFont(new Font("Tahoma", Font.BOLD, 11));
    lblEmail.setForeground(Color.CYAN);
    lblEmail.setHorizontalAlignment(SwingConstants.CENTER);

    panel_1.add(lblEmail);

    panel_1.add(txtEmail);
    btnSubmit.addActionListener(new BtnSubmitActionListener());
    btnSubmit.setBackground(Color.BLACK);
    btnSubmit.setFont(new Font("Tahoma", Font.BOLD, 11));
    btnSubmit.setForeground(Color.GREEN);

    panel_1.add(btnSubmit);
    scrollPane.setBorder(null);

    contentPane.add(scrollPane, BorderLayout.CENTER);

    scrollPane.setViewportView(textArea);
    panel_2.setBorder(null);
    panel_2.setBackground(Color.BLACK);

    scrollPane.setRowHeaderView(panel_2);
    panel_2.setLayout(new GridLayout(0, 1, 0, 0));
    lblWouldYouLike.setBackground(Color.BLACK);
    lblWouldYouLike.setForeground(Color.CYAN);
    lblWouldYouLike.setFont(new Font("Tahoma", Font.BOLD, 11));

    panel_2.add(lblWouldYouLike);
    buttonGroup.add(btnYes);
    buttonGroup.add(btnNo);
    btnYes.setBackground(Color.BLACK);
    btnYes.setFont(new Font("Tahoma", Font.BOLD, 11));
    btnYes.setForeground(Color.GREEN);

    panel_2.add(btnYes);
    btnNo.setBackground(Color.BLACK);
    btnNo.setFont(new Font("Tahoma", Font.BOLD, 11));
    btnNo.setForeground(Color.RED);
    btnNo.setSelected(true);

    panel_2.add(btnNo);
}

//update text area with current list of inventory items
private void updateList() {
    //clear text area
    textArea.setText("");
    //get current list
    ArrayList<Fan> fans = Fan.getSubscribingFans();
    if (fans == null) {
        JOptionPane.showMessageDialog(contentPane, "ERROR: unable to create or open fans file");
        return;
    }
    //create String array
    String[] fansStrs = new String[fans.size()];
    for (int i=0; i<fans.size(); i++) {
        fansStrs[i] = String.format("%10d %s \n", fans.get(i).getAge(), fans.get(i).getName(), fans.get(i).getEmail(),fans.get(i).getPromo());
    }
    //sort String array
    Arrays.sort(fansStrs);
    //display strings
    for (String s: fansStrs) {
        textArea.append(s);
    }
}

        //submit button clicked
private class BtnSubmitActionListener implements ActionListener {
    public void actionPerformed(ActionEvent arg0) {
        //local variables
        String email = txtEmail.getText();
        int age = (int)spnAge.getValue();
        String name = txtName.getText();
        String promo;
        boolean ok = true;
        //add fan EDITED promo =
        if (btnYes.isSelected()){
            promo = "PromoTeam";
        }else{
            promo = "";
        }
        ok = Fan.addFanSubscriber(age, name, email, promo);
        if (!ok) {
            JOptionPane.showMessageDialog(contentPane, "ERROR: unable to add item to inventory file");
            return;
        }
        //refresh the list
        updateList();
        //clear input fields
        txtEmail.setText("");
        txtName.setText("");
        spnAge.setValue(18);
    }
}

1 个答案:

答案 0 :(得分:0)

看看以下几行:

while (scanFile.hasNextLine()) {
    list.add(new Fan(scanFile.nextInt(), scanFile.nextLine(), scanFile.nextLine(), scanFile.nextLine()));
}

如果您输入的文件有例如最后一个空行,while循环的条件为真,但nextInt将找不到任何int,并且正如Java文档所说:

  

抛出:

     
    

NoSuchElementException - 如果输入已用尽

  

来源:http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt%28%29

如果最后一个数据集未完成且您的文档中没有剩余三行,则会出现相同的错误,因为您只检查是否有剩余行,然后您读取了三行。

对于第一个问题,您可以使用hasNextInt方法检查是否还有其他int