该程序将询问用户学生姓名和成绩,然后同时显示两者。用户输入的值存储在数组名称和数组等级中。我使用计数器控制的 for 循环将用户输入收集到数组中。如果我想为每个学生输入多个成绩怎么办?编程相当新手,任何关于如何做到这一点的输入或想法将不胜感激......
public class Five {
public static void main(String[] args) {
int students;
Scanner input = new Scanner(System.in); //created input scanner
System.out.println("How many students are on your roster? If you wish to exit please type 00: ");// Initializing statement for program************
students = input.nextInt();
if(students == 00) { //Exit program****************
System.out.println("Maybe Next Time!!");
System.exit(0);
}
String[] names = new String[students];// Array names*******
String[]grade = new String[students]; //Array grade********
// Use Counter to go through Array**************************
for(int counter =0; counter < students; counter++){
System.out.println("Enter the name of a student: " + (counter +1));
names [counter] = input.next();
System.out.println("Now enter that students grade A, B, C, D OR F: ");
grade [counter] = input.next();
}
input.close();// End Scanner object
//Use For loop for Printing names and grades entered by the user**************
System.out.println("Your students names and grades are as follows: ");
for(int counter =0; counter < students; counter++){
System.out.println("Name: " + names[counter]);
System.out.println("Grade: " + grade[counter]);
}
}
}
您可以使用不规则数组来输入多个成绩您需要声明它,因此这里有一种方法可以做到这一点。
String[] names = new String[students];// Array names*******
String[][]grade = new String[names][]; //Array grade********
for(int i=0; i<names[i];i++)
{System.out.println("How many grades will you enter for "+names[i]+"?")
int temp=input.nextInt();
for(int j=0; j<names[i][temp-1];j++){
grad[i][j]=input.next();
}}
您可能应该创建一个学生类和一个成绩类并将它们存储为对象。使用数据结构,您最好的选择是哈希图。
HashMap<String, List<String>> grades = new HashMap<>();
grades.put("Jack", new ArrayList<>());
grades.get("Jack").add("A");
你可以在这里找到更多关于HashMap的信息