*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 Management
Here is a sample run:
Enter two characters: M1
Mathematics Freshman
Enter two characters: C3
Computer Science Junior
Enter two characters: T3
Invalid input
下面是参考答案代码:
import java.util.*;
public class StudentMajorAndStatusQuestion18 {
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();
}
}
运行效果:
注:编写程序要养成良好习惯
1.文件名要用英文,具体一点
2.注释要英文
3.变量命名要具体,不要抽象(如:a,b,c等等),形式要驼峰化
4.整体书写风格要统一(不要这里是驼峰,那里是下划线,这里的逻辑段落空三行,那里相同的逻辑段落空5行等等)
5.普通变量,方法名要小驼峰,类名要大驼峰,常量要使用全部大写加上下划线命名法
6.要学习相应的代码编辑器的一些常用快捷键,如:快速对齐等等