您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,switch语句可以与其他控制结构(如if-else、循环等)结合使用,以实现更复杂的逻辑。以下是一些示例:
import java.util.Scanner;
public class SwitchIfElseExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number between 1 and 3: ");
int number = scanner.nextInt();
switch (number) {
case 1:
System.out.println("You entered 1.");
if (true) {
System.out.println("This is an if statement inside the case 1.");
}
break;
case 2:
System.out.println("You entered 2.");
break;
case 3:
System.out.println("You entered 3.");
if (false) {
System.out.println("This is an if statement inside the case 3.");
} else {
System.out.println("This is an else statement inside the case 3.");
}
break;
default:
System.out.println("Invalid number.");
}
}
}
import java.util.Scanner;
public class SwitchLoopExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number between 1 and 5 (0 to exit): ");
int number;
do {
System.out.print("Enter a number: ");
number = scanner.nextInt();
switch (number) {
case 1:
System.out.println("You entered 1.");
break;
case 2:
System.out.println("You entered 2.");
break;
case 3:
System.out.println("You entered 3.");
break;
case 4:
System.out.println("You entered 4.");
break;
case 5:
System.out.println("You entered 5.");
break;
case 0:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid number.");
}
} while (number != 0);
}
}
这些示例展示了如何在switch语句中使用if-else和循环控制结构。你可以根据需要修改这些示例,以实现更复杂的逻辑。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。