[英]Do while loop in Java using JOptionPane
我试图构建一个程序来确定它是负数还是正数,到目前为止它很好,但似乎我的代码没有读取负数,只有正数,我找不到它有什么问题。
import javax.swing.JOptionPane;
public class EYYY {
public static void main(String[] args) {
int positive=0;
int negative=0;
int num=0;
int loop = 1;
while(loop<=5){
Integer.parseInt(JOptionPane.showInputDialog("Enter a number: "));
if(num<0)
negative++;
if(num>=0)
positive++;
loop++;
}
JOptionPane.showMessageDialog(null,"Negative numbers in the program: " + negative + "\nPositive numbers in the program: " + positive);
}
}
num=0;
导致num
值始终为零和正数,但您需要在while-loop
的每次迭代中将JOptionPane
的输入值存储在num
变量中,以检查新输入值的负数或正数:
num = Integer.parseInt(JOptionPane.showInputDialog("Enter a number: "));
完整代码:
int positive = 0;
int negative = 0;
int num = 0;
int loop = 1;
while (loop <= 5) {
num = Integer.parseInt(JOptionPane.showInputDialog("Enter a number: "));
if (num < 0)
negative++;
if (num >= 0)
positive++;
loop++;
}
JOptionPane.showMessageDialog(null,
"Negative numbers in the program: " + negative + "\nPositive numbers in the program: " + positive);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.