Write a java program that takes an input string, converts each character of the
ID: 3798611 • Letter: W
Question
Write a java program that takes an input string, converts each character of the string to a hexidecimal value, and stores it in a 2-dimensional array (matrix). The 2-dimensional array must be of size 4x4. Within the program, create a method that repeatedly takes an input string length of 16 and prints out a 4x4 array (each 4x4 array separated by a space) until the input string is completely converted an stored in an array (this case would occur if the input string length is greater than 16). Array must be filled in a column by column order. Any remaining space in the array should be filled with a substitution character, resulting in a padded matrix. Input starts with a desired substituion character, next line is followed by the input string.
Example input 1:
~
Hola
Example output 1:
48 20 7E
6F 7E 7E
6C 7E 7E
61 7E 7E
Example input 2:
0
Een goede naam is beter.
Example output 2:
45 67 65 61
65 6F 20 6D
6E 65 6E 20
20 64 61 69
(space)
73 74 30 30
20 75 30 30
62 72 30 30
65 2E 30 30
Explanation / Answer
The examples given by you does not match the problem description.
The input string should be of size 16 only and no spaces between them.
CODE:
import java.util.Scanner;
public class ToHex {
public static void main(String[] args){
// Scanner class to get the input from the user.
Scanner sc = new Scanner(System.in);
// read from the console.
String st = sc.next();
// declare array of size 16 to hold the output.
String[] hexarray = new String[16];
// iterate through the input and convert it to HEX.
for (int i=0;i<st.length();i++){
String hex = String.format("%4x", (int) st.charAt(i));
hexarray[i] = hex;
}
// display the output.
for(int i=0;i<hexarray.length;){
System.out.println(hexarray[i] + " " + hexarray[i+1] + " " + hexarray[i+2] + " " + hexarray[i+3]);
i += 4;
}
System.out.println();
sc.close();
}
}
OUTPUT:
Eengoedenaamisbe
45 65 6e 67
6f 65 64 65
6e 61 61 6d
69 73 62 65
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.