我可以获取将预设值添加到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");
}
}
}
答案 0 :(得分:0)
就个人而言,我将采用单一的用户体验方法。如果要使用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
注释中指出的错误消息是因为Java Scanner
带有大写字母。不知道那是什么。
但是,如果要使用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);
...
请注意,扫描程序输入也存在相同的输入验证约束。