java - 字符类型的 if/else 语句

标签 java if-statement char

我想编写一个程序,输入从 1 到 4 的年份代码并输出年份级别。

注意:使用if...else语句且年份代码为字符类型。 (如果使用数组更好,我不允许使用数组,因为这是在条件控制结构中。这样做之后,我如何使用 switch....case 语句编写这个程序?

如何声明 char 并获取用户的输入?

import java.util.Scanner;
import java.io.*;

public class CharStatement {

    public static void main(String[] a) {

    char userInput = new char;
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Enter year code: ");  
    System.out.println("");

    if (char == 1) {
    System.out.println("First Year");
    System.out.println("Freshmen");     
    }
    else if ( char == 2) {
        System.out.println("Second Year");
        System.out.println("Sophomore");            
    }
    else if (char == 3) {
        System.out.println("Third Year");
        System.out.println("Junior");   
    }
    else if (char == 4) {
        System.out.println("Fourth Year");
        System.out.println("Senior");   
    }
    else {
        System.out.println("Invalid");
    }

}

最佳答案

在java中接受单个字符有点困惑。看看this了解更多相关信息。

您可以使用 int 执行相同的操作,如下所示,作为对代码的修改,

System.out.println("");
int choice  = keyboard.nextInt()   // accepts an integer from the user
if (choice == 1) {                 // check if the given input is equal to 1
    System.out.println("First Year");
    System.out.println("Freshmen");     
}
<小时/>

此外,您不能在 Java 中将变量命名为 char,因为它是 keyword .

关于java - 字符类型的 if/else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32484661/

相关文章:

c# - 如何获得角色的 "English name"?

java - LibGDX FreeTypeFontGenerator

java - 使用 RuntimeExceptions 进行错误处理是一个好习惯吗?

c - 我的 if else 语句有什么问题?

C : if-else about variables

c++ - 如何使用 C 字符串读取 .txt 文件?

c - char 数组初始值设定项错误中元素过多

java - 在泛型类中实例化泛型类

java:我正在尝试通过java程序创建任何abc.exe的快捷方式

c - 警告 : suggest parentheses around assignment used as truth value