所以我编写了一个单独的程序,打印出所有质数,直到输入的数字(极限)。它工作得很好,但当我将代码添加到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发布于 2015-05-20 10:31:59
不要在JTextArea上调用setText(...),因为会用新文本替换 JTextArea中的当前文本。取而代之的是在JTextArea上调用append(myText + "\n");,以便创建新的行,每行都有一个新答案的副本。
例如,
if(checkForPrime(num)){
// assuming that answers is a JTextArea
answers.append(String.valueOf(num) + "\n");
}append方法会将传入的字符串添加到JTextArea中已经显示的文本中。
发布于 2015-05-20 10:20:15
您将在每个循环中设置文本。执行以下操作:
if(checkForPrime(num)){
answers.setText(answers.getText(num + " "));//The space separates the numbers and makes it a String
}这将在每次循环时增加数字。
https://stackoverflow.com/questions/30339181
复制相似问题