Reputation: 89
I have a program that takes input from a text file and displays this
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int numLabels = 0;
if(scan.hasNextInt())
{
numLabels = scan.nextInt();
scan.nextLine();
}
else
{
System.out.println("Error! Invalid input.");
System.exit(0);
}
String[] label = new String[numLabels];
int[] data = new int[numLabels];
for(int i=0; i<numLabels*2; i++)
{
if (i<numLabels)
{
label[i] = scan.nextLine();
}
if (i >= numLabels)
{
if(scan.hasNextInt())
{
data[i-numLabels] = scan.nextInt();
}
else
{
System.out.print("Error! Invalid input.");
System.exit(0);
}
}
}
for(int i=0; i<numLabels; i++)
{
int width = 0;
for(int j=0; j<label.length; j++)
{
if(width<label[j].length()) width=label[j].length();
}
String a = "";
for(int j=0; j<data[i]; j++)
{
a = a + "*";
if(j==(data[i]-1)) System.out.println();
}
System.out.printf("%" + width + "s %s", label[i], a);
}
}
It's doing what I want, but there's a blank line at the beginning. It's pretty minor but I want to know why it's showing up, both to fix it now and for future reference.
Upvotes: 0
Views: 54
Reputation: 36446
It's because of this line here:
if(j==(data[i]-1)) System.out.println();
Also, by putting the new line inside the loop, I think it will actually produce an incorrect result when you try to plot something with a count of 0.
If you want to get rid of it, print out the newline after each row of your bar chart:
String a = "";
for(int j=0; j<data[i]; j++)
{
a = a + "*";
}
System.out.printf("%" + width + "s %s\n", label[i], a);
Upvotes: 2