【发布时间】:2015-08-01 13:46:39
【问题描述】:
我在创建一个包含构造函数的学生类时遇到问题,该构造函数采用格式为“Brookes 00918 X12 X14 X16 X21”的扫描仪字符串。条件应该是应该有学生姓名和学号,课程代码应该以“X”开头。如果他们不满意,我已经抛出了IncorrectFormatExceptions。但是,当我创建一个测试类并输入一个字符串并按 enter 时,例如 "abc 123" 它不会产生通常情况下的输出。
更新:我已将代码更改为使用字符串数组标记,但是现在使用使用“123 abc X12”的 toString() 方法会给出空指针异常。当我在构造函数中放入“123 abc”时它可以工作
更新:现在好像可以工作了忘记初始化arrayList
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Student extends UniversityPerson{
private String studentNumber="";
private List<String> courses=new ArrayList<String>();
private String studentName="";
public int checkNoofletters(char[] chararray){
int noofletters=0;
for (char c:chararray){
if (Character.isLetter(c)){
noofletters++;
}
}
return noofletters;
}
public String courseListinStr(){
String stringo="";
for (String c:courses){
stringo+=c;
stringo+=" ";
}
return stringo;
}
public Student(Scanner scanner) throws IncorrectFormatException{
int studentNumberCount=0;
int studentNameCount=0;
Scanner s=scanner;
String input=s.nextLine();
String[] tokens=input.split("\\s");
for (int i=0; i<tokens.length; i++){
char[] chars=tokens[i].toCharArray();
if (checkNoofletters(chars)==chars.length){//if the number of letters is equal to the character length
if (studentNameCount==1){throw new IncorrectFormatException("Can only have 1 student name");}
studentNameCount++;
this.studentName=tokens[i];
continue;
}
if (tokens[i].matches("[0-9]+")){//add to the studentNumbers list
if (studentNumberCount==1){throw new IncorrectFormatException("Can only have 1 student number");}
studentNumberCount++;
this.studentNumber=tokens[i];
continue;
}
if (!tokens[i].startsWith("X")){
throw new IncorrectFormatException("Course code must start with an 'X'");
}
System.out.println(tokens[i]);
courses.add(tokens[i]);
}
if (studentNumber=="" || studentName==""){
throw new IncorrectFormatException("Must have 1 student Number and Student Name");
}
}
@Override
public String toString() {
//return String.format("%s %s", studentName,courseListinStr());
return String.format("Student: %s %s", studentName,studentNumber);
}
@Override
public boolean equals(Object o) {
// TODO Auto-generated method stub
return false;
}
}
【问题讨论】:
标签: java