我正在嘗試為我的班級撰寫一個 30 行或更少的程式(自我挑戰)。
程式向用戶詢問一個簡單的加法、除法、乘法或減法問題,玩家回答,沖洗并重復 10 次,然后詢問玩家是否要繼續或結束程式。問題的型別(add、mult等)應隨機選擇。
這樣我就不需要使用巨大的 switch case 或 if-else 樹,我想知道是否有任何方法可以在變數中包含運算子,然后再使用它。
例子:
var operator = ;
int[] n = {1, 2};
System.out.println(n[0] operator n[1]);
輸出將是“3”
這是我想做的事情的一個例子。這可能嗎?
uj5u.com熱心網友回復:
不,你不能直接這樣做。您將必須創建一個表示運算子的型別。
最常見的方法是使用列舉:
enum Operator {
PLUS {
@Override int operate(int a, int b) {
return a b;
}
};
abstract int operate(int a, int b);
}
Operator operator = Operator.PLUS;
int[] n = {1, 2};
System.out.println(operator.operate(n[0], n[1]));
uj5u.com熱心網友回復:
無法將運算子分配給變數。
不超過 30 行……程式要求用戶進行簡單的加法、除法、乘法或減法運算
如果你想用盡可能少的行來實作它,內置函式式介面將是一個不錯的選擇。為此,您需要IntBinaryOperator表示對兩個int引數執行的操作。
函式式介面可以通過使用lambda 運算式或方法參考來實作(同樣,您也可以使用匿名內部類來實作,因為它不會更短)。加法運算可以這樣表示:
IntBinaryOperator add = Integer::sum; // or (i1, i2) -> i1 i2
問題的型別(加法、乘法等)應隨機選擇
為此,首先,您需要定義一個Random物件。為了獲得給定范圍內的隨機整數,請使用nextInt()期望邊界的方法,并從邊界(獨占int)回傳一個值:0
rand.nextInt(RANGE)
為避免硬編碼,RANGE應定義為全域常量。
因為您的應用程式必須與用戶互動,所以每個操作都應該與將向用戶公開的名稱相關聯。
可以通過宣告一個record(具有 final 欄位和自動生成的建構式的特殊型別類 getters , hashCode/equals, toString())來完成。宣告記錄的語法非常簡潔:
public record Operation(String name, IntBinaryOperator operation) {}
表示算術運算的記錄可以存盤在串列中。您可以通過生成隨機索引(從0串列大小到串列大小)來選擇操作。
operations.get(rand.nextInt(operations.size()))
與常見的 getter 不同,編譯器為記錄生成的 getter 的名稱將與其欄位的名稱相同,即name()和operation()。
為了使用從記錄中檢索到的函式,您需要呼叫applyAsInt()它的方法,傳遞兩個先前生成的數字。
這就是它的樣子。
public class Operations {
public static final int RANGE = 100;
public static final Random rand = new Random();
public record Operation(String name, IntBinaryOperator operation) {}
public static final List<Operation> operations =
List.of(new Operation("add", Integer::sum), new Operation("sub", (i1, i2) -> i1 - i2),
new Operation("mult", (i1, i2) -> i1 * i2), new Operation("div", (i1, i2) -> i1 / i2));
public static void main(String[] args) {
// you code (instansiate a scanner, enclose the code below with a while loop)
for (int i = 0; i < 10; i ) {
Operation oper = operations.get(rand.nextInt(operations.size()));
int operand1 = rand.nextInt(RANGE);
int operand2 = rand.nextInt(RANGE);
System.out.println(operand1 " " oper.name() " " operand2); // exposing generated data to the user
int userInput = sc.nextInt(); // reading user's input
int result = oper.operation().applyAsInt(operand1,operand2); // exposing the result
System.out.println(result "\n__________________");
}
// termination condition of the while loop
}
}
這是用戶將看到的輸出示例:
38 add 67
105 // user input
105
_____________________
97 sub 15
...
uj5u.com熱心網友回復:
不幸的是,java 既不支持運算子多載也不支持中綴表示法,因此在源代碼中不可能這樣做。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/457766.html
上一篇:使用陣列,有沒有辦法優化這個PowerShell函式?
下一篇:Java中的變數不更新
