Mathias Pettersson
Mathias Pettersson

Reputation: 19

How do i call an array from private methods?

so, i have to make an application that creates results, i have completed everything, I think???? but i dont know how to get me private method outputData to output the array results from the private method getValue.

This is what i have

 // CreateResults.java
// Create poll results and output them to a file.
import java.io.FileNotFoundException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.IllegalFormatException;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class CreateResults
{
   private int getValue()
   {
         int[]results = { 1, 1, 1, 1, 1, 2, 2, 3, 3, 4, 5, 6, 7, 8, 9 };
         outputData(results);

   } // end method getValue

   private void outputData(int[] output) 
   {

         for (int row = 0; row < results.length; row++) {
         System.out.println(input [row]);
   }//end for
   } // end method outputData

   public static void main( String args[] )
   {
      CreateResults application = new CreateResults();
      application.outputData();
   } // end main
} // end class CreateResults

Upvotes: 1

Views: 2041

Answers (2)

Alex
Alex

Reputation: 4473

Your array exists only within method scope. Put definition outside, ,make it class variable, like this:

public class CreateResults
{
int[]results;
   private int getValue()
   {
         results = new int[] { 1, 1, 1, 1, 1, 2, 2, 3, 3, 4, 5, 6, 7, 8, 9 };
         outputData(results);

   } // end method getValue
}

Upvotes: 1

Scary Wombat
Scary Wombat

Reputation: 44813

To get your code to work, you will need to make getValue public (and as it does not return anything, make it void)

Then within your main you can then then call application.getValue() which will create your array and then call outputData

public void getValue()
{
     int[]results = { 1, 1, 1, 1, 1, 2, 2, 3, 3, 4, 5, 6, 7, 8, 9 };
     outputData(results);

} // end method getValue

public static void main( String args[] )
{
  CreateResults application = new CreateResults();
  application.getValue ();
} // 

Also as you outputData is working on the inputted parameter of output you need to change it to

 private void outputData(int[] output) 
 {

     for (int row = 0; row < output.length; row++) {
         System.out.println(output[row]);
     }
 }//e

Upvotes: 1

Related Questions