2014-08-11 2 views
0

Я пытаюсь создать программу, которая в основном является виртуальными notecards. Каждый notecard имеет строку для вопроса и ответа, а также счет, который теперь много раз задан. Во многих случаях я использую сканер, и я думаю, что использую его неправильно, и я не совсем уверен, почему. Программа позволит мне ответить на первые 2 вопроса, скажите, что они неправильны, что бы ни случилось, и пропустите, позвольте мне ответить на последний вопрос. Вот класс NoteCard:Проблемы с сканированием Java, Notecard class

public class Notecard { 

    public String ans; 
    public String q; 
    public int count; 

    public Notecard(String q, String ans) { 
     this.q = q; 
     this.ans = ans; 
     this.count = 0; 
    } 

    public Boolean answer(String effort) { 
     if (this.q.toUpperCase().equals(effort.toUpperCase())) { 
      System.out.println("Correct!"); 
      return true; 
     } else { 
      System.out.println("Incorrect! Correct answer:" + this.ans); 
      count++; 
      return false; 
     } 
    } 

    public void clearCount() { 
     this.count = 0; 
    } 

    public String getQ() { 
     return this.q; 
    } 
} 

и вот мой другой файл:

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.Collections; 
import java.util.Random; 
import java.util.Scanner; 

public class CreateNotecard { 

    int trys; 

    public static void main(String[] args) { 
     System.out.println("Get ready to be quizzed \n\n"); 
     ArrayList<Notecard> notecards = makeCards(); 
     quiz(notecards); 
    } 

    static ArrayList<Notecard> makeCards() { 
     ArrayList<Notecard> notecards = new ArrayList<Notecard>(); 
     try { 
      BufferedReader in = new BufferedReader(new FileReader(
        "notecards.txt")); 
      String str; 
      str = in.readLine(); 
      while ((str = in.readLine()) != null) { 
       String[] argg = str.split(","); 
       notecards.add(new Notecard(argg[0], argg[1])); 
      } 
      in.close(); 
     } catch (IOException e) { 
      System.out.println("File Read Error"); 
     } 
     return notecards; 
    } 

    static void quiz(ArrayList<Notecard> notecards) { 
     ArrayList<Notecard> backupList = notecards; 
     Scanner sc = new Scanner(System.in); 
     long seed = System.nanoTime(); 
     Collections.shuffle(notecards, new Random(seed)); 
     int total = notecards.size(); 
     int correct = 0; 
     for (Notecard x : notecards) { 
      System.out.println(x.getQ()); 
      String effort = sc.next(); 
      Boolean nailedIt = x.answer(effort); 
      if (nailedIt) { 

       correct++; 
      } 
     } 
     System.out.println("Total Notecards: " + total + "\nTotal Correct: " 
       + correct); 
     System.out.println("Accuracy: " + (correct/total)); 
     System.out.println("Do you want to repeat? Put \"y\" or \"n\""); 
     String choice1 = sc.nextLine(); 
     if (choice1.toUpperCase().equals("Y")) { 
      System.out.println("Use only cards missed or all? Type \"missed\" or \"all\""); 
      String choice2 = sc.nextLine(); 
      if (choice2.toUpperCase().equals("MISSED")) { 
       quiz(notecards); 
      } else { 
       quiz(backupList); 
      } 
     } else { 
      return; 
     } 

    } 

} 

У меня есть текстовый файл, который я использую для этой программы, она содержит

19-9,10 
square root of 4,2 
capitol of Missouri,Jefferson City 
Blastoise's 1st evolution,squirtle 

и мой выпуск

Get ready to be quizzed 


square root of 4 
2 
Incorrect! Correct answer:2 
capitol of Missouri 
Jefferson City 
Incorrect! Correct answer:Jefferson City 
Blastoise's 1st evolution 
Incorrect! Correct answer:squirtle 
Total Notecards: 3 
Total Correct: 0 
Accuracy: 0 
Do you want to repeat? Put "y" or "n" 
+0

В вашем методе ответа, вы уверены, что вы хотите сравнить вопрос и усилий или ответа и усилий? – nbro

+0

omg спасибо, что поймал это. – user3516302

+0

No problem dude;) – nbro

ответ

2

Вы сравниваете неправильные вещи:

public Boolean answer(String effort) { 
    if (this.q.toUpperCase().equals(effort.toUpperCase())) { 

Должен быть

if (this.ans.toUpperCase().equals(effort.toUpperCase())) { 
1

проблема в том, что класс Scanner ищет разделитель для создания жетонов с, по умолчанию whitespace. Поскольку вы вводите «2», Scanner.next() не находит разделителей, поэтому нет токенов.

Например, если вы введете «Jefferson City», то Scanner нашел один разделитель, поэтому два жетона. sc.next в этом случае будет только «Jefferson» (нет «City», это следующий токен).

Решение? Прочитайте строки из стандартного ввода и использование sc.nextLine()

+0

Будет ли NextLine лучше выбирать? – user3516302

+0

Правильно, я должен был уточнить. nextLine должен решить вашу проблему. – Hypino

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