有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java forloop逻辑的问题

我很难理解为什么我的for循环没有按我希望的那样运行。我循环的目的是在GUI上添加多个文本字段,确切地说是70。7号线,10号线。它可以很好地添加字段,但比我想要的短一行和一列。这似乎是足够的信息来确定问题,但我不能,所以我来到这里

        for(int i = 0; i < 6; i++){
            for(int j = 0; j < 9; j++){
                OT2Field[i][j] = new JTextField();
                OT1Field[i][j] = new JTextField();
                STField[i][j] = new JTextField();
            }
        }

        int xPointer = 3;
        int yPointer = 7;
        for(int i = 0; i < 6; i++){
            for(int j = 0; j < 9; j++){
                addTimeFieldBorder0010(option3, OT2Field[i][j], gridbag, gbc, xPointer, yPointer, 1, 1, 0);
                yPointer = yPointer + 3;
            }
            xPointer++;
            yPointer = 7;
        }


    }

    private void addTimeFieldBorder0010(JComponent container, JComponent component, 
            GridBagLayout gridbag, GridBagConstraints gbc,
            int x, int y, int height, int width, double weightx) {
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.gridheight = height;
        gbc.gridwidth = width;
        gbc.weightx = weightx;
        ((JTextField) component).setHorizontalAlignment(JLabel.CENTER);
        component.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.red));
        component.setFont(component.getFont().deriveFont(18.0f));
        component.setForeground(Color.red);
        component.setBackground(Color.YELLOW);
        gridbag.setConstraints(component, gbc);


        container.add(component, gbc);
     }

共 (5) 个答案

  1. # 1 楼答案

    根据Java Language Specification §15.20.1报告

    • The value produced by the < operator is true if the value of the left-hand operand is less than the value of the right-hand operand, and otherwise is false.

    所以你从i = 0开始循环,而i小于6。当它小于7或小于或等于6时,需要循环。这同样适用于下一个循环

    将两个循环更改为:

    for(int i = 0; i < 7; i++){
        for(int j = 0; j < 10; j++){
            //stuff
        }
    }
    
  2. # 2 楼答案

    for(int i = 0; i <= 6; i++){
        for(int j = 0; j <= 9; j++)
    
  3. # 3 楼答案

    你的循环应该是

    for(int i = 0; i < 7; i++)
    {
       for(int j = 0; j < 10; j++)
       {
    
           //your code
       }
    }
    
  4. # 4 楼答案

    外部循环仅在0到5之间执行,内部循环仅在0到8之间执行。将循环更改为

    for(int i = 0; i < 7; i++){
            for(int j = 0; j < 10; j++){
                OT2Field[i][j] = new JTextField();
                OT1Field[i][j] = new JTextField();
                STField[i][j] = new JTextField();
            }
        }
    

    当左边的值等于右边的值时,<符号返回false。因此,对于i=6i<6返回false,因此缺少一次迭代

  5. # 5 楼答案

    您正在0 to 5for loop i0 to 8for loop j之间循环。 这就是它短停一行一列的原因。 您应按以下方式更改它们:

    for(int i = 0; i <= 6; i++){
      for(int j = 0; j <= 9; j++){
        ...
      }
    }
    

    for(int i = 0; i < 7; i++){
      for(int j = 0; j < 10; j++){
        ...
      }
    }