我是Java编程的初学者,我在while循环上有一个任务。
分配是打开窗口,显示数字1-10。
前两个,我下来了。第三个是让用户输入数字'x',下一个窗口是使用while循环显示1和'x'之间的所有整数。
正如我现在编写的那样,每个循环迭代在一个窗口中弹出它自己的窗口而不是一次全部。
TL; DR我希望有一个带10个循环的窗口,而不是10个窗口,每个窗口有1个循环。
JOptionPane和while循环在他们给我们的讲义和笔记中,但没有提到如何组合它们。
import javax.swing.JOptionPane;
public class Pr27
{
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10");
JOptionPane.showMessageDialog(null, "1 2 3 4 5 6 7 8 9 10");
String text;
text=JOptionPane.showInputDialog("Please enter a number: ");
int f,x;
f=0;
x=Integer.parseInt(text);
while (f<=x)
{//What am I doing wrong between here
JOptionPane.showMessageDialog(null, f);
f++;
}//and here?
}
}
答案 0 :(得分:1)
我相信您希望在单个DialogBox中打印出x中小于或等于f的所有数字,而不是每次循环迭代。
import javax.swing.JOptionPane;
public class Pr27
{
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10");
JOptionPane.showMessageDialog(null, "1 2 3 4 5 6 7 8 9 10");
String text;
text = JOptionPane.showInputDialog("Please enter a number: ");
int f, x;
//if you wish to loop from 1 to x then f must start at 1 and not 0 because in your loop you print out f before it increases thus it would be 0.
f = 1;
x = Integer.parseInt(text);
StringBuilder sb = new StringBuilder();
while (f <= x)
{
//rather than show a message dialog every iteration append f and a new line to a StringBuilder for later use.
sb.append(f).append("\n");
//JOptionPane.showMessageDialog(null, f);
f++;
}
//string builder has a "\n" at the end so lets get rid of it by getting a substring
String out = sb.substring(0, sb.length() - 1);
JOptionPane.showMessageDialog(null, out);
}
}