[英]How do i use switch statement inside a method such that the method can return a char value which is acquired by the switch statement inside it?
[英]Can I put a return statement inside a switch statement?
我是否允許有一個switch
語句來決定返回什么? 例如,我想根據我的隨機生成器提出的內容返回不同的內容。 Eclipse給我一個錯誤,希望我將return
語句放在switch
之外。
我的代碼:
public String wordBank() { //Error here saying: "This method must return a type of string"
String[] wordsShapes = new String[10];
wordsShapes[1] = "square";
wordsShapes[2] = "circle";
wordsShapes[3] = "cone";
wordsShapes[4] = "prisim";
wordsShapes[5] = "cube";
wordsShapes[6] = "cylinder";
wordsShapes[7] = "triangle";
wordsShapes[8] = "star";
wordsShapes[9] = "moon";
wordsShapes[10] = "paralellogram";
Random rand = new Random();
int i = rand.nextInt(11);
if (i == 0) {
i = rand.nextInt(11);
}
switch (i) {
case 1:
return wordsShapes[1].toString();
case 2:
return wordsShapes[2].toString();
case 3:
return wordsShapes[3].toString();
case 4:
return wordsShapes[4].toString();
case 5:
return wordsShapes[5].toString();
case 6:
return wordsShapes[6].toString();
case 7:
return wordsShapes[7].toString();
case 8:
return wordsShapes[8].toString();
case 9:
return wordsShapes[9].toString();
case 10:
return wordsShapes[10].toString();
}
}
對不起,但在這種情況下,為什么不只是這樣做:
return wordsShapes[i].toString();
這樣你可以避免開關和所有。
希望有所幫助,
你可以把return
放在switch
但在這種情況下你不需要使用switch
。
問題不在於你在switch
語句中有return語句,這完全沒問題,但是在switch語句之后你沒有返回。 如果你的switch語句完成而沒有返回,現在會發生什么?
Java規則要求通過值返回函數的所有路徑都會遇到return
語句。 在您的情況下,即使您知道i
的值將始終是一個將導致從交換機return
的值,Java編譯器也不夠聰明,無法確定。
(ASIDE:順便說一句,你實際上並沒有阻止生成值0;也許你的if
應該是一段while
。)
附錄:如果您有興趣,這是一個實現。 有關實例,請參見http://ideone.com/IpIwis 。
import java.util.Random;
class Main {
private static final Random random = new Random();
private static final String[] SHAPES = {
"square", "circle", "cone", "prism", "cube", "cylinder", "triangle",
"star", "moon", "parallelogram"
};
public static String randomShapeWord() {
return SHAPES[random.nextInt(SHAPES.length)];
}
public static void main(String[] args) {
for (int i = 0; i < 20; i++) {
System.out.println(randomShapeWord());
}
}
}
請注意在函數外部定義隨機數生成器的最佳實踐。
return語句將從使用它的整個函數返回。所以我認為如果你想在switch中使用return語句,那么在交換機下面不能有其他有用的代碼行是很好的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.