java - 如何使用扫描仪让用户输入这段代码
问题描述
我可以让程序将预设值添加到 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");
}
}
}
解决方案
就个人而言,我会坚持单一的用户体验方法。如果要使用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);
...
请注意,扫描器输入也存在相同的输入验证约束。
推荐阅读
- amazon-web-services - NoSuchKey:指定的键不存在。同时推送放大graphql API
- regex - 正则表达式搜索包含多个字符串的文件
- php - 如何通过 WooCommerce 添加自定义帖子 ID 添加到购物车?
- azure - 如何使用 Azure 认知搜索进行分面搜索?
- c++ - 这是一个纸牌游戏,我有一个括号括起来的错误
- flutter - 按钮单击添加从 API 获取的下拉小部件
- assembly - 什么自写的 asm 不匹配 bochs
- google-chrome - 如何找到已经在 Chrome 中加载的页面的 HTTP 状态代码?
- ubuntu-18.04 - MicroStack 未启动:命令“snapctl start microstack.nginx”返回非零退出状态 1
- javascript - 如何按日期范围和交付状态过滤 json 数据