Java help with class?

Discussion in 'Mac Programming' started by Big Dave, Aug 20, 2010.

  1. Big Dave macrumors 6502

    Joined:
    Nov 27, 2007
    Location:
    Crestview, Fl
    #1
    I'm writing a simple class that will calculate the (x,y) points on a circle. I'm using the cosine and sin of the angle to calculate the points. I get strange results that I'm hoping someone can show me what I am doing wrong.
    The output I get is:
    1 0
    0.53 0.85
    -0.45 0.89
    -1 0.09
    -0.6 -0.8
    0.37 -0.93
    0.98 -0.18
    0.67 0.75

    The output I want is:
    1 0
    .71 .71
    0 1
    -.71 .71
    -1 0
    -.71 -.71
    0 -1
    .71 -.71

    Here is my code:
    Code:
    import java.text.*;
    import java.lang.Math;
    class circle {
        public static void main (String args[]) {
        DecimalFormat df = new DecimalFormat("#.##");
          double x = 0.0;
          double y = 0.0;
          int r=1;
          for (int angle=0; angle<=315; angle+=45) {
            x = r*Math.cos(angle);
            y = r*Math.sin(angle);
            System.out.print(df.format(x));
            System.out.print(" ");
            System.out.println(df.format(y));
          }
        }
    }
     
  2. sammich macrumors 601

    sammich

    Joined:
    Sep 26, 2006
    Location:
    Sarcasmville.
    #2
    Usually needs to be in a unit called 'radians'.

    One radian or π (pi) is 180˚, so there are 2π in a full circle. So use the built in value for PI in java to calculate the values you need.
     
  3. plinden macrumors 68040

    plinden

    Joined:
    Apr 8, 2004
    #3
    A suggestion ... instead of iterating over the angle, specify the number of points, since otherwise you're limited to 360 in the loop.

    Your loop would look like this (the compiler will optimize out 2 * Math.PI, so no need for anyone to comment on that):
    Code:
            int max = 8;
            for (int i = 0; i < max; i++) {
                double radian = 2 * Math.PI * i / max;
                System.out.printf("%6.2f %6.2f\n", Math.cos(radian), Math
                        .sin(radian));
            }
    
    Also, always use title case for class names - it's the Java style standard.
     
  4. Big Dave thread starter macrumors 6502

    Joined:
    Nov 27, 2007
    Location:
    Crestview, Fl
    #4
    Thanks! You have provided me a working solution!

    Thanks guys! Here is what the code is now:

    Code:
    import java.text.*;
    import java.lang.Math;
    class Circle {
        public static void main (String args[]) {
          int max =8;
          for (int i = 0; i < max; i++) {
              double radian = 2* Math.PI * i / max;
              System.out.printf("%6.2f %6.2f\n", Math.cos(radian), Math.sin(radian));
          }
        }
    }
     

Share This Page