Simple Java Homework Help (* NOW SOLVED*)
I am having trouble with this code, it does half of what I need it to do but not quite exactly.
Here is what it needs to do:
Write a method, named printHorizontalBars(), that prompts the user for four values and draws
corresponding bar graphs using an ASCII character. For example if the user entered 15, 12, 9
and 4, the program would draw.
* * * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * *
Here is what I get with the current code output:
Enter four integers...
15 12 9 4
* * * *
* * * *
* * * *
* * * *
Can anyone help me figure out whats wrong?:(think):
Thanks
-Austin
Code:
package patterns;
import java.util.Scanner;
/**
*
* @author Austin J Benner
*/
public class Patterns {
public void HorizontalBars(){
int[] numberArr = new int [4]; // Creates and array to read inputs into
Scanner sc = new Scanner (System.in); // Creates a new instance of the Scanner() method
System.out.println("Enter four integers...");
int number_1 = sc.nextInt(); // Reads in the four integer inputs from user
int number_2 = sc.nextInt();
int number_3 = sc.nextInt();
int number_4 = sc.nextInt();
numberArr[0] = number_1;
numberArr[1] = number_2;
numberArr[2] = number_3;
numberArr[3] = number_4;
System.out.println();
int max = 0; // Determines the largest integer value in the array
for(int i = 0; i < numberArr.length;i++)
{
if (numberArr[i] > max)
{
max = numberArr[i];
}
for(int j = 0; j < numberArr.length; j++)
{
if (numberArr[i] >= j)
{
System.out.print("* "); // Prints ASCII symbol if largest integer value
}
}
System.out.println();
}
} public static void main(String[ ] args) {
// TODO code application logic here
Patterns myTestDriver = new Patterns();
System.out.println("printHorizontalBars");
myTestDriver.HorizontalBars();
}
}
Re: Simple Java Homework Help
I wont give you the solution to all of your problems since it's a homework, but can you spot anything wrong with the following part:
Code:
for(int j = 0; j < numberArr.length; j++)
{
if (numberArr[i] >= j)
{
System.out.print("* "); // Prints ASCII symbol if largest integer value
}
}
Will your program ever print out more * than the length of your array?
Re: Simple Java Homework Help
Code:
for(int j = 1; j <= numberArr.length; j++)
{
if (numberArr[i] >= j)
{
System.out.print("* "); // Prints ASCII symbol if largest integer value
}
}
I'm not 100% sure what you are asking (VERY NEW TO JAVA) because it did display more than one *'s with that code segment...I just messed with the code a little bit, starting to go in the right direction, though it only correctly displays number <= 4 properly. Anything over that it just displays as 4.
-Austin
Re: Simple Java Homework Help
Never mind I think I understand Now.
Code:
for(int j = 1; j <= max; j++)
Is this what you were alluding to?
-Austin
Re: Simple Java Homework Help
Et voila!
You solved it! :o:
Re: Simple Java Homework Help
Thanks for your guidance Zyril!!! Much appreciated. :(clap):