· 4 years ago · Mar 24, 2021, 09:44 AM
1import java.util.Scanner;
2import java.util.ArrayList;
3
4public class DataVisualizer {
5 public static void main(String[] args) {
6 Scanner scnr = new Scanner(System.in);
7
8 String userTitle;
9 String columnHeader1;
10 String columnHeader2;
11 ArrayList<String> authorName = new ArrayList<String>();
12 ArrayList<Integer> numNovels = new ArrayList<Integer>();
13 int i = 0;
14 String userInput = "";
15
16
17 System.out.println("Enter a title for the data:");
18 userTitle = scnr.nextLine();
19 System.out.println("You entered: " + userTitle);
20 System.out.println("");
21 System.out.println("Enter the column 1 header:");
22
23 columnHeader1 = scnr.nextLine();
24 System.out.println("You entered: " + columnHeader1);
25 System.out.println("");
26 System.out.println("Enter the column 2 header:");
27 columnHeader2 = scnr.nextLine();
28 System.out.println("You entered: " + columnHeader2);
29
30
31 userInput = "";
32 while (!userInput.equals("-1")) {
33 userInput = scnr.nextLine();
34 System.out.println("\nEnter a data point (-1 to stop input):");
35
36 if (userInput.equals("-1")){
37 break;
38 }
39
40 // if more than 1 comma exists in userInput
41 if (userInput.indexOf(',') != -1 && userInput.indexOf(',', userInput.indexOf(',')+1) != -1){
42 System.out.println("Error: Too many commas in input.");
43 }
44 else if (userInput.indexOf(',') != -1) {
45 // create new Scanner object that takes userInput from comma onwards
46 Scanner in = new Scanner(userInput.substring(userInput.indexOf(',')+1));
47 // if there is integer then add all information into ArrayList
48 if (in.hasNextInt()) {
49 authorName.add(i,userInput.substring(0, userInput.indexOf(',')));
50 numNovels.add(i, in.nextInt());
51 System.out.println("Data string: " + authorName.get(i));
52 System.out.println("Data integer: " + numNovels.get(i));
53 i++;
54 }
55 else {
56 System.out.println("Error: Comma not followed by an integer.");
57 }
58 }
59 else if (userInput.indexOf(',') == -1) {
60 System.out.println("Error: No comma in string.");
61 }
62 }
63
64 // Output information into formatted table
65 System.out.println("");
66 System.out.printf("%33s\n", userTitle);
67
68 System.out.printf("%-20s|%23s\n", columnHeader1, columnHeader2);
69 for (int j = 0; j < 44; j++) {
70 System.out.print("-");
71 }
72 System.out.println("");
73
74 for (int j = 0; j < authorName.size(); j++) {
75 System.out.printf("%-20s|%23d\n", authorName.get(j), numNovels.get(j));
76 }
77 System.out.println("");
78
79 // Output information as a formatted histogram
80 for (int j = 0; j < authorName.size(); j++) {
81 System.out.printf("%20s ", authorName.get(j));
82 for (int k = 0; k < numNovels.get(j); k++) {
83 System.out.print("*");
84 }
85 System.out.println("");
86 }
87 }
88}
89