Exercise "Nicely formatting sine values. "





  • Why not use some packages? 😉

    public class App {
        public static void main(String[] args) {
            System.out.println("  x | sin(x)");
            for(int i = 0; i < 360; i += 5) {
                if(i % 20 == 0)
                    System.out.println("----+-------");
                System.out.format("%3d |%6s\n", i, SineCalc.calculateSin(i));
            }
        }
    }
    
    import java.text.DecimalFormat;
    import java.text.DecimalFormatSymbols;
    import java.util.Locale;
    
    public class SineCalc {
    
        /**
         * calculate the sin from a degree with 3 decimal places
         * @param degree pass degree
         * @return get sin with 3 decimal places
         */
        public static String calculateSin(int degree) {
            //Set Decimal Symbols to '.' (ENGLISH) instead of ',' (GERMAN)
            DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.ENGLISH);
    
            // Uses Formatter with solution for zero issues '0.000' + pass symbols to formater
            DecimalFormat df = new DecimalFormat("#,###0.000", symbols);
    
            //calculates PI and applies formatter => returns solution
            return df.format(Math.sin(Math.toRadians(degree)));
        }
    }
    
    


  • Unfortunately formatting classes are being discussed much later in https://freedocs.mi.hdm-stuttgart.de/sd1_numbers_sect_NumberFormatting.html.


Log in to reply