简体   繁体   中英

Is there a way to initialize a 2d array with other arrays?

I have been given a homework assignment as follows:

Read three sentences from the console application. Each sentence should not exceed 80 characters. Then, copy each character in each input sentence in a [3 x 80] character array.

The first sentence should be loaded into the first row in the reverse order of characters – for example, “mary had a little lamb” should be loaded into the array as “bmal elttil a dah yram”.

The second sentence should be loaded into the second row in the reverse order of words – for example, “mary had a little lamb” should be loaded into the array as “lamb little a had mary”.

The third sentence should be loaded into the third row where if the index of the array is divisible by 5, then the corresponding character is replaced by the letter 'z' – for example, “mary had a little lamb” should be loaded into the array as “mary zad azlittze lazb” – that is, characters in index positions 5, 10, 15, and 20 were replaced by 'z'. Note that an empty space is also a character, and that the index starts from position 0.

Now print the contents of the character array on the console.

The methods, return types, and parameters in the code below are all specified as required so I cannot change any of that information. I am having trouble initializing the 2d array. The instructions say that the sentences must be loaded into the array already reversed etc. but the parameters of the methods for doing this calls for strings. I assume that means I should read the lines as strings and then call the methods to modify them, then use toCharyArray to convert them before loading them into the 2d array. I don't understand how to initialize the 2D array with the values of the char arrays. Is there some kind of for loop I can use? Another issue is that no processing can be done inside of the main method but in the instructions there is no method that I can call to fill the array.

import java.util.regex.Pattern;


public class ReversedSentence {

    public static String change5thPosition(String s){
        char[] chars = s.toCharArray();
        for (int i = 5; i < s.length(); i = i + 5) {
            chars[i] = 'z';
        }
        String newString = new String(chars);
        return newString;
    }

    public static String printChar2DArray(char[][] arr){
        for (int x = 0; x < 3; x++) {
            for (int y = 0; y < 80; y++) {
                // just a print so it does not make new lines for every char
                System.out.print(arr[x][y]);
            }

        }
        return null;
    }

    public static String reverseByCharacter(String s){
        String reverse = new StringBuffer(s).reverse().toString();
        return reverse;
    }


    public static String reverseByWord(String s){
        Pattern pattern = Pattern.compile("\\s"); //splitting the string whenever there
        String[] temp = pattern.split(s);  //  is whitespace and store in temp array.
        String result = "";
        for (int i = 0; i < temp.length; i++) {
            if (i == temp.length - 1)
                result = temp[i] + result;
            else
                result = " " + temp[i] + result;
        }
        return result;
    }

    public static String truncateSentence(String s){
        if (s==null || s.length() <= 80)
            return s;

        int space = s.lastIndexOf(' ', 80);
        if (space < 0)
            return s.substring(0, 80);

        return s;
    }


    public static void main(String[] args) {

        String sentence1 = ("No one was available, so I went to the movies alone.");
        String sentence2 = "Ever since I started working out, I am so tired.";
        String sentence3 = "I have two dogs and they are both equally cute.";


        char[][] arr = new char[3][80];
        arr[0] = reverseByCharacter(sentence1).toCharArray();
        arr[1] = reverseByWord(sentence2).toCharArray();
        arr[2] = change5thPosition(sentence3).toCharArray();


        printChar2DArray(arr);
    }
}

The error I am getting is:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 52 out of bounds for length 52   
at ReversedSentence.printChar2DArray(ReversedSentence.java:20)  
at ReversedSentence.main(ReversedSentence.java:71)

.enola seivom eht ot tnew I os,elbaliava saw eno oN

The problem is that in your printChar2DArray method you assume that every array has the length of 80, but that's actually not the case here. In Java, a 2D array is just an array of arrays. So, when you have this: char[][] arr = new char[3][80] , you are creating an array of 3 arrays, and each of these arrays has the length of 80 characters. That may seem ok, but in the next lines you reinitialize the 3 arrays with something different entirely.

arr[0] = reverseByCharacter(sentence1).toCharArray();
arr[1] = reverseByWord(sentence2).toCharArray();
arr[2] = change5thPosition(sentence3).toCharArray();

Now none of these arrays has the length of 80. Each of them has the length of the respective string.

You can solve this in 2 ways (depending on how constrained your task actually is).

First, you can copy the string into arrays, instead of assigning the arrays to the results of the toCharArray method. You can achieve this with a simple loop, but I wouldn't recommend this approach, because you will end up with arrays of 80 characters, even if the strings contain less.

String firstSentence = reverseByCharacter(sentence1);
for (int i = 0; i < firstSentence.length(); i++) {
    arr[0][i] = firstSentence.charAt(i);
}

Or:

char[] firstSentence = reverseByCharacter(sentence1).toCharArray();
for (int i = 0; i < firstSentence.length; i++) {
    arr[0][i] = firstSentence[i];
}

Second, you can drop the assumption of the arrays' lengths in the printChar2DArray method. I recommend this approach, because it makes you code much more flexible. Your printChar2DArray method will then look like this:

public static String printChar2DArray(char[][] arr){
    for (int x = 0; x < arr.length; x++) {
        for (int y = 0; y < arr[x].length; y++) {
            // just a print so it does not make new lines for every char
            System.out.print(arr[x][y]);
        }
    }
    return null;
}

You can see that I've substituted numbers with the length field, which can be accessed for any array.

Also, this way you don't need to initialize the inner arrays, because you reinitialize them in the next lines anyway.

char[][] arr = new char[3][];
arr[0] = reverseByCharacter(sentence1).toCharArray();
arr[1] = reverseByWord(sentence2).toCharArray();
arr[2] = change5thPosition(sentence3).toCharArray();

But this approach may not be suitable for your task, because then the sentences could be of any length, and they wouldn't be constained to 80 characters max.

UPDATE - To answer the question in the comment

To print a newline character you can use System.out.println() without parameters. It's better than putting the newline character into the arrays because it's not a logical part of the sentences.

So your for -loop in the printChar2DArray would look like this:

for (int x = 0; x < 3; x++) {
    for (int y = 0; y < 80; y++) {
        // just a print so it does not make new lines for every char
        System.out.print(arr[x][y]);
    }
    System.out.println();
}

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