2014-10-12 5 views
1

У меня возникли проблемы с пониманием того, как разбирать текстовые документы с неизвестным количеством «учеников». Все мои решения странствуют, и у меня проблемы со Сканером. Разбирая входные данные, первое целое число показывает, сколько классов есть, первая строка - это имя класса, следующие учащиеся с соответствующими датами и переменными, которые необходимо сохранить вместе со студентом, с неизвестным количеством студентов. Я хочу, чтобы хранить каждый студент вместе с классом они находятся вКак я должен анализировать это на Java?

Мой код очень грязный и запутанной до сих пор:.

String filename = "input.txt"; 
    File file = new File(filename); 
    Scanner sc = new Scanner(file); 
    Student[] studArr = new Student[100]; 
    int studCounter = 0; 
    boolean breaker = false; 
    boolean firstRun = true; 
    int numClasses = sc.nextInt(); 
    System.out.println(numClasses); 


    while(sc.hasNextLine()){ 
     String className = sc.nextLine(); 
     System.out.println("Name: " + className); 
     String test = null; 
     breaker = false; 
     sc.nextLine(); 

     // Breaks the while loop when a new class is found 
     while (breaker == false){ 
      Student temp = null; 

      // Boolean to tell when the first run of the loop 
      if (firstRun == true){ 
       temp.name = sc.nextLine(); 
      } 

      else 
       temp.name = test; 

      System.out.println(temp.name); 

      temp.date = sc.nextLine(); 

      if (temp.date.isEmpty()){ 
       System.out.println("shit is empty yo"); 
      } 

      temp.timeSpent = sc.nextInt(); 
      temp.videosWatched = sc.nextInt(); 
      temp.className = className; 
      studArr[studCounter] = temp; 
      studCounter++; 
      sc.nextLine(); 
      test = sc.nextLine(); 
      firstRun = false; 
     } 
    } 
} 
} 

class Student { 
    public String name; 
    public String date; 
    public String className; 
    public int timeSpent; 
    public int videosWatched; 
} 

мне не нужен точный ответ, но я должен искать в другой инструмент, а затем сканер? Есть ли способ, который я могу исследовать?

Спасибо за любую помощь.

+2

У вас проблема, описанная здесь http://stackoverflow.com/questions/13102045/skipping-nextline-after-use-nextint. Также 'if (firstRun == true)' не лучший стиль кодирования (очень легко ошибиться, как 'if (firstRun = true)'). Лучше просто написать 'if (firstRun)' – Pshemo

ответ

1

я придумал следующее решение. Сканер - прекрасный инструмент для работы. Трудная часть состоит в том, что вам нужно посмотреть вперед, чтобы увидеть, есть ли у вас пустая строка или дата, чтобы узнать, есть ли у вас студент или класс.

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.ArrayList; 
import java.util.Scanner; 

public class Parser { 

    private static String nextLine(Scanner sc) { 
    String line; 
    while (sc.hasNext()) { 
     if (!(line = sc.nextLine()).isEmpty()) { 
     return line; 
     } 
    } 
    return null; 
    } 

    public static ArrayList<Student>[] parseFile(String fileName) { 
    File file = new File(fileName); 
    try (Scanner sc = new Scanner(file)) { 
     int numClasses = sc.nextInt(); 
     String className = nextLine(sc); 
     ArrayList<Student>[] classList = new ArrayList[numClasses]; 
     for (int i = 0; i < numClasses; i++) { 
     classList[i] = new ArrayList<>(); 
     while (true) { 
      String studentOrClassName = nextLine(sc); 
      if (studentOrClassName == null) { 
      break; 
      } 
      String dateOrBlankLine = sc.nextLine(); 
      if (dateOrBlankLine.isEmpty()) { 
      className = studentOrClassName; 
      break; 
      } 
      int timeSpent = sc.nextInt(); 
      int videosWatched = sc.nextInt(); 
      classList[i].add(new Student(className, dateOrBlankLine, studentOrClassName, timeSpent, 
       videosWatched)); 
     } 
     } 
     return classList; 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 
    return new ArrayList[0]; 
    } 

    public static void main(String[] args) { 
    for (ArrayList<Student> students : parseFile("classList.txt")) { 
     if (!students.isEmpty()) { 
     System.out.println(students.get(0).className); 
     } 
     for (Student student : students) { 
     System.out.println(student); 
     } 
    } 
    } 

    static class Student { 

    public String className; 
    public String date; 
    public String name; 
    public int timeSpent; 
    public int videosWatched; 


    public Student(String className, String date, String name, int timeSpent, 
     int videosWatched) { 
     this.className = className; 
     this.date = date; 
     this.name = name; 
     this.timeSpent = timeSpent; 
     this.videosWatched = videosWatched; 
    } 

    public String toString() { 
     return name + '\n' + date + '\n' + timeSpent + '\n' + videosWatched + '\n'; 
    } 
    } 
} 
+0

Вау! Огромное спасибо. Я просмотрю это, но я уже могу сказать, что он меня многому научит. – RJones

1

Задайте себе вопрос: что делает Студент? Имя, дата, номер и номер. Так что вы хотите сделать следующее (не фактический код) (. Формат, написанный на Lua код, очень понятно Это означает, что это не будет работать в Lua: P)

if line is not empty then 
    if followingLine is date then 
     parseStudent() // also skips the lines etc 
    else 
     parseClass() // also skips lines 
    end 
end 
+0

Спасибо, это очень помогло. – RJones

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