【问题标题】:How to Iterate through a 2D array step by step using a button?如何使用按钮逐步迭代二维数组?
【发布时间】:2018-12-29 11:35:37
【问题描述】:

在 android 中按下按钮后,我必须逐步迭代 2D 循环,比如说

3 4 3 4 5 4 2 3 4

输出应该是:

After Button pressed:3 After Button pressed:4 After Button pressed:3 ....... ....... After Button pressed:4

我应该如何在循环中使用 clicklistener?

【问题讨论】:

    标签: android arrays for-loop iteration


    【解决方案1】:

    试试这样:

    public class Main extends AppCompatActivity {
    int[][] array = new int[][]{
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
    };
    
    int rows = 0;
    int columns = 0;
    TextView textView;
    
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textView = (TextView) findViewById(R.id.text);
    
    
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
    
                if (columns < array[rows].length) {
                    textView.setText("After Button pressed: " + array[rows][columns]);
                    columns++;
                } else {
                    rows++;
                    if (rows != array.length) {
                        columns = 0;
                        textView.setText("After Button pressed: " + array[rows][columns]);
                        columns++;
                    } else {
                        rows = 0;
                        columns = 0;
                    }
                }
            }
        });
    }
    

    【讨论】:

    • 按预期工作。我正在考虑使用两个 for 循环,这让我很困惑
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 2012-10-22
    • 2011-12-28
    • 2015-04-04
    • 2014-05-30
    • 2020-06-09
    相关资源
    最近更新 更多