[英]Why is my program not cycling through the array
我已經嘗試了一些代碼安排,這是我的最新版本。 我正在嘗試創建一個窗口,該窗口將循環瀏覽我的5個問題,最后將顯示您有多少個正確答案。
目前,在文本字段中輸入我的第一個答案后,它跳到數組的末尾。 之后,它將繼續停留在同一問題上。
抱歉,我犯了很多編碼錯誤,因為這是我看了很多教程后第一次創建程序。 謝謝你的幫助!
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class testwin extends JFrame {
private JTextField input;
private JLabel problem;
private String[] questions = new String[5];
private String[] answers = new String[5];
private String[] response = new String[5];
private int total = 5;
private int result = 0;
private String mark;
public testwin(){
super("Pop Quiz");
setLayout(new FlowLayout());
questions[0] = "Solve for x \t (x + 3)*2-10 = 4";
questions[1] = "Factorize \t x^2 + 10x + 21";
questions[2] = "Find the square root of 64";
questions[3] = "Multiply 23 and 94";
questions[4] = "Add 2145, 1452, 253,1414";
answers[0] = "4";
answers[1] = "(x + 3)(x + 7)";
answers[2] = "8";
answers[3] = "2162";
answers[4] = "5264";
problem = new JLabel(questions[0]);
add(problem);
input = new JTextField("Answer goes here",20);
add(input);
mark = String.format("You got %s correct out of %s", result,total);
input.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
int y = 0;
int x = 0;
if(event.getSource() == input){
while(x < questions.length){
problem.setText(questions[x]);
response[y] = String.format("%s",event.getActionCommand());
input.setText("Answer goes here");
x++;
y++;
}
}
if(x == 4)
JOptionPane.showMessageDialog(null, mark);
for(int z = 0; z < questions.length; z++){
if(response[z] == answers[z])
result++;
}
}
}
);
add(input);
setSize(250,250);
setVisible(true);
}
}
在每個actionPerformed調用期間,您將循環瀏覽整個列表。 這里:
while(x < questions.length){
problem.setText(questions[x]);
response[y] = String.format("%s",event.getActionCommand());
input.setText("Answer goes here");
x++;
y++;
}
因此,在再次實際顯示文本時,您已經將其設置為每個不同的問題,但是從最后一個問題開始,這就是用戶實際看到的內容。 每次執行操作時,您只想將文本更改為下一個問題。
您需要保留某種計數器,您可以針對該問題使用actionPerformed
方法訪問
另外,如評論中所述,您將想要更改結果檢查以使用equals方法。 不能使用==
符號來比較字符串,因為對於Strings ==
比較每個String
對象指向的引用,而不是String
對象的值
if(response[z].equals(answers[z]))
result++;
問題是ActionListener中的while()循環,它將始終遍歷整個問題集並在最后一個條目處完成。 這是因為您的x和y變量在ActionListener的作用域內是局部的,因此,始終將其重置為0並在每次輸入單擊時循環。
要解決此問題,您不需要while循環,只需將x變量設置為私有類字段(questionIndex),使用if語句確保索引在數組范圍內,並相應地更新問題和響應值。
這是一些應該做正確的事情的偽代碼:
private int questionIndex = 0;
public void actionPerformed(ActionEvent event){
if(event.getSource() == input){
if(questionIndex < questions.length){
problem.setText(questions[questionIndex]);
response[questionIndex] = String.format("%s",event.getActionCommand());
input.setText("Answer goes here");
questionIndex++;
}
...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.