【发布时间】:2014-05-12 10:54:11
【问题描述】:
我问这个听起来很傻,但是我的 for 循环有问题。
这是我遇到问题的部分代码。
Scanner input = new Scanner( System.in);
int number;
for(int i = 0;i < 5;i++) {
System.out.print("Enter 5 integers:");
number = input.nextInt();
}
当我运行它时,打印输出循环超过 5 次。
public class BarGraph extends JPanel
{
public void paintComponent( Graphics g )
{
Scanner input = new Scanner( System.in);
// super.paintComponent(g);
int number;
for(int i = 0;i < 5;i++)
{
System.out.print("Enter 5 integers:");
number = input.nextInt();
// g.drawRect(10 * i, 10 * i, 100 * number, 10);
}
}
}
运行条形图测试
public class BarGraphTest
{
public static void main( String[] args)
{
BarGraph panel = new BarGraph();
JFrame application = new JFrame();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
application.add( panel );
application.setSize( 300, 300);
application.setVisible( true );
}
}
基本上我想要做的是读取 5 个整数,然后将它们显示在 JPanel 上的条形图上。
【问题讨论】:
-
罪魁祸首是
input.nextInt();。请改用input.nextLine();。 -
比 5 多多少次?
-
它应该只运行 5 次(如果您不键入整数值作为输入,则应该运行更少)。你确定你发布的代码吗?
-
如果我运行您的代码,则循环将执行 5 次。
-
paintComponent 由 swing "when it needs to be" 调用,在这种情况下,它似乎需要 2 次重绘。出于这种原因,我个人不会像这样混淆图形和逻辑