我有一个类将 double 部分与整数部分和分数部分分开。当我从该类创建对象时,我想单独使用它们。
我尝试将其作为函数,但函数只有 1 个返回值,或者我可以将其作为返回数组,我知道这一点。我只是想知道我是否可以更优雅地做到这一点
类的构造函数
public wholeAndFraction(double db){
String st=""+db;
st=st.replace(".", "-");
String[] str=st.split("-");
int whole=Integer.parseInt(str[0]);
int fraction=Integer.parseInt(str[1]);}
当我生成一个对象时,我想邀请整个或分数部分,例如
wholeAndFraction first=new wholeAndFraction(5.32);
System.out.println(first.whole);
或者使用 setter/getter ,但这也会给我一个错误
最佳答案
您需要一个类(class):
class WholeAndFraction {
long whole; // or String I do not know
long fraction; // or String I do not know
// constructor, getters
}
并传递此类的一个实例。
无法从一个方法返回 2 个值。你可以返回一个List或者一个包含2个值的数组,但是它是否更优雅是有争议的。
关于java - 从类中编写一个返回 2 个值的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55520750/