Coolunized5
Coolunized5

Reputation: 35

How do I use characters from a method to an array in the main class?

I'm new to programming, so I probably have some mistakes in formatting and other things.

How do I get the characters, '#' and '.' from my method, checkInt, to my arrays? When I run the code, it prints out the random integer values but not the transformed ones. (#, .)

import java.util.Scanner;
import java.util.Random;

public class maze {

    public static void main(String[] args) {
        int[] row1;
        int[] row2;
        int[] row3;
        int[] row4;
        int[] row5;

        //set values to arrays
        row1 = new int[5];
        row2 = new int[5];
        row3 = new int[5];
        row4 = new int[5];
        row5 = new int[5];

        for (int i = 0; i < 5; i++) {
            row1[i] = checkInt();
            row2[i] = checkInt();
            row3[i] = checkInt();
            row4[i] = checkInt();
            row5[i] = checkInt();
        }
        System.out.println(java.util.Arrays.toString(row1));
        System.out.println(java.util.Arrays.toString(row2));
        System.out.println(java.util.Arrays.toString(row3));
        System.out.println(java.util.Arrays.toString(row4));
        System.out.println(java.util.Arrays.toString(row5));
    }
    public static int checkInt() {
        Random rand1 = new Random();
        int value = rand1.nextInt(100);
        if (value >= 65) {
            System.out.println("#");
        }   else {
            System.out.println(".");
        }
        return value;
    }
}

Upvotes: 0

Views: 29

Answers (1)

David Ehrmann
David Ehrmann

Reputation: 7576

You should change your arrays to be char arrays

 char[] row1 = new char[5];`

and checkInt() to return a char rather than just printing it:

public static char checkInt() {
    Random rand1 = new Random(); 
    int value = rand1.nextInt(100); 
    if (value >= 65) {
        // Note that these are single quotes because it's a char, not a String
        return '#';
    }   else {
        return '.';
    }
}

Wouldn't hurt to rename checkInt() while you're at it. It isn't really checking an int. There's a joke that there are two hard problems in computer science: cache invalidation and naming things.

Upvotes: 1

Related Questions