How do i call an array from private methods?

守給你的承諾、 提交于 2019-12-24 16:59:56

问题


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

回答1:


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



回答2:


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
}


来源:https://stackoverflow.com/questions/29909341/how-do-i-call-an-array-from-private-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!