Java Switch如何与其他控制结构结合

发布时间:2025-03-02 00:35:53 作者:小樊
阅读:104
Java开发者专用服务器,限时0元免费领! 查看>>

在Java中,switch语句可以与其他控制结构(如if-else、for、while和do-while)结合使用,以实现更复杂的逻辑。以下是一些示例:

  1. switch与if-else结合:
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.");
                }
        }
    }
}
  1. switch与for结合:
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.");
            }
        }
    }
}
  1. switch与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 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元/月。点击查看>>

推荐阅读:
  1. 《Java架构筑基》从Java基础讲起——Java基础知识
  2. java基本控制语句 有哪些

开发者交流群:

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:Java Switch语句使用技巧有哪些

下一篇:Java异常处理中如何传递异常信息

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》
开发者交流群×