Ok, so I recently tried to create a java program in eclipse that basically takes an infinite amount of numbers that are 1-100, and stores them in an arraylist. Once this is done, it is supposed to print them out in a horizontal bar graph.
import java.util.ArrayList;
import java.util.Scanner;
/*
* 1-10
* 11-20
* 21-30
* 31-40
* 41-50
* 51-60
* 61-70
* 71-80
* 81-90
* 91-100
*
* Created by Peter browning, PBdeveloping, 2015
*/
public class Asterisks {
public static ArrayList<Integer> array = new ArrayList<Integer>();
public static Scanner reader = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("Enter some numbers, 1-100, 0 to stop.");
int input = reader.nextInt();
while (input != 0)
{
if ((input >= 1) && (input <= 100))
{
array.add(input);
input = reader.nextInt();
}
else
{
System.out.println("Error: Number must be 1-100");
input = reader.nextInt();
}
}
for (int i = 1; i <= 10; i++)
{
int firstNumber = ((i - 1) * 10) + 1;
int secondNumber = (i * 10);
int count = 0;
System.out.println(firstNumber + " - " + secondNumber + " |" );
for (int nInsideArray : array)
{
if ((nInsideArray >= firstNumber) && (nInsideArray <= secondNumber))
{
count++;
}
}
for (int x = 0; x < count; x++)
System.out.print("*");
System.out.println();
}
}
}
So the problem that I am having is, whenever I keep on trying to run this program, (lets use the user input "1", "21", then "0" as an example, it should print out:
1-10 | *
11-20 |
21-30 | *
31-40 |
41-50 |
51-60 |
61-70 |
71-80 |
81-90 |
91-100 |
but instead it prints out....
1 - 10 |
*
11 - 20 |
21 - 30 |
*
31 - 40 |
41 - 50 |
51 - 60 |
61 - 70 |
71 - 80 |
81 - 90 |
91 - 100 |
Note: the asterisks are not beside the |'s for some reason, any help would be appreciated. Also if you have a more efficient way to code something like this, I would love to hear your input. I usually learn alot on this website, so please help me with my issue, thanks!
答案 0 :(得分:0)
This is because you are printing the pipe with a println()
. Change that to print()
. When you are done printing asterisks do a println
for a new line.