所以我制作了一个单独的程序,打印出输入数字(限制)以内的所有素数。它工作得很好,但是当我将代码添加到 GUI 代码中时,它只显示最后一个素数。例如,我输入 9,它只显示 7,因为这是 9 之前的最后一个质数。显然,GUI 代码搞乱了 for 循环,我不知道如何修复它。这是在文本区域中显示答案的代码(位于我的程序的底部)(代码的其他部分只是设置 GUI)。请帮忙!
public void actionPerformed(ActionEvent event){
//turns the inputNum text into type int and parsed into int input
//iterates through each number
for(){
//prints the primes that returned true in the isPrime method ONLY
if(isPrime(num)){
}
}
}
public static boolean checkForPrime(int num){
//for loop that checks if the inputed number is prime
最佳答案
不要在 JTextArea 上调用 setText(...)
,因为这会用新文本替换 JTextArea 中的当前文本。而是在 JTextArea 上调用 append(myText + "\n");
,以便创建新行,每行都有新答案的副本。
例如,
if(checkForPrime(num)){
// assuming that answers is a JTextArea
answers.append(String.valueOf(num) + "\n");
}
append方法会将传入的字符串添加到已经显示在文本中 JTextArea。
关于Java GUI不会显示for循环中的所有答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30339181/