繁体   English   中英

“ For”循环停止正常工作(或者我做错了什么)

[英]“For”-loop ceases to work properly (or I'm doing something wrong)

因此,这里的问题非常简单; 我有一个“ for”循环,无法正常工作。 “ for”循环位于“ generateBlock()”方法中第二个类的末尾。 应该使用此“ for”循环将标签的文本从数组labels []更改为“文本已更改”。

我遇到的问题是,如果我设置为“ for(i = 0; i < 12 ; i ++);”,则会出现出站错误,如果我设置为“ for(i = 0; i < 11 ; i ++)”,则会遇到出站错误。 ;“,我没有出站错误。 这很奇怪,因为数组的索引实际上由0到11组成。但是,这甚至不是主要问题。

主要问题是,如果我设置“ for(i = 0; i <11; i ++);”,则只有最后一个标签[i](因此标签[11])的文本更改为“文本更改”,而另一个标签[i]都保持不变,因此保持不变。

因为i <11,所以这很奇怪,因此label [11]应该是唯一保持不变的标签,但是在这种情况下,它显然是相反的,我不知道为什么。 我还不知道如果将i设置为<12,为什么会出现出站错误,因为我非常确定数组的索引由0到11组成。

如果我手动设置“ coloredWords.labels [0] .setText(“文本已更改”);“ 然后将其复制并粘贴到它确实起作用的所有其他值。

public class ColoredWordsExperiment {
    JFrame frame;
    JLabel[] labels;
    ButtonHandler buttonHandler;
    int i;

    ColoredWordsExperiment(){
        frame = new JFrame ();
        button1 = new JButton("Matching");

        labels = new JLabel[12];
        for (i = 0; i < 12; i++) {
            labels[i] = new JLabel("label");
            labelContainer.add(labels[i]);
        }

        buttonHandler = new ButtonHandler(this);
        button1.addActionListener(buttonHandler);
    }

    public static void main(String[] arg) {
        new ColoredWordsExperiment():
    }

}

-

class ButtonHandler implements ActionListener {
    ColoredWordsExperiment coloredWords;
    public ButtonHandler(ColoredWordsExperiment coloredWords) {
        this.coloredWords = coloredWords;
    }

    @Override
    public void actionPerformed(ActionEvent e){
        if (e.getActionCommand().equals("Matching")) {
            generateBlock();
        }
    }

    public void generateBlock(){
        int i = 0;
        for (i = 0; i < 11; i++); {
            coloredWords.labels[i].setText("Text changed");
        }
    }

}

您的for循环甚至不会执行一次,因为您已经用分号( ; )终止了它。 在for循环后删除分号:

    for (i = 0; i < 11; i++); {

应该

    for (i = 0; i < 11; i++) {

首先,您的for循环正在终止

for( i = 0 ; i  < 11 ; i ++); // replace this line with

for( i =0; i <11; i++){

//您的逻辑}

第二件事,如果您想将最后一个标签[11]更改为“ Text Changed”,请将此条件放入for循环中-

If( i ==11){
    coloreWords.labels[i].set text("Text Changed");

}但是,您应该仔细检查数组索引,如果它确实是一个11索引数组,则代码应运行到i <12。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM