Trying to make a histogram, but the loop I'm trying to use for it is giving me a Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 14 error. I'm trying to get something along the lines of:
* *
* * * *
* * * * * *
* * * * * *
* * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
- - - - - - - - - -
0 1 2 3 4 5 6 7 8 9
And this is what I have so far:
public static void VerticalHist()
{
int max = 0; // initialize max
int[] count = new int[10]; // make array to find max
for (int i = 0; i < 100; i++)
{
int rand = (int)(Math.random() * ((9 - 0) + 1)); // generate random values
count[rand]++;
}
for (int x : count) // find max
{
if (x > max)
max = x;
}
// System.out.println(max);
String[][] nums2 = new String[max][10]; // create 2d array for histogram
for (int x = max; x > 0; x--)
{
System.out.println();
for (int i = 0; i < nums2[x].length; i++)
{
if (count[i] > 0)
nums2[x][i] = "*";
}
}
for (int i = 0; i < max; i++) // print 2d array
{
System.out.println();
for (String n: nums2[i])
{
System.out.print(n);
}
}
}
My loop for inserting the * is giving me the error.
for (int x = max; x > 0; x--)
{
System.out.println();
for (int i = 0; i < nums2[x].length; i++)
{
if (count[i] > 0)
nums2[x][i] = "*";
count[i]--;
else
nums2[x][i] = "";
}
}
I'm trying to take each row, check each index to see if there needs to be an asterisk, (if so, put an asterisk, if not put a blank space) and do so for each row in the 2d array.
I think the problem might be in the for loop definition,
for (int x = max; x > 0; x--)
Can you try changing it to
for (int x = max-1; x >= 0; x--)
The reason is, since you define an array of size max and index starts from zero max is actually outside the array
The first thing is that this line
for (int x = max; x > 0; x--)
should be
for (int x = max-1; x >= 0; x--)
I would then change the logic to decide whether to add a "*" or a " " to this:
if (count[i] > x)
nums2[x][i] = "*";
else
nums2[x][i] = " ";
Note that this needs to be a space, not an empty string, otherwise your rows will be compressed.
With these changes you get output like this:
**********
**********
**********
**********
**********
**********
**********
** *******
* *** ***
* * * ***
* * **
* * *
*
Which is obviously upside down. You need to change this line:
for (int i = 0; i < max; i++) // print 2d array
to this
for (int i = max-1; i >= 0; i--) // print 2d array
Which produces:
* **
* **
* **
* ** *
* ** *
* *** * *
* *** * *
* *** * *
***** ***
****** ***
****** ***
****** ***
**********
**********
**********
Related
I have a working program that randomly generates a total of 100 asteriks arbitrarily on 10 rows. However, I am having a hard time printing the total of asteriks on each row. On the last line of code (which is commented out), I tried what I thought would be the first step to getting it to work. I need the output to look similar to this:
14| * *
13| * *
12| * * * *
11| * * * *
10| * * * * * *
9| * * * * * *
8| * * * * * * * *
7| * * * * * * * *
6| * * * * * * * * * *
5| * * * * * * * * * *
4| * * * * * * * * * *
3| * * * * * * * * * *
2| * * * * * * * * * *
1| * * * * * * * * * *
-------------------
0 1 2 3 4 5 6 7 8 9
Mine instead looks as followings:
0 |************
1 |*************
2 |******
3 |*************
4 |******
5 |*********
6 |*********
7 |*********
8 |************
9 |***********
Any assistance would be greatly appreciated
import java.util.Random;
public class QuestionTwoAssignmentOne2018 {
public static void main(String[] args) {
Random bytes = new Random(); //take this out of the loops as mentioned in the comments
int count = 100; //keep track of 100 '*'s
int arr[] = new int[100];
for (int a = 0; a < 100; a++) {
arr[a] = bytes.nextInt(10); //
}
for (int i = 0; i < 10 ; i++) {
int bcount = 0;
for (int a = 0; a < 100; a++) {
if (arr[a] == i)
bcount++;
}
System.out.print(i + " |");
for (int c = 0; c < bcount; c++ )
System.out.print("*");
System.out.println();
// System.out.println(bcount + " |"); // MY ATTEMPT
}
}
}
}
You cannot get desired output because you are using that commented line inside the loop.
import java.util.Random;
public class QuestionTwoAssignmentOne2018 {
private static final int NUM = 10;
public static void main(String[] args) {
Random bytes = new Random(); // take this out of the loops as mentioned
// in the comments
int count = 100; // keep track of 100 '*'s
int arr[] = new int[100];
for (int a = 0; a < 100; a++) {
arr[a] = bytes.nextInt(10); //
}
for (int i = 0; i < NUM; i++)
{
int bcount = 0;
for (int a = 0; a < 100; a++) {
if (arr[a] == NUM - i)
bcount++;
}
System.out.print(NUM - i + " |");
for (int c = 0; c < bcount; c++)
System.out.print("*");
System.out.println();
}
System.out.print(" "); // for better view
for (int i = 0; i < (NUM * 2) - 1 ; i++)
System.out.print("-");
System.out.println();
System.out.print(" "); // for better view
for (int i = 0; i < NUM; i++)
System.out.print(i + " ");
}
}
And I wrote the more generic code for you. You may just change constant NUM to arrange number of rows.
That is my homework assignment in the link above. This is what I did so far:
import java.util.Scanner;
public class Bowling {
public static void recursionPins(int n, int t) {
if (n == 1) {
System.out.print("\t\t");
for (int i = 1; i <= t - 1; i++)
System.out.print(" ");
System.out.println("*");
} else {
recursionPins(n - 1, t);
for (int i = 1; i <= t - n; i++)
System.out.print(" ");
for (int i = 1; i <= n; i++)
System.out.print("* ");
System.out.println();
}
}
// main method
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of rows of pins: ");
int n = scan.nextInt();
recursionPins(n, n);
}
}
When I run it, the first * is out of place and I'm not sure what the error is. The link below is a sample run of the program.
Enter number of rows of pins: 10
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
I'm not sure how to move the star over.
Here in the base case:
if (n == 1) {
System.out.print("\t\t");
for (int i = 1; i <= t - 1; i++)
System.out.print(" ");
System.out.println("*");
}
You are printing two tabs and the required number of spaces. You need to remove System.out.print("\t\t");:
if (n == 1) {
for (int i = 1; i <= t - 1; i++)
System.out.print(" ");
System.out.println("*");
}
Output:
Enter number of rows of pins: 5
*
* *
* * *
* * * *
* * * * *
I need help with this
1******
12*****
123****
1234***
12345**
123456*
1234567
Using 3 for loops this will be completed.
i tried this
public class Pattren {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int i,j,k;
for (i = 1; i <= 7; i++)
{
for (j = 1; j <= i; ++j)
{
System.out.print((j)+("\n"));
for (k = 7 - i; k >= 1; k--)
{
System.out.print("* ");
}
}
}
}
}
But there is some logical problem with it. I need improvement in thos code.
I got this output.
1
* * * * * * 1
* * * * * 2
* * * * * 1
* * * * 2
* * * * 3
* * * * 1
* * * 2
* * * 3
* * * 4
* * * 1
* * 2
* * 3
* * 4
* * 5
* * 1
* 2
* 3
* 4
* 5
* 6
* 1
2
3
4
5
6
7
An easier version would be
int i,j;
for (i = 1; i <= 7; i++)
{
for (j = 1; j <= 7; ++j)
{
if (j <= i) {
System.out.print(j);
}
else {
System.out.print("*");
}
}
System.out.println();
}
Output
1******
12*****
123****
1234***
12345**
123456*
1234567
Below is a solution with much fewer lines of code:
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
String s = "";
for(int i=1; i<=7; i++){
s += i;
sb.append(String.format("%-7s", s).replace(" ", "*")).append("\n");
}
System.out.println(sb.toString());
}
The query was to write a Java method which prints the following triangle based on the input given (of the number of alphabets, on each side of the triangle).
public void triangle(int side);
Output expected:
triangle(3)
* * A * *
* F * B *
E * D * C
triangle(4)
* * * A * * *
* * I * B * *
* H * * * C *
G * F * E * D
I've come up with a method which does just that, but the code that I've written with my limited experience is with more number of for loops. Can any of you can review my code and come up with suggestions or optimized code for the same problem?
public void triangle(int input) {
int x = input;
int y = 2 * input - 1;
int mid = y / 2;
char character = 'A';
String[][] partitionArray1 = new String[x][y];
\\Following for loop will add letters on the side-1
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
if (i + mid == j) {
partitionArray1[i][j] = "" + character++;
} else {
partitionArray1[i][j] = "*";
}
}
}
\\Following for loop will add letters on the side-2 (horizontal)
for (int j = y - 2; j >= 0; j--) {
j--;
if (j >= 0) {
partitionArray1[x - 1][j] = "" + character++;
} else {
break;
}
}
\\Following for loop will add letters on the side-3
for (int i = x - 2; i >= 0; i--) {
for (int j = 0; j < y; j++) {
if ((i == mid - j) && (j < mid)) {
partitionArray1[i][j] = "" + character++;
}
}
}
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
System.out.print(partitionArray1[i][j] + "");
}
System.out.println();
}
}
Is there an algorithm available to answer such problems?
Try:
public static void triangle(int n) {
for (int i = 0; i < n; ++i) {
if (i == n-1) {
for (int j = 0; j < 2*n-1; ++j)
if (j % 2 == 0)
System.out.printf("%c ", 'A' + 2*n-2-j/2);
else
System.out.printf("* ");
System.out.println();
break;
}
for (int j = 0; j < 2*n-1; ++j) {
if (j == n-1+i)
System.out.printf("%c ", 'A'+i);
else if (j == n-1-i)
System.out.printf("%c ", 'A'+3*n-i-3);
else
System.out.printf("* ");
}
System.out.println();
}
}
The idea is to print row #n separately from the other. The rest of the row have exactly two element(except the first one which is a degenerated case) symmetrical with respect the center.
triangle(9);
* * * * * * * * A * * * * * * * *
* * * * * * * X * B * * * * * * *
* * * * * * W * * * C * * * * * *
* * * * * V * * * * * D * * * * *
* * * * U * * * * * * * E * * * *
* * * T * * * * * * * * * F * * *
* * S * * * * * * * * * * * G * *
* R * * * * * * * * * * * * * H *
Q * P * O * N * M * L * K * J * I
I was bored so i did it with one array
public static void mimi(int size){
int sizetab=size*size*2;
char res[] = new char[sizetab];
Arrays.fill(res,'*');
int pos=size-1;
int JumpGoRight=(2*size)+1;
int JumpGoLeft=2;
char letter='A';
boolean changed = false;
int nbLetters = size -1;
for (int s=size;s>1;s--)
nbLetters+=2;
int i=0;
while(i<(size-1)){
res[pos]=letter++;
pos+=JumpGoRight;
i++;
}
int limit=(sizetab-(size*2))+1;
while(i<nbLetters){
res[pos]=letter++;
pos-=JumpGoLeft;
if( !changed && (pos<limit) ){
JumpGoLeft=(size*2)-1 ;
changed=true;
}
i++;
}
int index = 0;
int doublesize=size*2;
for(char c: res){
if( ((++index)%doublesize)==0)
System.out.print('\n');
else
System.out.print(c);
}
}
So basically my program will print this type of triangle when user input a number that module 8 and equal to 0. So a larger triangle is made out of smaller triangle with a base of 4. This is how a triangle look like when i input number 16:
* * * * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * *
* * * *
* * * * * * * * * * * *
* * * * * * * * *
* * * * * *
* * *
* * * * * * * *
* * * * * *
* * * *
* *
* * * *
* * *
* *
*
but mine turned out like this:
* * * * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * *
* * * *
* * * * * * * * * * * *
* * * * * * * * *
* * * * * *
* * *
* * * * * * * *
* * * * * *
* * * *
* *
* * * *
* * *
* *
*
I'm not so sure how to add the spaces. Can someone help me out? Here is my code:
...
System.out.println("Please enter the length:");
int length = scan.nextInt();;
//length must be longer than 2
if (length <= 1){
System.out.println("Sorry :(! Length must be 2 or higher");
}
//if user enter a number that can divide by 8 and has no remainder, then
//loop to print out a beautiful triangle
else if(length%8==0) {
int numOfTriangle = length/4;
System.out.println("Here is your beautiful triangle :D \n");
for (int rowOfTri = numOfTriangle; rowOfTri > 0; rowOfTri--){
for(int i = 0; i < rowOfTri; i++){
printBase();
}
System.out.println();
for(int i = 0; i < rowOfTri; i++){
printThree();
}
System.out.println();
for(int i = 0; i < rowOfTri; i++){
printTwo();
}
System.out.println();
for(int i = 0; i < rowOfTri; i++){
printOne();
}
System.out.println();
}
System.out.println();
}
//any other number will print a normal triangle
else{
System.out.println("Here is your beautiful triangle :D \n");
for (int i = 1; i <= length; i++){
for (int j = 1; j <= length; j++){
if (j < i){
System.out.print(" ");
} else {
System.out.print("*");
System.out.print(" ");
}
}
System.out.println();
}
}
//asking users if they want to print again
System.out.println("\nDo you want to print another triangle? Type Yes or No.");
//scan for string answer
String againChoice = scan.next();
//if answer start with Y or y then answer is Yes.
if(againChoice.startsWith("Y") || againChoice.startsWith("y")){
printAgain = true;
}
//if answer start with N or n then answer is No.
else if(againChoice.startsWith("N") || againChoice.startsWith("n")){
printAgain = false;
System.out.println("Bye!");
}
// set input to none again
} while (printAgain == true);
}
//methods to print a triangle
public static void printBase(){
System.out.print("* * * * ");
}
public static void printThree(){
System.out.print(" * * * ");
}
public static void printTwo(){
System.out.print(" * * ");
}
public static void printOne(){
System.out.print(" * ");
}
public static void printSpace(){
System.out.print(" ");
}
}
I've changed your printing code like this and it works properly:
else if (length % 8 == 0) {
int layer = 0;
int numOfTriangle = length / 4;
System.out.println("Here is your beautiful triangle :D \n");
for (int rowOfTri = numOfTriangle; rowOfTri > 0; rowOfTri--) {
for (int i = 0; i < layer; i++) {
printSpace();
}
for (int i = 0; i < rowOfTri; i++) {
printBase(layer);
}
System.out.println();
for (int i = 0; i < layer; i++) {
printSpace();
}
for (int i = 0; i < rowOfTri; i++) {
printThree(layer);
}
System.out.println();
for (int i = 0; i < layer; i++) {
printSpace();
}
for (int i = 0; i < rowOfTri; i++) {
printTwo(layer);
}
System.out.println();
for (int i = 0; i < layer; i++) {
printSpace();
}
for (int i = 0; i < rowOfTri; i++) {
printOne(layer);
}
System.out.println();
layer++;
}
System.out.println();