您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,switch语句可以与其他控制结构(如if-else、for、while和do-while)结合使用,以实现更复杂的逻辑。以下是一些示例:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number between 1 and 3: ");
int num = scanner.nextInt();
switch (num) {
case 1:
System.out.println("You entered 1.");
break;
case 2:
System.out.println("You entered 2.");
break;
default:
if (num < 1 || num > 3) {
System.out.println("Invalid number. Please enter a number between 1 and 3.");
}
}
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a character: ");
char ch = scanner.next().charAt(0);
for (int i = 0; i < 5; i++) {
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
System.out.println(ch + " is a vowel.");
break;
default:
System.out.println(ch + " is a consonant.");
}
}
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number between 1 and 5: ");
int num = scanner.nextInt();
while (num > 0) {
switch (num) {
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;
default:
System.out.println("Invalid number. Please enter a number between 1 and 5.");
}
num--;
}
}
}
这些示例展示了如何在Java中将switch语句与其他控制结构结合使用。根据需要,您可以根据自己的需求组合不同的控制结构。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
开发者交流群:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。