java - 将字符串转换为整数

标签 java if-statement syntax switch-statement

我需要将变量参数添加到已经有很多参数的 switch case 中的语法。下面提供了上下文。

我正在使用 switch case 将字符串答案更改为整数返回。而不是让用户回答

1.这个。
2. 别的事。

我希望答案看起来像

(是/否)

我之前用这样的代码完成过:

static public int getYN() {
    String answer = "";
    switch(keyboard.nextLine().substring(0, 1).toLowerCase()) {
        case "y":
            return 1;

        case "n":
            return 0;

        default:
            return 2;

    }
}



然后使用语句:

int getAnswer = getYN();
        System.out.println();

        if (getAnswer == 1) {
        System.out.println("Stuff.");
        test = 1;
        }
        else {
        System.out.println("Other stuff."); 
        System.out.println();
    }

但是,我不知道在哪里将字符串答案变量放入 switch case 中。通常,如果您没有使用许多其他参数,则只需

 switch(answer) {
}



最佳答案

内联检查,忘记有专门的方法来执行此检查。

    char getAnswer = keyboard.next().charAt(0);

    System.out.println();

    if (getAnswer == 'y' || getAnswer == 'Y') 
    {
        System.out.println("Stuff.");
        test = 1;
    }
    else if( getAnswer == 'n' || getAnswer == 'N')
    {
        System.out.println("Other stuff."); 
        System.out.println();
    }

如果你绝对必须使用开关:

    char getAnswer = keyboard.next().charAt(0);

    switch(getAnswer)
    {
        case 'y':
          System.out.println("Stuff.");
          test = 1;
          break;
        case 'n':
          System.out.println("Other stuff."); 
          System.out.println();
          break;
    }

关于java - 将字符串转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20252141/

相关文章:

json - 您可以在 JSON 对象中使用尾随逗号吗?

java - 将内容放在透明操作栏上

java - JPA 无法使用 START_OBJECT TOKEN 作为搜索键

python - 无法解析余数 : '{{' from '{{'

r - R 中具有多个条件的 Countif

mysql - 在 IF 语句中从同一个表中选择

java - 如何在java中创建分数

java - 如何避免 LOCATION_SERVICE 的 NullPointerException?

java:防止恶意更改或修改java包中的某些公共(public)函数

mysql - 如何在 MySQL 中自动增加 +1 特定行数