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