May*_*y12 2 java methods return
抱歉愚蠢的问题......任何人都可以帮我从方法中返回两个变量(我在这里阅读 并尝试重新编码,但没有结果).
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我需要在另一个类中使用m和z将它们写入文件.谢谢.
Bri*_*new 10
我对这些问题的第一个问题是,这两个结果之间的关系是什么?
如果它们不相关,这是否指向您的方法做两件不同的事情?
如果它们相关(它们似乎是在这种情况下),则将它们包装在自定义对象中.这使您有机会稍后在此对象中添加更多结果,并且可以将行为附加到此对象.
您的另一个解决方案是将回调对象传递给此方法,因此您根本不返回任何内容,而是您的方法然后调用此对象上的方法,例如
// do some processing
callbackObject.furtherMethod(m, n);
Run Code Online (Sandbox Code Playgroud)
这样做的好处是遵循OO原则,即让对象为您做事,而不是向他们询问信息并自己动手.
小智 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 ;
}
Run Code Online (Sandbox Code Playgroud)