首页 > 解决方案 > 如何使用扫描仪让用户输入这段代码

问题描述

我可以让程序将预设值添加到 csv 文件中,但我想对其进行调整,以便用户可以输入学生 ID Char(6) 和学生标记(最大 100),并确保不能输入减号。我该怎么做呢?

public class Practicalassessment {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {

       System.out.println("Enter the Students ID:  ");
       scanner scanner = new scanner (System.in);
       String ID = scanner.nextline();
       System.out.println("You have selected Student" + ID);

       System.out.println("Enter the Students Mark");
       scanner scanner1 = new scanner(System.in);
       String mark = scanner1.nextLine();
       System.out.println("You Have Entered" + mark);

       String filepath = ("marks.txt");


       newMarks(ID,mark,filepath);
    }

    public static void newMarks (String ID, String mark, String filepath) throws IOException
    {
        try
        {
            FileWriter fw = new FileWriter(filepath,true);
            BufferedWriter bw = new BufferedWriter (fw);
            PrintWriter pw = new PrintWriter (bw);

            pw.println(ID+","+mark);
            pw.flush();
            pw.close();

            JOptionPane.showMessageDialog(null, "Records Updated Sucessfully");
        }
        catch (Exception E)
        {
            JOptionPane.showMessageDialog(null, "Records Unable to Be Updated");
        }
    }
}

标签: javacsvnetbeans

解决方案


就个人而言,我会坚持单一的用户体验方法。如果要使用JOptionPane显示对话框,则还应使用 GUI 收集信息。

我会这样做(请注意,按照惯例,Java 变量是以小写字母开头的 camelCase):

String id = JOptionPane.showInputDialog("Enter Student's ID:");
// NOTE: need to check for null if canceled
// NOTE: should verify the input/format

注释中指出的错误消息是因为 JavaScanner是大写字母。不知道那是什么东西。

但是,如果想使用 a Scanner,则只实例化一个:

Scanner scanner = new Scanner(System.in);

System.out.println("Enter the Students ID:  ");
String ID = scanner.nextline();
System.out.println("You have selected Student" + ID);

System.out.println("Enter the Students Mark");
String mark = scanner.nextLine();
System.out.println("You Have Entered" + mark);

...

请注意,扫描器输入也存在相同的输入验证约束。


推荐阅读