Input some names and then print the names vertically and side by side.
![]() |
| Code Output |
/**
* Write a program to input some names >2 and <=9 and print it vertically side by side.
* Input: Ankur Chiranjan Mack
* output: A C M
* N H A
* K I C
* U R K
* R A
* N
* J
* A
* N
*/
package stringFun;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class stringFun {
String a[];
int lenM;
stringFun() {
lenM = 0;
}
private void fnInput() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the number of names: ");
int s = Integer.parseInt(br.readLine());
a = new String[s];
for (int x = 0; x < s; x++)
a[x] = br.readLine();
br.close();
}
private void fnSort() // This method finds out the length of the longest name
{
String arr[] = new String[a.length];
for (int i = 0; i < a.length; i++)
arr[i] = a[i];
String temp = "";
/*
* Bubble sorting technique is applied in this program. You may use other
* sorting techniques too.
*/
for (int t = 0; t < a.length - 1; t++) {
for (int i = 0; i < a.length - 1 - t; i++) {
if (arr[i].length() < arr[i + 1].length()) {
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
}
lenM = arr[0].length(); // Obviously, the sorted array would contain the longest name in the first cell.
}
private void addSpaces() {
for (int d = 0; d < a.length; d++) {
String space = " ";
if (a[d].length() < lenM) {
for (int u = 0; u < lenM - a[d].length() - 1; u++)
space = space + " ";
}
a[d] = a[d].concat(space);
}
}
private void display() throws Exception {
for (int k = 0; k < lenM; k++) {
for (int j = 0; j < a.length; j++) {
char ch = a[j].charAt(k);
System.out.print(ch + " ");
}
System.out.println();
}
}
public static void main(String[] args) throws Exception {
stringFun object = new stringFun();
object.fnInput();
object.fnSort();
object.addSpaces();
object.display();
}
}

Comments
Post a Comment