Java bar chart method - java

I need to print out a bar chart, via a call from a method barChartPrinter. I.e. barChartPrinter(5, 6, 2); would print: a vertical column of 5 XX's followed by
a space then a vertical column of 6 XX's and a vertical column of 2 XX's.
The numbers are based on user input, so I'm thinking I need to gather the numbers and store those in an array. And I'm thinking a for loop will be involved,
but I'm not sure how I'd do it.
public class BarChart {
public static void main(String args[]) {
int[] list = new int[4];
Scanner input = new Scanner(System.in);
System.out.println("Enter four integers: ");
for(int i = 0; i < list.length; i++)
list[i] = input.nextInt();
System.out.println();
barChartPrinter(list);
}
public static void barChartPrinter(int[] numbers) {
int max = numbers[0];
for (int i = 0; i < numbers.length; i++)
if(numbers[i] > max)
max = numbers[i];
}
}
This is where I get stuck: defining the method that will print out the bar chart; given the user input values. The method needs to print out in this format, i.e.
barChartPrinter(1, 2, 3, 4) =
For some reason, it won't display how the bar chart should be constructed on here so I'll just describe it:
There would first be a column of XX, then a column of XX (two of these vertically to represent 2), then another column of XX (but this time three of these on top of each other, to represent the number 3) and finally another column of XX * 4 vertically.
Any pointers?

OK, by now I'm sure that you know that it would be trivially easy to create horizontal bar graphs:
2 6 4
**
******
****
Since the print and println methods of the console's PrintStream (the out of System.out) prints things horizontally. The trick for your assignment is how to print this graph vertically. And for that you're going to have to use a little logic. Since this is obviously homework, I'm not going to give you a solution but rather will suggest options.
You know that you'll need to use a loop of some sort to print lines in a row.
One possible solution has you figuring out how many times to loop in advance of the loop by first finding the maximal value held by the array. If you do this, then use a for loop.
Another possible solution you don't find max, but rather just loop til done. Here use a while loop. This would be the option I'd use, and I'd use a boolean variable, say named keepGoing to help tell the while loop when to keep looping and when to stop.
If you go with this latter option, you'll use an int counter in the loop to check what row you're on, and you'll advance this counter inside of the loop.
You will need to nest a for loop inside of your while loop to go through each array item.
You'd use this counter and the array items (in the for loop within the while loop) to see if the String that you will eventually print should have an "* " added to it.
After the inner for loop, you'll print the String you've created.
If no "* " are present (you could call myString.trim().isEmpty()), then keepGoing = false; and the while loop should stop.
Edit: your posted code is a bit off in that it tells the user to enter four numbers but only accepts three. You'll want to fix this.
Edit 2 You state:
Hey, sorry yeah I've sorted the code out. I've coded the way to find the max value within the method. I'm stuck on the step of actually producing the chart now. I know that it will print the XX's each row horizontally, but I'm still stumped as to how I can achieve this- I know it will involve a for loop, but I can't see how I can print the XX's for each column; apologies if I'm missing something obvious
Again, break up your problem by splitting up the big problem into little steps, the smallest you can think of, and then solve each small step. You know that you're going to have to construct a String to be printed, and so you should focus on that, on how to construct this String so that an asterisk is present where need be, and a space is present when the column should show no asterisk. Try to come up with a solution, even a partial solution and post it as an edit to your question, much like how I'm posting this edit to my answer.

Related

confusion with For Loop Java

Sorry i'm new to java, just need help with my school project.
I'm trying to implement a For loop for a deck of cards. I want my loop to keep adding cards till it has reached 5.
The count increases using the following URL: https://deckofcardsapi.com/api/deck/new/draw/?count=1
count=1 needs to keep going up from 1 to 5. I think what i have below is correct but is this the right way to do it? and can i enhance it so there is an output at the end of it?
int counter = 5;
for(int i = 1; i <= counter; i++) {
String uriString = "https://deckofcardsapi.com/api/deck/new/draw/?count="+i;
If you want to deal cards from 1 to 5, then yes it works correctly.
"can i enhance it so there is an output at the end of it?"
It depends on what do exactly you want. If you want to parse the result, then check this out: http://unirest.io/java.html

Java - Validation if row number already exists in arrayList,

I want my program to check if the item entered is already in arrayList which is stored within my file ChessList.java, if so produce error and loop back to question else accept number and move on.
Reason being I only want one number to be selected in a row.
Say my program asks for Piece 1, row number and USER ENTERS 5
Then when program loops to piece 2, row number cannot accept 5 again and would produce error.
Therefore, two pieces cannot be contained within in the same row.
Any suggestions how I would go about this? thanks.
I haven't read your code because there's a lot of it, but it just sounds like you want something like
while(true){
int number = getNumber();
if(list.contains(number){
System.out.println("That number is already in the list. Try again");
else{
list.add(number);
break;
}
}
An alternative would be to store it as a Set, which does not store duplicates.

Using a WHILE statement to check against duplicates in Java

I am trying to write a program containing 3 String ArrayLists, where 1 item may be included in all 3 ArrayLists. However, the output must insure that the randomly selected items are all different. As I work through this issue, I am just using numbers so it will be easier to catch. I have been trying to solve this problem for a few days now, and figure there must be something I am overlooking. Here is the code for the method that must have the fault:
private void generateThree() {
// Find the maximum number the random can be.
index = thirdNumberArray.size();
// Initiate the random function.
Random rand = new Random();
// Generate a random number from 1 to the maximum.
randomInt = rand.nextInt(index);
// Access the item in the ArrayList using the random number as the index.
thirdDrawn = thirdNumberArray.get(randomInt);
// Check that the number is different than any previously set numbers.
while ((thirdDrawn.equals(secondDrawn)) || (thirdDrawn.equals(firstDrawn))) {
randomInt = rand.nextInt(index);
thirdDrawn = thirdNumberArray.get(randomInt);
}
// Set the output.
thirdNumberLabel.setText((thirdDrawn));
// Reset the index.
index = 0;
}
So far, the IF statement I use to check the secondDrawn against the firstDrawn has worked perfectly. But the above code still allows the thirdDrawn to display a duplicate of both the firstDrawn and secondDrawn. I know this problem has to be in my loop logic, but I just can't grasp what it is. I have tried multiple different IF statements, but they didn't solve the whole problem. Can anyone give me some feedback or corrections? Thanks in advance.
Any time you generate a number you want to draw, add it to a HashSet<String>. Then, have your if statement conditional check !myHashset.contains(thirdDrawn).

select odd/even elements of array using recursion

Am working on some programming homework and am a bit lost. The project is to select the even/odd elements of a listarray and store in another array. It is not the even numbers in each element, but the elements themselves so if an array had values "1,2,5,7,9" and returned the even elements it would give "1, 5, 9". Also have to use recursion. Would anyone be able to give me a starting point or some advice. Though about starting with 2 elements and taking 2nd element and then building up from that, but don't know how it would add on the 2nd pass
public static ArrayList<Integer> even(ArrayList<Integer> list)
ArrayList<Integer> evenlist = ListMethods.deepClone(tList);//make copy of list
if (evenlist.size()<=1) // The list is empty or has one element
{
// return null;// Return the list as is
}
if
(evenlist.size()==2)
{
//return right element
//call method again
//add to list
}
Psuedocode
int[] evens,odds;
function categorize(List<Integer> in,int idx)
if(idx>=in.length)
return
int cur = in[idx]
if(even), add to evens
else add to odds
categorize(in,idx+1)
This sounds similar to the homework I just completed, so if it is (And you're in my class!), I'll not tell you to use any terminology we haven't covered as I know it can be daunting trying to discover something new for practicals (beyond what we have to do).
First, set your exit condition. As you've already said, you have to create a new ArrayList out of the existing one. You are going to remove items from the existing ArrayList, storing the integers that are at even (or odd) indices, until the list is empty.
So your exit condition is:
if (evenList is Empty)
return evenList;
Then, work your way through the steps. I would advise determining if the Array you start with has an even of odd number of steps, something like this:
if (evenList has Even Elements)
int holderForIntsAtEvenElements = last evenList EVEN element
Note we start at the last element, so when you are coming OUT of the recursive method, this will be the last one added to your new ArrayList, and thus it'll be in numerical order. You might find this post interesting to do this: What does this boolean return mean?
We then want to remove the last element from the list and recursively call the method again.
Finally, when we hit our exit condition and start to come out, we want to add the ints we've been storing to them, e.g.:
evenList.add(holderForIntsAtEvenElements);
return evenList;
That doesn't solve one problem, which is what to do with the very first element if the list does NOT have an even number of elements - however, I'll let you try and solve that!
That's a good mix of code and pseudo code and will hopefully help to get you on the right track.
You could use a simple for loop like this:
for (int i = 0; i < list.size(); i += 2) {
System.out.println(list.get(i));
}
If you have to use recursion, here's an outline of the steps you might take. (I won't tell you exactly what to do because you haven't tried anything and it is like homework.)
Take first element and store it
Remove (new) first element from list
Call self

Value (not index) greater than 3 in array causes java.lang.ArrayIndexOutOfBoundsException

I'm a novice programmer. This may be a simple problem but I've never seen this before. First of all, let me clarify that I'm not even trying to manipulate the index. Here's the part of the code that is causing the exception:
int[] bumpercatcher = new int[4];
//time variable that helps control events
int time = 0;
public void setup()
{
bumpercatcher[0]=4;
bumpercatcher[1]=4;
bumpercatcher[2]=4;
bumpercatcher[3]=4;
As you can see I'm trying to set them all equal to 4 at the start of the program. This causes the arrayindexoutofbounds exception. If I set them all equal to 0~3 then there is no problem (until I set them to a value greater than 3 later in the program). I don't understand it.
-it doesn't matter if I set the array size to 10, I still get the same exception
-it doesn't matter if I set only one of the values (i.e. at index 1, which is definitely within bounds of the array). same exception
Is there something I'm doing wrong? Thanks.
well, here' the entire code if you want to take a look(not too long, 1 class, bad programming practies): http://dl.dropbox.com/u/33501308/Pong.java
Here's the html from which you can see the program from (not much to see. it just freezes instantly.): http://dl.dropbox.com/u/33501308/bin.zip
by the way I'm using eclipse.
I don't really know what SSCEE is. sorry
Your posted code file includes loops along the lines of
for(int j: bumpercatcher) {
if(bumpercatcher[j]>5)
...
}
This is an issue. This is a different kind of loop than a traditional for loop. It is an extended or enhanced for, also called a foreach. It reads "for each integer j in array bumpercatcher do x." You are taking your element j (a value) and using it as an index to the array. When your value exceeds the maximum index, you will get an exception.
Write your code with a proper for loop if you want to access by index, or try simply restructuring your logic like
for (int j : bumpercatcher) {
if (j > 5) // j is the value!
...
}
I'm not sure what the problem is, but a far more readable way of doing this would be with a for loop:
for(int i = 0; i < bumpercatcher.length; i++) {
bumpercatcher[i] = 4;
}

Categories