gpt4 book ai didi

java - 如何从java函数: for dummies only返回2个不同类型的值

转载 作者:太空宇宙 更新时间:2023-11-04 06:32:28 25 4
gpt4 key购买 nike

我搜索了这个主题并找到了答案,但作为一个 Java 傻瓜,我并不真正理解这一切,因此我尝试在一个小例子中执行我找到的最佳答案:

package return2valuesofdifftype;
public class Return2ValuesOfDiffType {
public static void main(String[] args) {
System.out.println("started");
String strHere = "nothing happened";
int iHere = -5;
Method myM = new Method();
ReturningValues myRV = new ReturningValues(strHere, iHere);
myRV = myM.method(5, 10); //should return a RV holding the string "correct" and the integer 1

//so far so good (i hope), but how to get this string and integer out of RV ???

System.out.println("string = "+strHere+" ,en i = "+iHere);
}
}

package return2valuesofdifftype;
public final class ReturningValues {
private final String value;
private final int index;

public ReturningValues(String value, int index) {
this.value = value;
this.index = index;
}
}

package return2valuesofdifftype;
public class Method {
public ReturningValues method(int five, int ten) {
String str="";
int i=-1;
if(five==5){str="correct";}
else{str="wrong";}
if(ten==10){i=1;}
else{i=0;}
ReturningValues rv = new ReturningValues(str, i);
return rv;
}
}

我的问题:如何从 RV 中获取这个整数和字符串?多谢 !爸爸

最佳答案

添加 getter 方法是一种方法...

public final class ReturningValues 
{
private final String value;
private final int index;

public ReturningValues( String value, int index )
{
this.value = value;
this.index = index;
}

public String getString()
{
return value;
}

public String getInteger()
{
return index;
}
}

另一种方法是将属性的可见性更改为公共(public)。

public final class ReturningValues 
{
public final String value;
public final int index;

public ReturningValues( String value, int index )
{
this.value = value;
this.index = index;
}
}

关于java - 如何从java函数: for dummies only返回2个不同类型的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25928950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com