在Java中,Switch语句可以与其他控制结构(如if-else、循环等)结合使用,以实现更复杂的逻辑。以下是一些示例:
public class SwitchWithIfElse {
public static void main(String[] args) {
int number = 3;
String result;
switch (number) {
case 1:
result = "One";
break;
case 2:
result = "Two";
break;
default:
if (number > 3) {
result = "Greater than Three";
} else {
result = "Less than Three";
}
break;
}
System.out.println("Result: " + result);
}
}
public class SwitchWithForLoop {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
switch (number) {
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
break;
default:
System.out.println("Other");
break;
}
}
}
}
import java.util.Scanner;
public class SwitchWithWhileLoop {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number between 1 and 5: ");
int number = scanner.nextInt();
while (number > 0) {
switch (number) {
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
break;
default:
System.out.println("Other");
break;
}
System.out.print("Enter another number between 1 and 5 (0 to exit): ");
number = scanner.nextInt();
}
System.out.println("Exiting...");
scanner.close();
}
}
这些示例展示了如何在Java中将Switch语句与其他控制结构结合使用。根据实际需求,您可以根据需要组合不同的控制结构。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。