【问题标题】:Why is my code running the for loop more than 5 times? [closed]为什么我的代码运行 for 循环超过 5 次? [关闭]
【发布时间】: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 次重绘。出于这种原因,我个人不会像这样混淆图形和逻辑

标签: java for-loop


【解决方案1】:

您将状态更改与图形混为一谈。 paintComponent 由 swing "when it needs to be" 调用,在这种情况下,无论出于何种原因,Swing 确定它需要重新绘制 2 次。

如果您的程序是以关心何时或多久调用一次paintComponent 的方式编写的,那么您可能会遇到问题。相反,您应该只让paintComponent 询问某些对象的当前状态并相应地进行绘制。

根据您的具体情况,应通过以下方式之一提供 5 个数字

  • 传递给 BarGraph 的构造函数
  • 用户在 BarGraph 的构造函数中请求(不是我最喜欢的,但可以工作)
  • 传递给 BarGraph 的方法
  • 位于传递给 BarGraph 的其他对象中。

绝对不应该向paintComponent 中的用户请求它们,这意味着每次重绘都是必需的(例如移动、调整大小、更改焦点、被其他帧隐藏等),数字将被重新- 来自用户的请求。

您也可能希望以super.paintComponent(g) 开始您的paintComponent 方法,但will again be situation dependant

【讨论】:

    猜你喜欢
    • 2022-01-16
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 1970-01-01
    相关资源
    最近更新 更多