2016-12-30 1 views
1

Привет, ребята, я пытаюсь создать массив типа Вопрос, но я думаю, что у меня есть проблема при подсчете вопросов в текстовом файле, текстовый файл имеет строку, затем пустая строка, то другая линия, то пустая строка и так ... и я получаю сообщение об ошибке:Попытка чтения файла по строкам в Java

Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Unknown Source) at Question.countQuestions(Question.java:27) at Question.readAllQuestions(Question.java:44) at test.main(test.java:7)

пример текстового файла:

enter link description here

вот мой код:

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

public class Question { 
private String q; private String a; 
private String b; private String c; 
private String d; private String cA; 

public Question(String q, String a, String b, String c, String d, String cA) { 
    this.q = q; this.a = a; 
    this.b = b; this.c = c; 
    this.d = d; this.cA = cA; 
} 

private static int countQuestions() throws FileNotFoundException{ 
    int counter = 0; 
    Scanner file = new Scanner (new File("testBank.txt")); 
    while(file.hasNextLine()){ 
     // check if line empty 
     String text = file.nextLine(); 
     while(!text.equals("")){ 
      file.nextLine(); 
     } 
     file.nextLine(); 
     file.nextLine(); 
     file.nextLine(); 
     file.nextLine(); 
     file.nextLine(); 
     file.nextLine(); 
     file.nextLine(); 
     file.nextLine(); 
     file.nextLine(); 
     file.nextLine(); 

     counter++; 
    } 
    return counter; 
} 

public static Question[] readAllQuestions() throws FileNotFoundException{ 
    int numberOfQuestions = countQuestions(); 
    Question [] allQuestions = new Question[numberOfQuestions]; 
    Scanner file = new Scanner (new File("testBank.txt")); 
    for (int i = 0 ; i < allQuestions.length ; i++){ 
     String text = file.nextLine(); 
     String q = ""; 
     while(!text.equals("")){ 
      q += file.nextLine(); 
     } 
     String a=file.nextLine(); 
     file.nextLine(); 
     String b=file.nextLine(); 
     file.nextLine(); 
     String c=file.nextLine(); 
     file.nextLine(); 
     String d=file.nextLine(); 
     file.nextLine(); 
     String cA=file.nextLine(); 
     file.nextLine(); 
     Question question = new Question(q,a,b,c,d,cA); 
     allQuestions[i] = question; 
    } 
    return allQuestions; 
} 
+0

Внутри внутренний 'while' петли вы не обновляя' Text', но вы используете его в условие цикла, поэтому результат оценки состояния будет не меняются во время цикла, который будет либо циклически навсегда, либо даже не один раз, в зависимости от того, какое значение имеет значение 'text' перед входом в цикл. – SantiBailors

ответ

1

Надеюсь, это поможет ..!

Чтобы избежать Exception в потоке "основного" java.util.NoSuchElementException: Нет линии не нашел применение

while(text.equals(" ")) 
{ 
    file.nextLine(); 
} 

вместо

while(!text.equals("")) 
{ 
    file.nextLine(); 
} 

и написать свой код в try..catch блока, например.

private static int countQuestions() throws FileNotFoundException{ 
    int counter = 0; 
    Scanner file = new Scanner (new File("testBank.txt")); 
    while(file.hasNextLine()){ 
     try 
     { 
      // check if line empty 
      String text = file.nextLine(); 

      while(text.equals(" ")){ 
        file.nextLine(); 
      } 
      file.nextLine(); 
      file.nextLine(); 
      file.nextLine(); 
      file.nextLine(); 
      file.nextLine(); 
      file.nextLine(); 
      file.nextLine(); 
      file.nextLine(); 
      file.nextLine(); 
      file.nextLine(); 

      counter++; 
     } 
     catch(NoSuchElementException e) 
     { 
      //Found End of File 
     } 
    } 
    return counter; 
} 

Проверить это один

public static Question[] readAllQuestions() throws FileNotFoundException 
{ 
    int numberOfQuestions = countQuestions(); 
    Question [] allQuestions = new Question[numberOfQuestions]; 
    Scanner file = new Scanner (new File("testBank.txt")); 
    try 
    {  
     for (int i = 0 ; i < allQuestions.length ; i++) 
     { 
      String text = file.nextLine(); 
      String q = ""; 
      while(text.equals(" ")){ 
       file.nextLine(); 
      } 
      q += text; 
      file.nextLine(); 
      String a=file.nextLine(); 
      file.nextLine(); 
      String b=file.nextLine(); 
      file.nextLine(); 
      String c=file.nextLine(); 
      file.nextLine(); 
      String d=file.nextLine(); 
      file.nextLine(); 
      String cA=file.nextLine(); 
      file.nextLine(); 
      Question question = new Question(q,a,b,c,d,cA); 
      allQuestions[i] = question; 
     } 
    } 
    catch(NoSuchElementException e) 
    { 
     //Found End of File 
    } 
    return allQuestions; 
} 
+0

же проблема Исключение в потоке "основного" java.util.NoSuchElementException: Нет линии не найдено \t на java.util.Scanner.nextLine (Unknown Source) \t на Question.countQuestions (Question.java:32) \t на вопрос. readAllQuestions (Question.java:44) \t at test.main (test.java:7) – Ammar

+0

Пожалуйста, отметьте его как принятый. Если он решил вашу проблему .. !!! – Pradnyarani

+0

Это сработало, но я столкнулся с другой проблемой при попытке присвоить переменные для вопросов и ответов во втором методе readAllQuestions() – Ammar

0

В приведенном ниже коде вы звоните file.nextLine() без проверки, если он имеет следующую строку. Кроме того, если я не ошибаюсь, вы можете вызвать его один раз только внутри цикла.

private static int countQuestions() throws FileNotFoundException{ 
int counter = 0; 
Scanner file = new Scanner (new File("testBank.txt")); 
while(file.hasNextLine()){ 
    // check if line empty 
    String text = file.nextLine(); 
    while(!text.equals("")){ 
     file.nextLine(); // no check if new line exist 
    } 
    file.nextLine(); 
    file.nextLine(); 
    file.nextLine(); 
    file.nextLine(); 
    file.nextLine(); 
    file.nextLine(); 
    file.nextLine(); 
    file.nextLine(); 
    file.nextLine(); 
    file.nextLine(); 

    counter++; 
} 

Используйте ниже код вместо

while(file.hasNextLine()){ 
    // check if line empty 
    String text = file.nextLine(); 
    while(!text.equals(" ")){ 
     counter++; 
    }  
} 
Смежные вопросы