【发布时间】:2015-10-01 19:40:55
【问题描述】:
使用代码时
else if(command.equalsIgnoreCase("add")) {
System.out.println("Enter the Student's Name: ");
String name = input.nextLine();
System.out.println("Enter the Student's Number: ");
String studNum = input.nextLine();
System.out.println("Enter the Student's Address: ");
String address = input.nextLine();
langara.addStudent(name, address, studNum);
System.out.println("A Student added to the College Directory");
}
如果用户输入add,则假设经过上述过程,在拼贴类(langara)中有一个“addStudent”方法:
public void addStudent(String name, String address, String iD) {
Student firstYear = new Student(name, address, iD);
collegeStudents.add(firstYear);
}
这会使用构造函数创建学生类的学生对象:
public Student(String name, String address, String iD) {
long actualId = Long.parseLong(iD);
studentName = name;
studentID = actualId;
studentAddress = new Address(address);
numberOfQuizzes = 0;
scoreTotal = 0;
}
我收到了错误:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Abernathy, C."
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:589)
at java.lang.Long.parseLong(Long.java:631)
at Student.<init>(Student.java:48)
at College.addStudent(College.java:33)
at CollegeTester.main(CollegeTester.java:53)
就好像它正在尝试将学生姓名转换为长名称,但它应该将学生 ID 转换为长名称..
这是创建扫描仪、创建学院和初始化命令的地方:
Scanner input = new Scanner(System.in);
College langara = new College();
String command = "";
System.out.print("College Directory Commands:\n" +
"add - Add a new Student\n" +
"find - Find a Student\n" +
"addQuiz - Add a quiz score for a student\n" +
"findHighest - Find a student with the highest quiz score\n" +
"delete - Delete a Student\n" +
"quit - Quit\n");
command = input.nextLine();
输入是从 input.txt 文件中读取的,每个输入都在自己的行中。 该命令在文件开头的输入是:
add
Abernathy, C.
10010123
100, West 49 Ave, Vancouver, BC, V7X2K6
这里出了什么问题?
【问题讨论】:
-
文本文件的行顺序是什么?它应该是姓名、ID、地址,因为您在此订单上阅读过!
-
您确定文本文件的顺序正确吗?
-
@WajdyEssam 是的,它的顺序是正确的,我用 input.txt 文件中的格式示例更新了帖子
-
我们需要知道
command是什么,它来自哪里以及input是什么。看起来add是作为名称而不是命令读入的。 -
尝试打印
name的值并告诉我们打印的内容。
标签: java string class number-formatting