2015-12-07 2 views
0

Я работаю над проектом, в котором у меня есть текстовый файл с первой строкой, размером с массив, который мне понадобится, а затем последующие строки содержат информацию о курсе в следующем порядке: dept, num, title. (например, CSC 101 Basic Computing) Мой код соответствует, но когда он запускает первый индекс в массиве, становится по умолчанию (т. е. ничего), и поэтому последняя строка в текстовом файле не сохраняется или не печатается. Мне интересно, как я могу исправить эту ошибку.Создание массива объектов в java с использованием классов

import java.util.Scanner; 
import java.io.*; 

public class Organizer { 

    public static void main(String[] args) { 
     Scanner fileScanner = null; 
     String file; 
     File f = null; 

     //Create a Do While loop in order to prompt the user for a input file 
     //and then continue prompting if the file entered does not exist. 

     do { 
      try { 

       System.out.print("What is the name of the input file? "); 
       Scanner inputReader = new Scanner(System.in); 
       file = inputReader.nextLine(); 
       f = new File(file); 
       fileScanner = new Scanner(new File(file)); 

       //Catch the exception and tell the user to try again 
      } catch (FileNotFoundException e) { 

       System.out.println("Error scanning that file, please try again."); 

      } 
     } while (!f.exists()); 

     //Testing the Make Array Method 
     //System.out.print(makeArray(fileScanner)); 

     //Testing the print Array Method 
     printArray(makeArray(fileScanner)); 

    } 

    public static Course[] makeArray(Scanner s) { 

     int arraySize = s.nextInt(); 
     String title = ""; 
     String dept = ""; 
     int num = 0; 
     Course[] a = new Course[arraySize]; 
     for (int i = 0; i < a.length; i++) { 

      a[i] = new Course(dept, num, title); 
      String oneLine = s.nextLine(); 
      Scanner lineReader = new Scanner(oneLine); 
      while (lineReader.hasNext()) { 

       dept = lineReader.next(); 
       a[i].setDept(dept); 
       num = lineReader.nextInt(); 
       a[i].setNum(num); 
       while (lineReader.hasNext()) { 
        title = title + lineReader.next() + " "; 
       } 
       a[i].setTitle(title); 
      } 
      title = " "; 
     } 
     return a; 
    } 


    public static void printArray(Course[] arr) { 

     for (int i = 0; i < arr.length; i++) { 

      System.out.println(arr[i].toString()); 
     } 
    } 
} 

Это мой другой класс.

public static class Course { 

    //INSTANCE VARIABLES 
    private String dept = ""; 
    private int num = 0; 
    private String title = ""; 

    //CONSTRUCTORS 
    public Course(String dept, int num) { 
     this.dept = dept; 
     this.num = num; 
    } 

    public Course(String dept, int num, String title) { 
     this.dept = dept; 
     this.num = num; 
     this.title = title; 
    } 

    public Course() { 
     this.dept = "AAA"; 
     this.num = 100; 
     this.title = "A course"; 
    } 

    //SETTER AND GETTER METHODS 
    public void setDept(String dept) { 
     this.dept = dept; 
    } 

    public void setNum(int num) { 
     this.num = num; 
    } 

    public void setTitle(String title) { 
     this.title = title; 
    } 

    public String getDept() { 
     return this.dept; 
    } 

    public int getNum() { 
     return this.num; 
    } 

    public String getTitle() { 
     return this.title; 
    } 

    //TOSTRING METHOD 
    public String toString() { 
     return dept + " " + num + ": " + title; 
    } 
} 

ответ

0

Не забудьте, где находится ваш курсор в вашем Сканере в каждый момент. s.nextLine() будет читать всю строку, а затем курсор перейдет к следующей строке, а s.nextInt() будет читать один int из вашей строки, а затем останется там. Он не будет проверять, был ли это последний вход для этой строки.

Просто исправить код:

int arraySize = s.nextInt(); 
s.nextLine(); 

и ваш код должен работать нормально!

(также рассмотреть вопрос об изменении a[i].setTitle(title); к a[i].setTitle(title.trim());, так как вы всегда будете оставаться с белым пространством в конце своей книги ..)

+0

Отлично! Спасибо! – Cara

0

метод nextInt не потребляет символ новой строки. Вот решение, которое работает:

public static Course[] makeArray(Scanner s){ 

    int arraySize = s.nextInt(); 
    String title = ""; 
    String dept = ""; 
    int num = 0; 
    Course[] a = new Course[arraySize]; 
    s.nextLine(); 
    for (int i = 0; i < a.length; i++){ 

     a[i] = new Course(dept, num, title); 
      String oneLine = s.nextLine(); 
      Scanner lineReader = new Scanner(oneLine); 

      while (lineReader.hasNext()){ 

       dept = lineReader.next(); 
       a[i].setDept(dept); 
       num = lineReader.nextInt(); 
       a[i].setNum(num); 
       while (lineReader.hasNext()){ 
        title = title + lineReader.next() + " "; 
       } 
       a[i].setTitle(title); 
      } 
      title = " "; 
    } 
return a; 

}

Смежные вопросы