从Java方法返回多个变量

时间:2012-08-15 11:10:34

标签: java methods return

抱歉愚蠢的问题...... 任何人都可以帮我从方法中返回两个变量(我读here 并尝试重新编码,但没有结果)。

public class FileQualityChecker {
    EnviroVars vars = new EnviroVars();  
    public int n = 0;
    public int z = 0;
    public int m = 0;
    String stringStatus;


    public void stringLenghtCheck(String pathToCheckedFile)
    {
        try{    
    FileInputStream fstream = new          FileInputStream(pathToCheckedFile+"\\"+"Test.dat");
         // Get the object of DataInputStream
         DataInputStream in = new DataInputStream(fstream);
         BufferedReader br = new BufferedReader(new InputStreamReader(in));
         String strLine;
          //Read File Line By Line
         while ((strLine = br.readLine()) != null)   
         {

           if  (
           strLine.length() == vars.strLenghtH ||
           strLine.length() == vars.strLenghtCUoriginal ||
           strLine.length() == vars.strLenghtCEAoriginal ||
           strLine.length() == vars.strLenghtCAoriginal ||
           strLine.length() == vars.strLenghtTrailer ||
           strLine.length() == vars.strLenghtLastRow 

           ) 
            {
               stringStatus = "ok";
               n++;
               z++; 

            }
           else 
           {
                stringStatus = "Fail";
                n++; 
                m++;
                }
           System.out.println (n +" " + strLine.length() +" " + stringStatus);
          }



         //Close the input stream
          in.close();
        }
        catch
        (Exception e){//Catch exception if any
         System.err.println("Error: " + e.getMessage());
         }

         /*How to return m and z from method to use these vars for writing in the file*/
         return (m, z);


        }

}

我需要在另一个类中使用m和z将它们写入文件。谢谢。

11 个答案:

答案 0 :(得分:10)

我对这些问题的第一个问题是,这两个结果之间的关系是什么?

如果他们不相关,这是否指向您的方法做两件不同的事情?

如果它们相关(它们似乎是这种情况),则将它们包装在自定义对象中。这使您有机会稍后在此对象中添加更多结果,可以将行为附加到此对象。

您的另一个解决方案是将回调对象传递给此方法,因此您根本不会返回任何内容,而是您的方法会在此对象上调用方法,例如。

// do some processing
callbackObject.furtherMethod(m, n);

这样做的好处是遵循OO原则让对象为你做事,而不是向他们询问信息并自己做

答案 1 :(得分:6)

创建一个单独的类,并将m和z作为该对象中的变量,创建并填充该对象并返回该对象

class result {
  int m ; 
  int z ; 

// define getters and setters 
} 

public result stringLengthCheck(String pathToFile)
{

// your code 

result r = new result();
r.setM(m);
r.setZ(z);
return r ;
}

答案 2 :(得分:4)

如何返回地图。 例如:

Map<String,Integer> result = new HashMap<String,Integer>();
result.put("ok",m);
result.put("fail",z);
return result;

并且您的方法应更改为:

public Map stringLenghtCheck(String pathToCheckedFile)

最后,您可以通过查看地图获得结果:

map.get("ok")
map.get("fail")

答案 3 :(得分:4)

您不能从方法返回多个变量。你需要返回别的东西。可以提出许多建议:

  1. 在你的方法所在的类中设置这些变量,然后访问它们(在这个类之外?)
    • plus:简单表示法,例如setget
    • plus:永远不要混淆你的变量
    • 减去:课堂上的一些垃圾
  2. 返回包含变量的数组或列表
    • plus:存储的简单性
    • plus:迭代数据的可能性
    • 减号:您可以轻松混淆变量(需要关于变量位置的约定)
    • 减去:额外的内存分配 - 在存储少量变量时可能就足够了
  3. 返回一个包装器(包含所需变量的类的实例)
    • plus:存储和阅读的简单性
    • plus:永远不要混淆你的变量
    • 减:丑陋的代码(可能)如果不经常使用包装
  4. 使用回调(如void setToArray(int[] array, args...)) - 相同的+/-表示1-3分和

    • plus:可以减少内存分配
    • 减去:更难看的方法签名

    还有一些黑客(黑客 - 不是偶然的情况!)也可以发生:

  5. 使用连接。您可以使用分隔符将多个字符串连接在一起,或者在long

    中存储两个整数
    • 所有可能的缺点,没有优点,但有趣
  6. 使用InputStreamOutputStream
    • plus:可以使用流处理的所有代码(例如,存储/读取文件)
    • 减:没有随机访问数据
  7. 使用Iterator(我把它放在'hacks'之下只是因为在很多方面它假设存储变量就像在包装器中一样)
    • plus:迭代数据的可能性
    • plus:避免额外内存分配的可能性
    • 减:没有随机访问数据
  8. 将所有内容存储在String(或byte[])中,并在需要时进行解析
    • plus:String无论如何都可以传输
    • 减:解析是一个昂贵的程序
  9. 为了存储两个整数,经常使用PointDimension个类。但是对于给出的代码,我建议使用简单的数组或在类FileQualityChecker中存储变量,因为mz似乎不适合坐标或维度上下文。

答案 4 :(得分:1)

您可以创建自定义类或返回列表:

return Arrays.asList(m, z);

(您的方法的返回类型为List<Integer>

或者在您的情况下,由于mz是类成员,您可以不返回任何内容(无效)并提供getter以获取mz的值一旦该方法返回。

答案 5 :(得分:1)

不,你不能,但写一个包含这些字段的类很容易:

class StrAndInt {
   String str;
   int num;

   StrAndInt(String str, int num) {
       this.str = str;
       this.num = num;
   }
}

class MyApplication {
   ....
   ....
   StrAndInt myMethod() {
      ....
      ....
      return new StrAndInt("The value returned", 10);
   }

答案 6 :(得分:1)

另一种选择是不返回任何内容,因为您可以使用其他方法获取这些结果。

FileQualityChecker fqc = ..

fqc.stringLenghtCheck(fileName);
int okCount = fqc.getOkCount();
int failedCount = fqc.getFailedCount();

答案 7 :(得分:0)

我不认为你可以从方法中返回两个变量,因为一个方法只能有一个返回类型。所以IMO你有两个选择:

1)创建一个具有相同类型变量的类,并为在该类中定义的变量生成getter-setter。现在,从您想要返回的方法返回变量,创建该类的对象,并使用setter设置实例变量的值,并使用要返回的变量的值返回该对象。

2)创建这些变量的数组并返回该数组。

答案 8 :(得分:0)

1.我希望mn使用传递值。 2.Instead use Pass by Reference。要在Java中执行通过引用传递,它必须是一个Java对象。 3.因此,创建新的整数对象 m = new Integer();

答案 9 :(得分:0)

您可以将两个变量放在int[]中,并在调用方法时提取这两个值。

return new Integer[]{m, z};

调用方法后:

Integer[] array = Foo.method();
int m = array[0];
int z = array[1];

答案 10 :(得分:0)

你可以简单地构造一个对象。

但是,如果必须返回多个变量,则可以返回类似类型变量的数组,例如:

public static StringBuilder[] remedySBarrayreturner() {
    sbbb.append("huhu");
    sbcc.append("hihi");
    return new StringBuilder[] {sbbb, sbcc};
}
相关问题