![](/img/trans.png)
[英]How can I select a random element from an array based on the value of one of it's object properties?
[英]How can I select a value from an array?
如何從數組中選擇一個值? 例如這個String[] ans = {"+", "-", "/", "*"};
然后我想選擇"+"
。
public static void main(String[] args) {
String[] ans = {"+","-","/","*"};
Random random = new Random();
Scanner calcu = new Scanner(System.in);
System.out.print("Enter First number: ");
numOne = calcu.nextInt();
System.out.print("Enter Second number: ");
numTwo = calcu.nextInt();
System.out.print("Choose an Operator to use");
}
您可以將ans[0]
用於“+”,依此類推。
ans[0] = "+";
ans[1] = "-";
ans[2] = "/";
ans[3] ="*";
在您的情況下,此代碼將幫助您:
public static void main(String[] a) {
String[] ans = {"+","-","/","*"};
double result = 0;
Scanner calcu = new Scanner(System.in);
System.out.print("Enter First number: ");
int numOne = calcu.nextInt();
System.out.print("Enter Second number: ");
int numTwo = calcu.nextInt();
System.out.print("Choose an Operator to use");
String oparation= calcu.next();
if(oparation.equals(ans[0])){
result = numOne + numTwo;
}
else if(oparation.equals(ans[1])){
result = numOne - numTwo;
}
else if(oparation.equals(ans[2])){
result = numOne / numTwo;
} else if(oparation.equals(ans[3])){
result = numOne * numTwo;
}
System.out.println("result is " + result);
}
如果您想使用switch
語句獲得相同的結果:
public static void main(String[] a) {
double result = 0;
Scanner calcu = new Scanner(System.in);
System.out.print("Enter First number: ");
int numOne = calcu.nextInt();
System.out.print("Enter Second number: ");
int numTwo = calcu.nextInt();
System.out.print("Choose an Operator to use");
String oparation= calcu.next();
switch(oparation){
case "+" :
result = numOne + numTwo;
break;
case "-" :
result = numOne - numTwo;
break;
case "/" :
result = numOne / numTwo;
break;
case "*" :
result = numOne * numTwo;
break;
}
System.out.println("result is " + result);
}
但是,使用switch
語句,如果要比較case ans[0]:
類的變量case ans[0]:
而不是case "*"
,那么你可以使用enum
。
您實現它的方式,您需要向用戶顯示這樣的列表:
1: +
2: -
3: /
4: *
當他們選擇一個數字時,您可以使用ans[input-1]
確定運算符。
您可以通過以下get方法訪問它:
ans[i]; // for getting first element you should set i to 0
ans[indexThatYouWantToaccess]
確保數組索引從0開始
ans[0] -> +
ans[1] -> -
ans[2] -> /
ans[3] -> *
要引用數組中的單個項目,請使用括號表示要引用的項目的位置,從0開始。
所以
string txt = ans[0];
會屈服+
和string txt = ans[2];
會產量/
你有數組作為String[] ans = {"+","-","/","*"};
這意味着數組的索引從zero
到array.length-1
包含您插入到數組中的元素,以便從元素中獲取元素只是迭代數組或者只是通過數組的索引獲取元素
for(String value : ans){
System.out.println(value);
}
要么
for(int i=0;i<ans.length-1;i++){
System.out.println(ans[i]);
}
或者簡單
String value = ans[index];//index must be from 0 to arrayLength-1
System.out.println("value "+value);
ans[0]
將返回第一個(0,因為第一個元素以0開頭,而不是1開始)數組元素, ans[1]
第二個,依此類推。
您可以通過引用其元素的索引從數組中選擇一個值。 數組元素(數組中的內容)從數組的0到length-1編號/索引。
在這種情況下,如果你想要數組的第一個元素,你會做:
ans[0]
如果你想要數組的最后一個元素:
ans[ans.length-1]
請查看本指南,了解陣列的精彩介紹。 http://www.cs.cmu.edu/~adamchik/15-121/lectures/Arrays/arrays.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.