public class Average {
static Integer[][] myDouble = new Integer[10][12];
static int x = 0, y = 0;
static int strDouble;
public Average() {
try {
BufferedReader in = new BufferedReader(new FileReader("StudentIdAverage.txt"));
String line;
while ((line = in.readLine()) != null) {
String[] values = line.split("\\s+");
for (String str : values) {
strDouble = Integer.parseInt(str);
myDouble[x][y] = strDouble;
y = y + 1;
}
x = x + 1;
y = 0;
}
in.close();
} catch (IOException ioException) {
}
}
public static void main(String[] args) {
Average arr = new Average();
for (int i = 0; i < myDouble.length; ++i) {
IntSummaryStatistics statistics = Arrays.asList(myDouble[i]).stream().filter(intValue -> intValue != null).collect(Collectors.summarizingInt(Integer::intValue));
System.out.println("Average: " + statistics.getAverage() + ", min: " + statistics.getMin() + ", max: " + statistics.getMax());
}
for (int k = 0; k < myDouble.length; ++k) {
int count = 0; // count the values used to calculate sum
double sum = 0;
double average = 0;
for (int j = 0; j < myDouble[k].length; ++j) {
if (myDouble[k][j] == null) //skip the null values
{
continue;
}
//Arrays.sort(myDouble[i]);
sum += myDouble[k][j];
count++;
System.out.print(Average.myDouble[k][j] + " ");
}
average = (sum / count); //use count instead of lenght
System.out.println(" ");
System.out.println(average);
}
}
}
input txt file
45 72 90 50 67 63 81 71 55 56 80 74/n 55 54 79 72 75 68/n 51 88 79 72/n 98 52 52 53 50 92 67 99 92 50 61 91/n 94 48 53 92 97/n 97 69 77 74 68 54 87 74 54 83 58 69/n 75 49 87 61 66 53 79 48 96 60/n 58 71 51 73 53 75 93 81 45 69 78 65/n 50 88 78 81 99 61 97 70 87 80 69/n 91 89 97 80 93 82 92 49 52 69 96 61
Given an array, myDouble[k] of size myDouble[k].length (call it L), dropping the min and max really means ignore the min and max. Since the sum is calculated as average/size, ignore the min and max values.
The sum is in the form newsum + min + max. Obtain the new sum by subtracting min and max from sum: sum -= (min + max).
You can get the min and max manually so you really are using just one for loop. Start min and max at the first non-null entry, and update min and max if the next entry is strictly less or strictly greater than the (candidate) current value, respectively.
The new size will also decrease by two (Beware if size is two or less!). That means, the average excluding min and max is the new sum/(myDouble[k].length - 2).
Simply keep track of the min and max value then substract both value at the end. You don't need to change the rest. This will allow you to get the average value without the need to read the line twice (to remove those values).
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
for (int j = 0; j < myDouble[k].length; ++j) {
if (myDouble[k][j] == null) // skip the null values
{
continue;
}
min = Math.min(myDouble[k][j], min);
max = Math.max(myDouble[k][j], max);
...
}
sum = sum - min - max;
If you can find those value twice, you will need to use a way to count the occurrence of those value. But you get the idea here.
Note that another solution would be to sort the array then skip the first and last value :
double[] sortedArray = Arrays.sort(myDouble[k]);
for (int j = 1; j < sortedArray.length - 1; ++j) {
sum += sortedArray[j];
}
This solution is easier but required more memory, for big list I would not recommend it (but performance is not an issue)
Related
I'm having a hard time getting this to print the way my professor wants. I have tried print, println, \t, and, \n however the results either come out vertically and side by side or each duplicated number next to each other horizontally. This is what my professor wants:
The results (printed twice) are:
14 81 94 91 47 57 98 89 82 15
14 81 94 91 47 57 98 89 82 15
my outputs have consisted of:
The results (printed twice) are:
14 14
81 81
94 94
91 91
47 47
57 57
98 98
89 89
82 82
15 15
The results (printed twice) are:
14 14 81 81 94 94 91 91 47 47 57 57 98 98 89 89 82 82 15 15
The results (printed twice) are:
14 14 81 81 94 94 91 91 47 47 57 57 98 98 89 89 82 82 15 15
This is my code thus far:
System.out.println("The results (printed twice) are:\t");
for (i = 0; i< arr.length; i++){
arr[i] = rand.nextInt(100) + 1;
int[] arrb = arr.clone();
System.out.print(arr[i] + " " + arrb[i] + " ");
Your current code attempts to do 2 things in a single loop:
Generate a new random number.
Print it (twice).
This is never going to work - you need to print the other numbers first, and then 'start over' and print the first number a second time. You can't ask java to 'hop between lines' - standard output is a rather abstract concept. Perhaps its a line printer; you can't ask it to swallow a page it just printed out back into itself and unprint something, for example.
Thus, the answer lies in separating out your tasks. This is usually a good idea for any programming task of any stripe:
Fill an int[] array by generating random numbers.
Print an int[] array - whatever may be inside it.
Do the previous thing twice in a row.
That involves at least 3 for loops, in other words.
int LEN = 100;
int[] numbers = new int[LEN];
for (int i = 0; i < LEN; i++) {
numbers[i] = rnd.nextInt(100) + 1;
}
That's one job done. Don't complicate matters by attempting to also print from there. You're just doing the one job.
Printing one line is easy:
for (int i = 0; i < LEN; i++) {
System.out.print(numbers[i] + " ");
}
System.out.println();
And how do we do things more than once? With.. for loops:
for (int print = 0; print < 2; print++) {
for (int i = 0; i < LEN; i++) {
System.out.print(numbers[i] + " ");
}
System.out.println();
}
Something like this could work:
int[] arr = new int[] { 14,81,94,91,47,57,98,89,82,15 };
System.out.println("The results (printed twice) are:\t");
int counter = 0;
while(counter <= 1) {
for (int i = 0; i< arr.length; i++) {
System.out.print(arr[i] + " ") ;
}
counter++;
System.out.println();
}
Or if you want a nested for loop could also do the work:
int[] arr = new int[] { 14,81,94,91,47,57,98,89,82,15 };
System.out.println("The results (printed twice) are:\t");
for (int i = 0; i <= 1 ; i++){
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[j] + " ") ;
}
System.out.println();
}
And then the output should be:
The results (printed twice) are:
14 81 94 91 47 57 98 89 82 15
14 81 94 91 47 57 98 89 82 15
Basically the logic here is just repeat the printing of the list two times with another for loop or while loop, both works the same way in the examples above, if you have any question you can reply my answer.
Use something like this instead:
System.out.println("The results (printed twice) are:\t");
for (i = 0; i< arr.length; i++){
arr[i] = rand.nextInt(100) + 1;
int[] arrb = arr.clone();
System.out.print(Arrays.toString(arr));
System.out.println();
System.out.print(Arrays.toString(arrb));
Example output:
[1,2,3,4]
[1,2,3,4]
If you want the outout to be 1 2 3 4 instead, use a simple for-loop
for (int i = 0; i<arr.lenght; i++){
System.out.print(arr[i] + " ")
}
System.out.println();
for (int i = 0; i<arrb.lenght; i++){
System.out.print(arrb[i] + " ")
}
There is no need to clone your array.
int[] arr = new int[10];
Random rand = new Random();
System.out.println("The results (printed twice) are:\t");
for (int i = 0; i < arr.length; i++) {
arr[i] = rand.nextInt(100) + 1;
System.out.print(arr[i] + " " + arr[i] + " ");
System.out.println();
}
The result:
The results (printed twice) are:
58 58
31 31
22 22
81 81
36 36
38 38
40 40
9 9
10 10
11 11
Did u try to System.out.println ???
Something like that:
System.out.println("The results (printed twice) are: ");
for (i = 0; i< arr.length; i++){
arr[i] = rand.nextInt(100) + 1;
int[] arrb = arr.clone();
System.out.println(arr[i]);
System.out.println(arrb[i]);
}
Or u can try to make 2D array and fill row[0] with Your arr.
Then fill row [1] with Your arrb
Sample input :
10
100
Sample output :
11,31,41,61,71,101
from the above code I can get the sample output value upto the value 71,how can I get nearest prime number ending with 1 after b.
Here is the code I tried:
import java.util.*;
public class Program{
public static void main(String[] args){
Scanner in=new Scanner(System.in);
int a=in.nextInt();
int b=in.nextInt();
int i,j,count;
for(i=a;i<=b;i++)
{
for(j=2;j<=b;j++)
{
if(i%j==0)
break;
}
if(j==i && j%10==1)
{
System.out.println(i);
}
}
}
You do not need to divide a number by numbers up to it in order to check if it is prime. You just need to check up to its square root. Check https://en.wikipedia.org/wiki/Primality_test. Do it as follows:
Using a for loop
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter two integers separated by space: ");
int a = in.nextInt();
int b = in.nextInt();
int i, j, sqrt;
// Note that there are three sections in the declaration of a 'for' loop:
// for(initialization;condition;change) where none of the sections is
// mandatory. There is no condition put in the loop syntax given below. The
// condition for termination has been put after printing the prime number.
for (i = a;; i++) {
sqrt = (int) Math.sqrt(i);
for (j = 2; j <= sqrt; j++) {
if (i % j == 0) {
break;
}
}
// If the loop with j completed without a break, the number is prime. Note that
// 1 is not a prime number.Also, the last digit of the number should be 1.
if (j > sqrt && Math.abs(i) != 1 && i % 10 == 1) {
System.out.print(i + " "); // Print the prime
if (i >= b) {// Condition for termination
break;
}
}
}
}
}
Alternatively, using a while loop
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter two integers separated by space: ");
int a = in.nextInt();
int b = in.nextInt();
int i = a, j, sqrt;
while (true) {
sqrt = (int) Math.sqrt(i);
for (j = 2; j <= sqrt; j++) {
if (i % j == 0) {
break;
}
}
// If the loop with j completed without a break, the number is prime. Note that
// 1 is not a prime number.Also, the last digit of the number should be 1.
if (j > sqrt && Math.abs(i) != 1 && i % 10 == 1) {
System.out.print(i + " "); // Print the prime
if (i >= b) {// Condition for termination
break;
}
}
i++;
}
}
}
A sample run:
Enter two integers separated by space: 10 100
11 31 41 61 71 101
Another sample run:
Enter two integers separated by space: 10 200
11 31 41 61 71 101 131 151 181 191 211
Add condition in both the for loops like I<= b*2;
After that before printing the series add one more if block or add the condition in if(j==1 && j%10==1)
Condition-
You should have to check what is value of i and whether it's greater than b or not. If it's greater than b then it should be end with 1 and nearer value otherwise no need to print and break it as other values you don't need at all.
I'm assuming you need a prime satisfying these conditions:
within a range (lower to upper)
ending in 1
nearest to a query value
If so, wouldn't the best strategy be to search outwards in both directions (below and above) and stop when you first hit a prime ending in 1?
public static int nearest1Prime(final int lower, final int upper, final int val)
{
if(val < lower || val > upper) return 0;
int before, after;
if((val % 10) == 1)
{
if(isPrime(val))
return val;
before = val - 10;
after = val + 10;
}
else
{
int base = 10 * (val / 10);
if(val == base)
{
after = base+1;
before = after-10;
}
else
{
before = base+1;
after = before+10;
}
}
int prime = 0;
while(prime == 0 && (before >= lower || after <= upper))
{
if(before >= lower && isPrime(before))
prime = before;
if(after <= upper && isPrime(after) && (prime == 0 || (after-val) < (val-before)))
prime = after;
before -= 10;
after -= 10;
}
return prime;
}
public static boolean isPrime(int v)
{
for(int i=(int)Math.sqrt(v); i>1; i--)
{
if((v % i) == 0) return false;
}
return true;
}
Testing:
int lower = 10;
int upper = 100;
for(int i=lower; i<=upper; i++)
{
int prime = nearest1Prime(lower, upper, i);
System.out.println("Nearest Prime: " + i + " : " + prime);
}
Output:
10 : 11
11 : 11
12 : 11
13 : 11
14 : 11
15 : 11
16 : 11
17 : 11
18 : 11
19 : 11
20 : 11
21 : 11
22 : 31
23 : 31
24 : 31
25 : 31
26 : 31
27 : 31
28 : 31
29 : 31
30 : 31
31 : 31
32 : 31
33 : 31
34 : 31
35 : 31
36 : 31
37 : 41
38 : 41
39 : 41
40 : 41
41 : 41
42 : 41
43 : 41
44 : 41
45 : 41
46 : 41
47 : 41
48 : 41
49 : 41
50 : 41
51 : 41
52 : 61
53 : 61
54 : 61
55 : 61
56 : 61
57 : 61
58 : 61
59 : 61
60 : 61
61 : 61
62 : 61
63 : 61
64 : 61
65 : 61
66 : 61
67 : 71
68 : 71
69 : 71
70 : 71
71 : 71
72 : 71
73 : 71
74 : 71
75 : 71
76 : 71
77 : 71
78 : 71
79 : 71
80 : 71
81 : 71
82 : 71
83 : 71
84 : 71
85 : 71
86 : 71
87 : 71
88 : 71
89 : 71
90 : 71
91 : 71
92 : 71
93 : 71
94 : 71
95 : 71
96 : 71
97 : 71
98 : 71
99 : 71
100 : 71
Here's how you can do it, run the first loop indefinitely and break it when i is greater than b and it's a prime with 1 at the end.
This is the implementation just modifying your code a bit-
import java.util.*;
class Program{
public static void main(String[] args){
Scanner in=new Scanner(System.in);
int a=in.nextInt();
int b=in.nextInt();
boolean flag = false;
int i,j,count;
for(i=a;;i++) {
if(i>b) flag = true;
for(j=2;j<=i;j++) {
if(i%j==0)
break;
}
if(j==i && j%10==1) {
System.out.println(i);
if(flag) break;
}
}
}
}
Try this with a few improvements.
first check to see if divisible by 2
then, since 2 is taken care of, divide only by odd numbers
starting with 3, not exceeding the sqrt of the number under test.
then just continue until the search parameter are met.
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int b = in.nextInt();
outer:
for (int i = a; i <= Integer.MAX_VALUE; i++) {
// first check division by 2 so you can increment by 2 later
if (i % 2 == 0) {
continue;
}
// increment from 3 to square root of i by 2's
for (int j = 3; j <= Math.sqrt(i); j+=2) {
if (i % j == 0) {
// not prime so continue with outer loop
continue outer;
}
}
if (i % 10 == 1) {
System.out.print(i + " ");
// keep searching until i > b.
if (i > b) {
break;
}
}
}
for input of 10 100 Prints
11 31 41 61 71 101
so I need help figuring it out why my code is not including the number 2 and it is including number 99 on the prime printed line. Do I need to change something on my findPrime()? I tried playing with the index and just got worse.
class Sieve {
private int max;
private boolean[] numbers;
public Sieve(int max) {
if (max < 2) {
throw new IllegalArgumentException();
}
this.max = max;
numbers = new boolean[max];
numbers[0] = false;
numbers[1] = false;
numbers[2] = true;
for (int i = 2; i < max-1; i++) {
numbers[i] = true;
}
}
public void findPrimes() {
for (int num = 2; num < max-1; num++) {
int multiples = num + num;
while (multiples < max-1) {
numbers[multiples-1] = false;
multiples += num;
}
}
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (int num = 2; num < max; num++) {
if (numbers[num]) {
builder.append(num+1).append(" ");
}
}
return builder.toString();
}
}
class Driver
{
// MAIN. Find some primes.
public static void main(String [] args)
{
Sieve sieve = null; // We must initialize SIEVE or Java will cry.
// 5 points. This must print "Sieve size must be at least 2." but without the
// quotes.
try
{
sieve = new Sieve(0);
}
catch (IllegalArgumentException oops)
{
System.out.println("Sieve size must be at least 2.");
}
// 5 points. This must print nothing.
try
{
sieve = new Sieve(100);
}
catch (IllegalArgumentException oops)
{
System.out.println("Sieve size must be at least 2.");
}
// 10 points. This must print integers from 2 to 99, separated by blanks.
System.out.println(sieve);
// 10 points. This must print the prime numbers between 2 and 99, separated by
// blanks. They are:
//
// 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
sieve.findPrimes();
System.out.println(sieve);
}
}
It is displaying this, instead of having the number 2 at the beginning and not having the number 99 at the last line of the program.
Sieve size must be at least 2.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 99
Your toString() method starts looping at num = 2 (which appends num+1 to the output). Your loop should start at 1.
public String toString() {
StringBuilder builder = new StringBuilder();
for (int num = 1; num < max; num++) { . // used to start at 2
if (numbers[num]) {
builder.append(num+1).append(" ");
}
}
return builder.toString();
}
}
Plus your code sets numbers[1] = false. That should be numbers[1] = true.
You are also looping until < max - 1. Consider looping until < max.
I made a few changes to your code the big things to point out is that you don't need max. Your findPrimes() looks ok but is difficult to read and hard to verify for correctness. Your toString() method should be iterating over every element and if that element is true append it to the list.
also 1 is not prime so numbers[1] = false; is as it should be. Why is 1 not a prime number?
class Sieve {
// private int max; // max is superfluous use numbers.length instead
private boolean[] numbers;
public Sieve(int max) {
if (max < 2) {
throw new IllegalArgumentException();
}
numbers = new boolean[max];
numbers[0] = false;
numbers[1] = false;
numbers[2] = true;
for (int i = 2; i <numbers.length; i++) {
numbers[i] = true;
}
}
public void findPrimes() {
// a bit more compact and neater in my opinion
for (int num=2; num<numbers.length; num++) {
for (int multiple=num+num; multiple<numbers.length; multiple+=num) {
numbers[multiple] = false;
}
}
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
// you should be iterating from 0 to 99
for (int i=0; i<numbers.length; i++) {
if (numbers[i]) {
builder.append(i).append(" ");
}
}
return builder.toString();
}
}
class Driver
{
// MAIN. Find some primes.
public static void main(String [] args)
{
Sieve sieve = null; // We must initialize SIEVE or Java will cry.
// 5 points. This must print "Sieve size must be at least 2." but without the
// quotes.
try
{
sieve = new Sieve(0);
}
catch (IllegalArgumentException oops)
{
System.out.println("Sieve size must be at least 2.");
}
// 5 points. This must print nothing.
try
{
sieve = new Sieve(100);
}
catch (IllegalArgumentException oops)
{
System.out.println("Sieve size must be at least 2.");
}
// 10 points. This must print integers from 2 to 99, separated by blanks.
System.out.println(sieve);
// 10 points. This must print the prime numbers between 2 and 99, separated by
// blanks. They are:
//
// 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
sieve.findPrimes();
System.out.println(sieve);
}
}
public class Average {
static int[][] myDouble = new int[10][12];
static int x = 0, y = 0;
static int strDouble;
public Average() {
try {
BufferedReader in = new BufferedReader(new FileReader("StudentIdAverage.txt"));
String line;
while ((line = in.readLine()) != null) {
String[] values = line.split("\\s+");
for (String str : values) {
strDouble = Integer.parseInt(str);
myDouble[x][y] = strDouble;
y = y + 1;
}
x = x + 1;
y = 0;
}
in.close();
} catch (IOException ioException) {
}
}
public static void main(String[] args) {
Average arr = new Average();
//int[][] residuescores = arr.myDouble;
for (int i = 0; i < myDouble.length; ++i) {
int sum = 0;
int average = 0;
for (int j = 0; j < myDouble[i].length; ++j) {
Arrays.sort(myDouble[i]);
sum+=myDouble[i][j];
System.out.print(Average.myDouble[i][j] + " ");
}
average = (sum/myDouble[i].length);
System.out.println(" ");
System.out.println(average);
}
}
}
input File:-
45 72 90 50 67 63 81 71 55 56 80 74/n 55 54 79 72 75 68/n 51 88 79
72/n 98 52 52 53 50 92 67 99 92 50 61 91/n 94 48 53 92 97/n 97 69 77
74 68 54 87 74 54 83 58 69/n 75 49 87 61 66 53 79 48 96 60/n 58 71 51
73 53 75 93 81 45 69 78 65/n 50 88 78 81 99 61 97 70 87 80 69/n 91 89
97 80 93 82 92 49 52 69 96 61
If you are using java 8 you can utilize streams and SummaryStatistics to calculate average/min/max like below
static Integer[][] myDouble = new Integer[10][12];
for (int i = 0; i < myDouble.length; ++i) {
IntSummaryStatistics statistics = Arrays.asList(myDouble[i]).stream().filter(intValue -> intValue!=null).collect(Collectors.summarizingInt(Integer::intValue));
System.out.println("Average: "+statistics.getAverage()+", min: "+statistics.getMin()+", max: "+statistics.getMax());
}
If you can not use java 8 then note that the issue with your code is that you are using primitive int in your array which will initialize the values to 0 and thus you get 0 when the row has less values than 12. One way to solve it is to change your array to Integer class but remember to skip the entries which have null as now instead of 0 you will get null in the rows with less entries.
your code working with int array changed to Integer, skipping nulls and using count instead of array.length:
for (int i = 0; i < myDouble.length; ++i) {
int count = 0; // count the values used to calculate sum
int sum = 0;
int average = 0;
for (int j = 0; j < myDouble[i].length; ++j) {
if(myDouble[i][j] == null) //skip the null values
continue;
//Arrays.sort(myDouble[i]);
sum+=myDouble[i][j];
count++;
System.out.print(App.myDouble[i][j] + " ");
}
average = (sum/count); //use count instead of lenght
System.out.println(" ");
System.out.println(average);
}
So I'm working on a method in Java that basically takes a random string of letters then goes through the method and changes the string into parity bits, which is basically converting each character to its numeric value in binary.
This is what I have:
public class ShiftData {
//this is the method that where Logic is implemented..
static String shiftRows(String text) {
//character array to store given String elements into an array..
char[] chs = text.toCharArray();
StringBuffer samBuffer = new StringBuffer();
//loop through the length of the character array..
for (int i = 0; i < chs.length; i++) {
//adding characters to the StringBuffer...
samBuffer.append(Integer.toHexString((int) chs[i]));
// here in the above statement toHexString method pads parity bit and converts to hexadecimal value..
}
return samBuffer.toString();//returning the value
}
}
This is the code that converts the string into 4x4 matrices:
if(text !=null && !text.isEmpty()) {
int len = text.length();
int rem = len %16;
int padChars = 16-rem;
for(int i =0; i < (len+padChars); i++) {
if(i < len) {
System.out.print(text.charAt(i)+ " ");
} else {
System.out.print( "A ");
}
if((i+1) % 4 == 0)
System.out.println();
if((i+1) % 16 == 0)
System.out.println("\n");
}
}
So basically if the input string is: WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO
The output should look like this:
d7 56 cf 47
d4 d8 d1 ca
48 d8 48 55
59 c9 c3 d7
59 4d 47 48
d2 4b d1 d4
50 d7 48 d1
47 4b 59 56
cc 50 59 53
d7 47 cf 50
d4 cf c9 4e
4d c6 cf 50
cf 41 41 41
41 41 41 41
41 41 41 41
41 41 41 41
I just need help combining the codes! I can get them working separately but I cant get the output I need. Please show how you would code this.
Don't use StringBuffer. Use StringBuilder instead.
Your printing loop is writing one letter at a time, separated by 3 spaces (and newlines). Letters in hex consist of two hex digits, as you already show in the desired output, so that won't work.
Your code prints blank lines at the end, which you probably don't want.
Integer.toHexString() will return a single digits if value is 0-15.
static String shiftRows(String text) {
char[] chs = text.toCharArray();
StringBuilder samBuffer = new StringBuilder();
for (int i = 0; i < chs.length; i++)
samBuffer.append(String.format("%02x", (int)chs[i])); // always 2 hex digits, even for 0-15
return samBuffer.toString();
}
public static void main(String[] args) {
String text = shiftRows("WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO");
if (text != null && ! text.isEmpty()) {
int len = (text.length() + 31) / 32 * 32; // round up to next increment of 32 (16 hex pairs)
for (int i = 0; i < len; i += 2) {
if (i != 0 && i % 8 == 0) { // every 4 hex pairs, but not first time
System.out.println();
if (i % 32 == 0) // every 16 hex pairs
System.out.println();
}
if (i < text.length())
System.out.print(text.substring(i, i + 2) + " ");
else
System.out.print("41 ");
}
}
}