通过从用户那里获取输入,在 switch 语句中使用字符串 [英] Using string in switch statement, by taking input from user

查看:33
本文介绍了通过从用户那里获取输入,在 switch 语句中使用字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,在编译期间,我收到不兼容的类型"错误.如果我使用其他逻辑,如 charAt(0) 和所有,这工作正常.没有办法在java switch 语句中使用字符串吗?我使用的是 JDK 7.

In the below code, during compilation, i get 'incompatible types' error. If I user other logic, like charAt(0) and all, this works fine. Isn't there any way to use string in a java switch statement? I'm using JDK 7.

谢谢.

import java.util.Scanner;

class cCode
{
    public static void Main(String args [])`
    {
        System.out.println("Enter country code\nChoices: IND, USA, JPN, NZ, WI");
        Scanner cc = new Scanner(System.in);
        switch(cc)
        {
            case "IND":
                System.out.println(cc+" refers to INDIA");
                break;  
            case "USA":
                System.out.println(cc+" refers to UNITED STATES");
                break;
            case "JPN":
                System.out.println(cc+" refers to JAPAN");
                break;
            case "NZ":
                System.out.println(cc+" refers to NEW ZEALAND");
                break;
            case "WI":
                System.out.println(cc+" refers to WEST INDIES");
                break;
            default:
                System.out.println("Invalid choice");
        }
    }
}

推荐答案

您可以通过接受用户的输入来使用以下代码.

You can use below code by taking input from user.

import java.util.Scanner;
public class cCode {

public static void main(String args[]) {

    System.out.println("Enter country code\nChoices: IND, USA, JPN, NZ, WI");
    Scanner cc = new Scanner(System.in);
    String txt = cc.nextLine();
    switch (txt) {
        case "IND":
            System.out.println(txt + " refers to INDIA");
            break;

        case "USA":
            System.out.println(txt + " refers to UNITED STATES");
            break;

        case "JPN":
            System.out.println(txt + " refers to JAPAN");
            break;

        case "NZ":
            System.out.println(txt + " refers to NEW ZEALAND");
            break;

        case "WI":
            System.out.println(txt + " refers to WEST INDIES");
            break;

        default:
            System.out.println("Invalid choice");
   }
}}

这篇关于通过从用户那里获取输入,在 switch 语句中使用字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆