0

Java program problem

Hi! I'm learning java for about 2 months and I tried to do a quiz from a file. I tried hard, but now I don't know what did I wrong and what should I do. The file (notepad) quiz has first line to question, four next lines are the answers and next line is a correct answer. That's like 3 times. Yes, I know, my code is really "dirty", but I've scarcely started we can say. Thanks in advance and there is the code: import java.util.LinkedList; import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; import java.util.Iterator; public class Main { public static void main(String[] args) throws FileNotFoundException { String fileName = "C:\\Users\\patry\\Desktop\\scanner.txt"; File textFile = new File(fileName); Scanner in = new Scanner(textFile); int counter = 0; int points = 0; Scanner scan = new Scanner(System.in); LinkedList<String> answers = new LinkedList<>(); LinkedList<String> correctAnswers= new LinkedList<>(); while(in.hasNextLine()){ String line = in.nextLine(); System.out.println(line); if(counter == 4|| counter == 10 || counter == 16){ System.out.print("Your answer: "); answers.add(scan.next()); in.nextLine(); counter++; } if(counter == 5|| counter == 11 || counter == 17) correctAnswers.add(line); counter++; } Iterator<String> it = answers.iterator(); Iterator<String> it1 = correctAnswers.iterator(); while(it.hasNext()){ if(it.next().equals(it1.next())) points++; } System.out.println("U've got "+ points + " point(s)! Congratulations!"); } } P.S. This code almost works, but It just chooses the answer 'd' everytime as a correct answer, the file looks like it: Question1 a b c d b Question2 a b c

1st Jul 2018, 10:11 PM
Patryk
2 Réponses
+ 2
In your first if statement: if(counter==4... the line, in.nextLine(); is not saved into the variable line for use in the next if statement. You could remove that line and just do; correctAnswers.add(in.nextLine()); There may be more, but that is what I can see at first glance.
2nd Jul 2018, 3:48 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
I dont try to read a similar code... Exist an useful feature like 'Code Playground' section... Use it (Save your code in that section and post his link here)
1st Jul 2018, 10:28 PM
KrOW
KrOW - avatar