如果我正确理解你的意图,你正在尝试读入一个整数,确认它大于0,然后以降序将这个数字中的所有数字打印到1。
如果是这种情况,问题在于你的while循环的位置。 for循环的条件是userInput> = i。您为i指定了1的值。鉴于此,如果userInput < = 0(您对while循环的条件),则for循环内的代码将永远不会执行(因为userInput> = i,或等价地userInput> = 1永远不会)。修正将是你之前移动while语句for循环,使其:
String stringSeries = "";
int userInput = userInput = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive number to evaluate"));
while (userInput <= 0)
{
userInput = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter a valid number"));
}
for (int i = 1; userInput >= i; userInput--)
{
stringSeries +=userInput+ ", ";
}
System.out.println(stringSeries);
的结构和成语几点意见:在你的作业第二userInput是不必要的。通常在for循环中,我(您的迭代变量)是要更改的值。这样做的一个更地道的办法是:
String stringSeries = "";
int userInput = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive number to evaluate"));
while (userInput <= 0)
{
userInput = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter a valid number"));
}
for (int i = userInput; i >= 1; i--)
{
stringSeries += i+ ", ";
}
System.out.println(stringSeries);
如果你想使用while循环一做,代码将是:
String stringSeries = "";
int userInput;
do {
userInput = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter a valid number"));
} while(userInput <= 0);
for (int i = userInput; i >= 1; i--)
{
stringSeries += i+ ", ";
}
System.out.println(stringSeries);
我们应该如何知道你在尝试做什么? – The111 2015-02-12 05:01:58
请提供您想要做的事情。只是写它的不工作不会让我们明白你想要执行什么 – 2015-02-12 05:03:13
好吧,用户输入一个正数,代码从该数字变为1.例如,用户输入一个8,所以它走8,7,6 ,5,4,3,2,1 – fredy21 2015-02-12 05:03:47