简体   繁体   English

这种方法究竟发生了什么?

[英]what exactly happens in this method?

I want to make a method which returns an array of buttons containing the letter of them . 我想做一个方法来返回包含它们的字母的按钮数组。 I wrote the method but I'm not sure what exactly happens? 我写了这个方法,但是我不确定到底会发生什么?

public JButton [] button(){
    JButton [] button = null ;
    for(int i = 0 ;i<26 ;i++){
        String letter  = String.valueOf((char)(i + 'A'));
        button[i] = new JButton(letter);
    }
    return  button() ;
}

Create the array first as following 首先创建数组,如下所示

JButton [] button = new JButton[26];  // see null is removed.

and return properly 并正确返回

return button; // removed paranthesis

You are calling the method recursively and indefinitely: 您正在递归且无限期地调用该方法:

return button() ;

That should be: 应该是:

return button;

Best would be avoiding naming methods and variables confusingly. 最好避免混淆地命名方法和变量。 Also, you'll need to initialize the button array properly: 另外,您需要正确初始化按钮数组:

JButton[] button = new JButton[26];

You will get a NullPointerException because your array is not initialised: 您将收到NullPointerException,因为您的数组未初始化:

JButton [] button = new JButton[26];

And at your return statement you call the method again which will cause an infinite loop. 然后在您的return语句中再次调用该方法,这将导致无限循环。

return button; // removed paranthesis

This will return the array you create in the loop. 这将返回您在循环中创建的数组。

Your code should look like this: 您的代码应如下所示:

public JButton [] button(){
    JButton [] button = new JButton[26];
    for(int i = 0 ;i<26 ;i++){
        String letter  = String.valueOf((char)(i + 'A'));
        buttons[i] = new JButton(letter);
    }
    return button;
}

To your question what the code does: 您的问题代码是做什么的:

It creates an array of JButtons labeled with one letter from A to Z 它创建一个JButton数组,标有从AZ一个字母

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

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