2014-10-04 31 views
1

对于我的科学博览会项目,我想给一个法语教学程序提供一个图形更新,这个程序在DosBOX中已经很老了。这一切都很好,但我遇到了问题。我在控制台应用程序中编写程序的基本逻辑,只是为了将它们结合在一起。我创建了一个Question类,它位于数组列表/集合中,名为“test1”。重复一个循环的增量

我有一个列表并在每次迭代迭代,它运行称为另一种方法循环评估:

public static boolean evaluate(Question question, Scanner scanner) 
{ 
    System.out.println(question.getPhrase()); // prints the question 
    String answer = scanner.nextLine(); // gets the answer 
    if (answer.compareTo(question.getCorrectAnswer()) == 0) 
     return true; // compares the answer to the correct answer w/i the current instance of "Question" 
    else 
     return false; // if it's not right, returns "false" meaning the question wasn't correct 
} 

循环看起来这样:

for (Question question : test1) 
    { 
     if (evaluate(question, scan)) 
      { 
       incorrect = 0; 
       continue; 
      } 

     else 
      { 
       incorrect++; 
       System.out.println(incorrect); 
      } 

     if (incorrect == 3) 
      System.out.println("you have failed"); 
      break; 
    } 

我想让它所以如果你错误地回答了一个问题,它会再次吐出这个短语,并将“不正确”加1,​​如果你打3,就终止列表(我想我已经正确实施了,如果我可以重复它问题)。现在它移动到列表中的下一个项目,因此下一个问题即使我不​​想要。

对不起,如果我的代码很糟糕,我还是比较新的编程。

+1

您需要的循环中,您已经在另一个内部循环有,重复当前的问题,直到它被正确回答。 – 2014-10-04 17:50:49

回答

0

而不是做一个foreach循环,你现在正在做的方式,你可以做到以下几点:

for (int i = 0; i < test1.size(); i++) { 
    Question question = test1.get(i); 
    if (evaluate(question, scan)) { 
     ... 
    } else { 
     incorrect++; 
     test1.add(question); 
    } 

    if (incorrect == 3) { ... } 
} 

假设您使用的数据结构使用size()add()作为方法;你可以调整它到你正在使用的。

这将在稍后重复问题,但不会在紧接着之后。如果你想后,立即重复它,只是递减i--else情况:

for (int i = 0; i < test1.size(); i++) { 
    Question question = test1.get(i); 
    if (evaluate(question, scan)) { 
     ... 
    } else { 
     incorrect++; 
     i--; 
    } 

    if (incorrect == 3) { ... } 
} 

还可以嵌套为else情况下一个循环:

for (Question question : test1) { 
    boolean passed = True; 
    incorrect = 0; 
    while (!evaluate(question, scan)) { 
     incorrect++; 
     if (incorrect == 3) { passed = False; break; } 
    } 

    if (!passed) { System.out.println("you have failed"); break; } 
} 
+0

非常感谢!这帮助了很多,解决了我的问题。 :) – JaysusMoon 2014-10-04 20:25:05

1

在for循环内部创建一个while循环,说明如果问题没有被正确回答,那么在每个问题中重复这样的问题直到它的正确值才会问问题。保持里面的一切for循环while循环,你应该:

for (Question question : test1) 
{ 
    while(!evaluate(question, scan)) { 
    if (evaluate(question, scan)) 
     { 
      incorrect = 0; 
      continue; 
     } 

    else 
     { 
      incorrect++; 
      System.out.println(incorrect); 
     } 

    if (incorrect == 3) 
     System.out.println("you have failed"); 
     break; 
} 
} 
+0

这并不像我喜欢的那样工作,但它仍然给我提供了关于将来如何实现类似功能的意见,所以谢谢!我没有这样想过。我知道我需要第二个循环,但并不确定要做什么。 – JaysusMoon 2014-10-04 20:26:09