繁体   English   中英

使用 JOptionPane 在 Java 中执行 while 循环

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM