Display a sin(x) wave in java console

441 views Asked by At

My question is about display a sin(x) wave, but transform it vertically 90 degrees to the Y axis

int num = 7;
for (double y = 2; y >= 0; y-=0.2) {
  for (double x = 0; x <= num; x+=0.2) {
    if ( ((0.1+x) >= Math.asin((double)y-1)) && (((double)x-0.1) <= Math.asin((double)y-1)) )
      System.out.print('*');
    else
      System.out.print(' ');
  }
  System.out.println();
}
2

There are 2 answers

0
Peter On BEST ANSWER
for (double x = 0; x <= Math.PI; x += 0.15) {
            int sinValue = (int) Math.round(Math.sin(x) * 30);
            for (int j = 0; j < sinValue; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
3
Robert Dodier On

My advice is to create an array of characters corresponding to the output display. Fill up the array with asterisks as appropriate; you can iterate over X or over Y, whatever is easier, you aren't constrained as you are when you output directly to the console. Depending on how your code is organized, you might fill the array and then transpose it (i.e., swap the (i, j) element with (j, i) element). Finally, print out your array element by element.