In: Computer Science
Write a program that concatenates the characters in a
two-dimensional into a set of Strings in a
one-dimensional array as described below.
main
#Request and Read in the number of rows of a two dimensional
array.
#Create the reference to the two-dimensional array.
For each row
#Request and Reads in a line of text
#Based on the length of the line create a row with the correct
number of columns (look
#back to lesson 3)
#Place each character for the String into the row, one character at
a time.
#Call concatenateColumnsPerRow with a reference to the character
two-dimensional array as a
#reference. The return will be a reference to a one-dimensional
String array.
#Call displayArray with a reference to the one-dimensional
StringArray.
concatenateColumnsPerRow
#Accepts a character two-dimensional array reference as
input.
#Concatenates the elements in each row into a String.
#Returns a one-dimensional String array, with the Strings from each
row placed into the
#corresponding row in the String array.
displayArray
#Accepts the one-dimensional String array and prints out the
Strings on separate lines
import java.util.Scanner;
public class MultiDimensionalArrayConcater {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//Request and Read in the number of rows of a two dimensional array.
System.out.printf("Enter number of rows: ");
int rows = scanner.nextInt();
//Create the reference to the two-dimensional array
char[][] arr = new char[rows][];
for (int i = 0; i < rows; i++) {
//Request and Reads in a line of text
System.out.printf("Enter line: ");
String word = scanner.next();
//Based on the length of the line create a row with the correct number of columns
arr[i] = new char[word.length()];
for (int j = 0; j < word.length(); j++) {
//Place each character for the String into the row, one character at a time
arr[i][j] = word.charAt(j);
}
}
//Call concatenateColumnsPerRow with a reference to the character two-dimensional array as a
//reference.
String[] result = concatenateColumnsPerRow(arr);
//Call displayArray with a reference to the one-dimensional StringArray
displayArray(result);
}
//Accepts a character two-dimensional array reference as input.Concatenates the elements in each row into a String
//Returns a one-dimensional String array, with the Strings from each row placed into the corresponding row in the String array
public static String[] concatenateColumnsPerRow(char[][] arr) {
String[] result = new String[arr.length];
for (int i = 0; i < arr.length; i++) {
String word = "";
//Creating word of a row
for (int j = 0; j < arr[i].length; j++) {
word += (arr[i][j]);
}
//adding to result
result[i] = word;
}
return result;
}
//Accepts the one-dimensional String array and prints out the Strings on separate lines
public static void displayArray(String[] arr) {
System.out.println();
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
|
![]() |