java - 从 Java 方法返回多个变量

标签 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 来将它们写入文件。谢谢。

最佳答案

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

如果它们不相关,是否表明您的方法在做两件不同的事情?

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

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

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

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

关于java - 从 Java 方法返回多个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11968265/

相关文章:

java - 安装了最新的 JDK 1.8.0,但我的 Javac -version 仍然显示旧版本 (Windows 7 - 64)

java - 暂时禁用 Spring Security (ldap auth)

java - Spring Boot 修改默认 JSON 响应

java - 如何调用数组列表中对象的方法

java - 无法到达的 If 语句

c - 返回字符串数组的 C 函数原型(prototype)

java - 如何正确使用Java中的add方法?

java - 在 Java 中更改方法范围之外的变量

java - 从给定整数数组中查找最接近中间范围的数字的方法

javascript - 将返回函数分配给另一个变量(this)