Write a program that keeps track of students in a class. The program will prompt the teacher to enter the total number of students. Then the teacher will input the last names of all the students (multiples of the same last name are possible). Next, the program will ask the teacher to enter a name. The program will print out the indices of all matching last names in the array
And I have successfully coded this situation:
import java.util.Scanner; //Imports the Scanner public class exercise4 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); //Creates a new scanner called 'scan' int students; String search; System.out.print("Please enter the total number of students: "); students = scan.nextInt(); String[] names = new String[students]; for (int x = 0; x < names.length; x++) { System.out.print("Enter the last name: "); names[x] = scan.nextLine(); } System.out.print("Enter a name to search for: "); search = scan.nextLine(); for (int x = 0; x < names.length; x++) { if (names[x].equals(search)) { System.out.print(search + " is at index " + x); } } } }
But the problem that I am currently dealing with is the output of this program. The expected output should be:
But the output that I am having is wrong:
As you can see, “Enter the last name” prints out twice so I’m assuming it does not declare the value of names[0] at all but instead it initially gets stored into names1 and so on, which is probably also why it shows that Branson is at index 6 instead of 5. Would someone be able to point out what is the cause of this issue?