In: Computer Science
Write a java method that creates a two dimensional char array after asking the user to input a String text and String key consisting of integers only, such that
int rows=(int)Math.ceil(text.length()/key.length()); // or int rows=(int)Math.ceil(text.length()/key.length()); ?
int columns= key.length();
int remainder= text.length() % key.length(); // such that the last row avoids taking an index beyond the string text by making columns - remainder
The method fills the 2d array with letters a String entered by the use (row by row). The method then shifts the columns of the array based on key.
After changing the columns, the method returns a String of all the characters in the 2d array but written column by column.
text = Sara;
key= 312
For example, the initial 2d array is
S | A | R |
A |
transformed into
R | S | A |
A |
The final retuned string is RSAA
Code with comments
import java.util.Scanner;
class Temp {
static void print(char[][] arr) { // print char array as grid
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
static void fun() {
Scanner sc = new Scanner(System.in);
String text = sc.nextLine();// input text
String key = sc.nextLine();// input key
sc.close();
int cols = key.length();
int rows = text.length() / cols;
int rem = text.length() % cols;
char[][] arr = new char[rows + 1][cols];// extra row for remainder
for (int i = 0; i < rows; i++) {// fill row by row
for (int j = 0; j < cols; j++) {// fill col by col
arr[i][j] = text.charAt(cols * i + j);
}
}
int j = 0;
for (; j < rem; j++)// fill remainder
arr[rows][j] = text.charAt(cols * rows + j);
for (; j < cols; j++)// fikl zeros
arr[rows][j] = 0;
print(arr);
String res = "";
for (int i = 0; i < key.length(); i++) {
int c = key.charAt(i) - '1'; // get column
for (j = 0; j <= rows; j++) { // all rows of that column
res += (arr[j][c] != 0 ? arr[j][c] : "");
}
}
System.out.println(res);
}
public static void main(String[] args) {
fun();
}
}