Skip to content
Advertisement

How to rewrite and condense in Java

I’m new to Java and I’m trying to write a function that will take an input, calculate the first 4 frequencies, and then out the input and next 4 frequencies (with 2 values after decimal place). The code I currently have written does exactly that but when I submit it for grading, it’s telling me it’s wrong. ( I can run it to test it and it works every time). Can someone help me maybe condense what I have to be neater, or just point me in the right direction? Thank you

import java.util.Scanner;

public class LabProgram {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);
      
      double f0 = scnr.nextDouble();
      double r = Math.pow(2, (1.0 / 12.0));
      double f1 = f0 * Math.pow(r, 1);
      double f2 = f0 * Math.pow(r, 2);
      double f3 = f0 * Math.pow(r, 3);
      double f4 = f0 * Math.pow(r, 4);
      double f5 = f0 * Math.pow(r, 5);
      
       
     System.out.printf("%.2f", f0);
     System.out.print(" ");
     System.out.printf("%.2f", f1);
     System.out.print(" ");
     System.out.printf("%.2f", f2);
     System.out.print(" ");
     System.out.printf("%.2f", f3);
     System.out.print(" ");
     System.out.printf("%.2f", f4);     

   }
}

Advertisement

Answer

This is a perfect situation to use an array and a for loop in. Since you have multiple of the same type of value, and then are doing some calculation on them which has some type of pattern, you can use an array to store the numbers, and use a for loop to do the calculations.

import java.util.Scanner;

public class LabProgram {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);
      
      double f0 = scnr.nextDouble();
      double r = Math.pow(2, (1.0 / 12.0));
      int numberCount = 5; // how many numbers you want to keep, in this case its 4 of them
      double[] nums = new double[numberCount]; // using an array to store the numbers, instead of multiple separate variables
      for (int i = 0; i < nums.length; i++) {
         nums[i] = f0 * Math.pow(r, i + 1);
      }

      System.out.printf("%.2f", f0);
      for (int i = 0; i < nums.length; i++) {
         System.out.printf(" %.2f", nums[i]);
      }    
   }
}

The good part about this is that this is entirely not hardcoded, so you can extend or shrink how many numbers you want to use by just changing the variable numberCount, instead of copy-pasting your code many times over.

Advertisement