'Format the output in JAVA
I am little confused about how I can format my output cleanly like the output given below:
My code:
import java.io.*;
import java.util.Scanner;
public class CountChar {
public static void main(String[] args) {
File file = new File("test1.txt");
BufferedReader reader = null;
int numCount = 0;
int otherCount = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please specify the # of intervals: ");
int N = sc.nextInt();
while (true) {
if (N == 2 || N == 4 || N == 5 || N == 10) {
break;
} else {
System.out.println("Your input is not supported, please choose another value: ");
N = sc.nextInt();
}
}
int interval_at = 100 / N;
int[] histogram = new int[N];
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
int num = 0;
try {
num = Integer.parseInt(text);
if (num > 0 && num <= 100) {
numCount++;
int inRange = (num - 1) / interval_at;
histogram[inRange] = histogram[inRange] + 1;
} else {
otherCount++;
}
} catch (NumberFormatException e) {
otherCount++;
continue;
}
}
// creating a file in which the output is stored
File myObj = new File("result1.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
// Writting in a file
FileWriter myWriter = new FileWriter("result1.txt");
myWriter.write("Please specify the # of intervals: ");
myWriter.write("\n" + N);
myWriter.write("\nNumber of integers in the interval [1,100]: " + numCount);
myWriter.write("\nOthers: " + otherCount);
for (int i = 0; i < N; i++) {
myWriter.write("\n" + ((i * interval_at) + 1) + " - " + ((i + 1) * interval_at) + " | ");
for (int j = 0; j < histogram[i]; j++) {
myWriter.write("*");
}
}
myWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
My code output:
1 - 25 | ****************
26 - 50 | *******************
51 - 75 | ***********************
76 - 100 | **********************
I need to format my output as given in the picture above.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

