Home > database >  How to get the value from each index?
How to get the value from each index?

Time:11-27

I'm extremely new to Java and we're tasked to take random values of an array and pass them through a method where it adds all of them for a running total.

For the sumMethod I'd like to take each value from all the index (given by sizeOfArray) and add them together.

Thank you!

public static void sumMethod(double[] arrayOfDoubles){
   //How to get the value from each indexes (given by sizeOfArray) and add them for the sum
   int arrayLength = arrayOfDoubles.length;
         
        System.out.println(arrayOfDoubles);
   }

  public static void main(String[] args) {   
   //1-3: Set up Scanner object to collect user's input on the size of array.
      Scanner keyboard = new Scanner(System.in);
      System.out.println("How many double numerical entries do you have?");
   //4: Declare an array of size sizeOfArray
      int sizeOfArray = keyboard.nextInt();  
   
      //Initialize array
      double[] arrayOfDoubles;
      arrayOfDoubles = new double[sizeOfArray];   
   
      
      
   
      for(int i = 0; i < sizeOfArray; i  ){
      //5: Use the Random number Class and walk over the array 
         Random randomNum = new Random();       
         arrayOfDoubles[i] = randomNum.nextDouble(0.0 , 100.0);
      //6: Invoke SumMethod
         sumMethod(arrayOfDoubles); 
      }
      
     
      
      
   }
}

CodePudding user response:

public static void sumMethod(double[] arrayOfDoubles) {
        double sum = 0;
        for (int j = 0; j < arrayOfDoubles.length; j  ) {
            sum  = arrayOfDoubles[j];
        }
    }

This will work too, if you are not familiar with the for-each loop yet.

Additionally, it is better to use arrayOfDoubles.length in the loop, in case you edit the code later, and change the size, or add or remove an element.

CodePudding user response:

For sumMethod, I'd say the first thing you could do is give it a return value rather than void, i.e. public static double sumMethod. That way when you run that method in main you can hold onto the result it prints out. I may be wrong but my understanding is your goal is to take an array and sum up the values within, for that, this would be a way to do it.

public static double sumMethod(double[] arrayOfDoubles) {
    double total = 0;
    for (double num : arrayOfDoubles) {
        total  = num;
    }
    return total;
}
  • Related