我试图在给定位置打印出两个数组。
该计划分为两部分。要求用户输入字符串(学生姓名)和int(学生成绩)的用户被要求搜索输入的姓名并打印出学生姓名和成绩
到目前为止,我无法打印任何内容。
这是我填充数组的代码......
System.out.println("Please Enter The Number Of Students In The Class!!");
int numberOfStudents = input.nextInt();
String []studentNames = new String[numberOfStudents];
int [] StudentGrades = new int[numberOfStudents];
int i;
for (i =0; i<numberOfStudents; i++)
{
System.out.println("Enter Student Name!");
studentNames[i]= input.next();
System.out.println("_________________");
System.out.println("Enter Student Grade");
StudentGrades[i] = input.nextInt();
System.out.println("_________________");
}
...这用于搜索名称:
Scanner input = new Scanner(System.in);
String nameInput = input.next();
int cheak;
cheak = 0;
for ( String student : studentNames)
{
if (nameInput.equals(student))
{
cheak++;
}
}
if (cheak !=0)
{
System.out.println("Name Found ");
}
else
{
System.out.println("Name Not Found");
}
现在我要打印在搜索中输入的学生姓名和相应的成绩。
我如何做到这一点?
答案 0 :(得分:0)
尝试以下方法:
for ( String student : studentNames) {
if (nameInput.equals(student)) {//if the student is found, stop the loop
break;
}
cheak++;
}
if (cheak != studentNames.length){
System.out.println("Name Found ");
System.out.println("The name is: " + studentNames[cheak]);
System.out.println("Grade is: " + studentGrades[cheak]);
} else {
System.out.println("Name Not Found");
}
答案 1 :(得分:0)
您必须在studentNames数组中保留目标名称索引的记录。 您可以通过以下方式修改循环以获取cheak变量中的索引 -
cheak = 0;
for ( String student : studentNames)
{
if (nameInput.equals(student))
{
break;
}
cheak++;
}
if (cheak != numberOfStudents)
{
System.out.println("Name Found. Name = " + studentNames[cheak] + " Grade = " + StudentGrades[cheak]);
}
else
{
System.out.println("Name Not Found");
}