代码的逻辑有什么问题?

时间:2015-02-11 04:50:44

标签: java arrays java.util.scanner

代码的逻辑有什么问题?有两种方法: readAllExams 创建并返回对象数组,并调用另一个返回对象的方法 readExam 。传递的Scanner对象是一个文本文件,其中包含10行不同的人名,ID,期中考试或期末考试,以及分数,例如:John McGregor 2'F'100。那么我在这里做错了什么?这个方法给出了这样的结论: [LEXam; @ 717da562 。提前谢谢,伙计们!

public static void main(String [] args) throws FileNotFoundException
    {
        Scanner data = new Scanner(new File("Exam.txt"));
        Exam[] tempObject = readAllExams(data);
        System.out.println(tempObject);


    }

    public static Exam[] readAllExams(Scanner s) throws ArrayIndexOutOfBoundsException
    {
        readExam(s);
        String firstName = "";
        String lastName = "";
        int ID = 0;
        String examType = "";
        int score = 0;

        int index = 0;

        Exam[] object = new Exam[50];

        while(s.hasNext())
        {
            //Returns firtsName and lastName 
            firstName = s.next();
            lastName = s.next();

            //Returns ID number
            if(s.hasNextInt())
            {
                ID = s.nextInt();
            }
            else 
                s.next();

            //Returns examType which is 'M' or 'F'
            examType = s.next();

            if(s.hasNextInt())
            {
                score = s.nextInt();
            }

            object[index] = new Exam(firstName, lastName, ID, examType, score);
            System.out.println();
            index++;
        }
        return object;


    }

    public static Exam readExam(Scanner s)
    {
        String firstName = "";
        String lastName = "";
        int ID = 0;
        String examType = "";
        int score = 0;

        while (s.hasNext())
        {
            //Returns firtsName and lastName 
            firstName = s.next();
            lastName = s.next();

            //Returns ID number
            if(s.hasNextInt())
            {
                ID = s.nextInt();
            }
            else 
                s.next();

            //Returns examType which is 'M' or 'F'
            examType = s.next();

            if(s.hasNextInt())
            {
                score = s.nextInt();
            }
        }
        Exam temp = new Exam(firstName, lastName, ID, examType, score);
        return temp;
    }

1 个答案:

答案 0 :(得分:0)

默认情况下,您在Exam数组中调用toString,这就是您所看到的。您需要关注:

  • 在Exam中实现toString方法以打印firstName,Id,lastName,examType

    public String toString() {
        return "id:" + ID + " fname: " + firstName; 
    }
    
  • 将您的System.out.println(tempObject);更改为System.out.println(Arrays.toString(tempObject));这将在内部调用数组中每个Exam对象的toString,并以可读的格式打印检查数组。