79393185

Date: 2025-01-28 08:54:27
Score: 1.5
Natty:
Report link

I am not writing the cleaner code for you. Why not? Because you will learn more from writing it yourself after you have read the suggestions. (Moderators and some users don’t like the purpose of leaving out code being stated. So this piece of information risks getting deleted.)

My suggestions are:

  1. Declare constants: Extract constants, for example RANDOM_GENERATOR, NUMBER_OF_ROWS, NUMBER_OF_COLUMNS, HEADER_LETTERS and BOUND_EXCLUSIVE = 2 (the number that you pass to ran.nextInt().

  2. Methods: As @Anonymous says in a comment, divide into methods. Have one method for generating the random number, one for constructing the 2D array and one for printing it. When I print tables in plain text I also often write a method for printing one row that I use for printing the header row and for each content row; but I don’t think it is worth it here.

  3. Loops or streams: As others have said, there are good ways to avoid the 12 lines with repeated calls to nextInt() and the variables coming out them for which no 12 good names exist. For me I would start with the idea from @DuncG, use Arrays.setAll() for filling each row. It combines fine with a method for generating the random numbers as I suggested. You also need a loop or stream operation to generate all the rows. In the cases where the array already exists prefer an enhanced for loop over a loop with an index:

    for (int[] row : array) {
        // Process inner array
    }
    
  4. String joiner: Since the advent of string joiners I have found them elegant for generating a printed row with spaces between the elements and without a space at the end.

    • For the header letters: String.join(" ", letter)

    • For each content row:

        Arrays.stream(row)
               .mapToObj(Integer::toString)
               .collect(Collectors.joining(" "));
      
Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Unregistered user (0.5):
  • User mentioned (1): @Anonymous
  • User mentioned (0): @DuncG
  • Low reputation (1):
Posted by: Ane De Jong