简体   繁体   中英

Java for loops and 2D arrays

This code should be so simple, yet isn't working at all. It doesn't do anything. To my understanding it should print out a 10 by 10 grid of random numbers below 21.

import java.util.Random;
public class Map {
    static Random rnd = new Random();
    public static int coords[][] = new int[10][10];

    public static void main(String[] args){
        System.out.println("dastardly");
        Map.generate();
        Map.show();
    }

    public static void show() {
        for(int i = 0; i >= 10; i++){
            for(int j = 0; j >= 10; j++){
                System.out.print(coords[i][j]);
            }
            System.out.println("");
        }
    }

    public static void generate() { 
        for(int i = 0; i >= 10; i++){
            for(int j = 0; j >= 10; j++){
                coords[i][j] = rnd.nextInt(21);
            }
        }
    }
}

Can anybody tell me why it doesn't work?

The terminating condition for the loops is wrong:

j >= 10

should be

j < 10

A for loop is composed of three parts:

  • Initialization
  • Condition to enter the loop and continue looping
  • Post action, done after each iteration.

So this loop (and the others too):

for(int i = 0; i >= 10; i++){

is not working and should be changed to:

for(int i = 0; i < 10; i++){

If you have some troubles remembering it, think a for-loop as just a while loop:

int i = 0;
while (i < 10) {
  // instructions
  i++;
}

Change

i >= 10; to i < 10;

and

j >= 10; to j < 10;

Working Code :

Changes :

i >= 10 to i < 10

j >= 10 to j < 10

import java.util.*;
import java.lang.*;
import java.io.*;


class Map 
{
     static Random rnd = new Random();
    public static int coords[][] = new int[10][10];
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println("dastardly");
        Map .generate();
        Map .show();
    }
    public static void show() {
        for(int i = 0; i < 10; i++){
            for(int j = 0; j < 10; j++){
                System.out.print(coords[i][j]);
            }
            System.out.println("");
        }
    }

    public static void generate() { 
        for(int i = 0; i <10; i++){
            for(int j = 0; j < 10; j++){
                coords[i][j] = rnd.nextInt(21);
            }
        }
    }
}

Output :

971756192091315
181318132191661920
100141331158018
66131218111611183
12112141501721516
27361013751614

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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