我想编写一个程序,输入从 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/