简体   繁体   English

switch语句如何在带有字符串参数的Java 1.5中工作?

[英]How does switch statements work in java 1.5 with string arguments?

Can i implement switch statements(by passing string arguments) in java 5 without making use of enums?I tried doing it using hashcode but i got an error 我可以在不使用枚举的情况下在Java 5中实现switch语句(通过传递字符串参数)吗?我尝试使用哈希码进行操作,但出现错误

package com.list;

import java.util.Scanner;

public class SwitchDays implements Days {

    static final int str = "sunday".hashCode();




    public static void main(String[] args) {


          Scanner in=new Scanner(System.in);    
            String day= in.nextLine();

        switch (day.hashCode()) {

        case str:
            System.out.println(day);

            break;

        default:
            break;
        }
            }


}

str in case str given an error: 如果出现str错误,则str:

case expressions must be constant expressions

Please guide. 请指导。

The problem is that str is referring to the expression "sunday".hashCode() , which is not a compile time constant expression as described by the JLS: 问题在于str引用的是表达式"sunday".hashCode() ,这不是JLS所描述的编译时常量表达式

A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following: ... Qualified names (§6.5.6.2) of the form TypeName . 常数表达式是表示原始类型值或String的值的表达式,该值不会突然完成,并且仅使用以下内容组成:... TypeName形式的合格名称(第6.5.6.2节)。 Identifier that refer to constant variables (§4.12.4). 引用常量变量的标识符(第4.12.4节)。

When you check the definition of constant variables: 在检查常量变量的定义时:

A constant variable is a final variable of primitive type or type String that is initialized with a constant expression (§15.28). 常量变量是使用常量表达式 (第15.28节) 初始化的原始类型或String类型的最终变量。 Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9), and definite assignment (§16 (Definite Assignment)). 变量是否为常数变量可能与类初始化(第12.4.1节),二进制兼容性(第13.1节,第13.4.9节)和确定分配(第16节(确定分配))有关。

Since "sunday".hashCode() does not meet this requirements, you get the error. 由于"sunday".hashCode()不满足此要求,因此会出现错误。

If you would change "sunday".hashCode() to a real compile time constant like 3 it would compile. 如果将"sunday".hashCode()更改为像3这样的实际编译时间常数,它将进行编译。

The most straight forward solution is to make an enum, ie. 最直接的解决方案是创建一个枚举,即。

enum Days{
    sunday, monday;
}

Then it could be used as: 然后可以用作:

Day d = Day.valueOf("sunday");
switch(d){
    case sunday:
        System.out.println("ONE");
        break;
    case monday:
        System.out.println("TWO");
        break;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM