第四章第十八题(学生的专业和年级)(Student major and status)
-
*4.18(学生的专业和年级)编写一个程序,提示用户输入两个字符,显示这两个字符代表的专业以及年级。第一个字符表示专业,第二个是一个数字字符1、2、3、4,分别表示该学生是大一、大二、大三还是大四。
假设下面的字符用于表示专业:
M:数学
C:计算机科学
I:信息技术下面是一个运行示例:
Enter two characters: M1
Mathematics Freshman
Enter two characters: C3
Computer Science Junior
Enter two characters: T3
Invalid input*4.18(Student major and status) Write a program that prompts the user to enter two characters and displays the major and status represented in the characters. The first character indicates the major and the second is number character 1, 2, 3, 4, which indicates whether a student is a freshman, sophomore, junior, or senior.
Suppose the following characters are used to denote the majors:
M:Mathematics
C: Computer Science
I: Information ManagementHere is a sample run:
Enter two characters: M1
Mathematics Freshman
Enter two characters: C3
Computer Science Junior
Enter two characters: T3
Invalid input -
参考代码:
package chapter04;
import java.util.Scanner;
public class Code_18 {
public static void main(String[] args) {
String studentInfo;
char studentMajor, studentStatus;
System.out.print("Enter two characters:");
Scanner input = new Scanner(System.in);
studentInfo = input.next();
if(studentInfo.length() != 2)
System.exit(1);
studentMajor = studentInfo.charAt(0);
studentStatus = studentInfo.charAt(1);
if('M' == studentMajor)
{
if('1' == studentStatus)
System.out.println("Mathematics Freshman");
else if ('2' == studentStatus) {
System.out.println("Mathematics Sophomore");
}
else if ('3' == studentStatus) {
System.out.println("Mathematics Junior");
}
else if ('4' == studentStatus) {
System.out.println("Mathematics Senior");
}
else {
System.out.println("Invalid input");
}
}
else if('C' == studentMajor)
{
if('1' == studentStatus)
System.out.println("Computer Science Freshman");
else if ('2' == studentStatus) {
System.out.println("Computer Science Sophomore");
}
else if ('3' == studentStatus) {
System.out.println("Computer Science Junior");
}
else if ('4' == studentStatus) {
System.out.println("Computer Science Senior");
}
else {
System.out.println("Invalid input");
}
}
else if('I' == studentMajor)
{
if('1' == studentStatus)
System.out.println("Information Management Freshman");
else if ('2' == studentStatus) {
System.out.println("Information Management Sophomore");
}
else if ('3' == studentStatus) {
System.out.println("Information Management Junior");
}
else if ('4' == studentStatus) {
System.out.println("Information Management Senior");
}
else {
System.out.println("Invalid input");
}
}
else
System.out.println("Invalid input");
input.close();
}
}
- 结果显示:
Enter two characters:M1
Mathematics Freshman
Process finished with exit code 0