[英]SharedPreferences, Singleton Class - What should you use for calling, editing, saving and recalling two integer values
[英]Adding two integer values in a singleton class
我必須創建一個在單例類中添加兩個整數值的方法。 我已經設置了單例,但是我正在弄亂公共靜態方法。
我有
public static newTotal() {
}
但是我不確定內在的表達方式。 幫助將不勝感激。 謝謝。
用代碼編輯
專門告訴我使用單例類。 我已經有一個bean類,需要添加一個整數合計,然后一個將x加到合計中的公共靜態方法(整數x)
public class testBeanSingleton {
private static testBeanSingleton instance = new testBeanSingleton();
private Integer total;
public static testBeanSingleton getInstance() {
return instance;
}
private testBeanSingleton() {
total = new Integer();
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public static addToTotal() {
}
}
請為單例模式使用枚舉。此方法可以安全地進行序列化,並為單例提供包鐵保證。 為此,您需要Jdk8,因為它使用DoubleBinaryOperator和Lambda experssion
public enum Operation {
PLUS("+", (x, y) -> x + y),
private final DoubleBinaryOperator op;
private final String symbol;
public double apply(double x, double y) {
return op.applyAsDouble(x, y);
}
Operation(String symbol, DoubleBinaryOperator op) {
this.symbol = symbol;
this.op = op;
}
public String toString() {
return symbol;
}
public static void main(String[] args) {
final double num1 = 100;
final double num2 = 200;
final Operation oper = Operation.PLUS;
double newResult=oper.apply(num1,num2);
}
}
首先,您的方法必須返回一些東西,也許是整數?
其次,由於您只有一個單例,因此您的方法不必是靜態的。 檢查一下:
public int add(int i1, int i2){
return i1+i2;
}
然后像這樣使用它:
int sum = MySingleton.getInstance().add(firstNumber,secondNumber);
public static int newTotal() {
}
您的方法必須返回一個整數。 注意static
之后的int
。
如果需要一些示例,請查看以下內容: https : //docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.