Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.2 kB
2
Indexable
Never
import java.util.ArrayList;
import java.util.Scanner;

public class StudentMarks {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        // create arrays for student names and totalstudents
        String[] courseNames = new String[10];
        int[] totalstudents = new int[10];

        // prompt user to input data for each array element
        for (int i = 0; i < courseNames.length ; i++) {
            System.out.print("Enter course name for element " + (1+i) + ": ");
            courseNames[i] = scanner.nextLine();
            System.out.print("Enter total students for " + courseNames[i] + ": ");
            totalstudents[i] = scanner.nextInt();
            scanner.nextLine(); // consume newline character
        }
    
        // display data for each array element in a table
        System.out.printf("%-30s\t\t\t\t\t%s %n", "Course Name", "Total Students");
        for (int i = 0; i < courseNames.length; i++) {
            System.out.printf("%-30s\t\t\t\t\t%d %n", courseNames[i], totalstudents[i]);
        }

        // prompt user to search for a specific mark
        System.out.print("Enter a total students to search for: ");
        int searchTotal = scanner.nextInt();

        // perform linear search to find the indices of the matching totalstudents without arraylist
        int[] indices = new int[10];
        int count = 0;
        for (int i = 0; i < totalstudents.length; i++) {
            if (totalstudents[i] == searchTotal) {
                indices[count] = i;
                count++;
            }
        }

// print the corresponding names from the courseNames array
        if (count > 0) {
            System.out.println("course name for total student is: " + searchTotal + ":");
            for (int i = 0; i < count; i++) {
                int index = indices[i];
                System.out.println(courseNames[index] );
            }
        } else {
            System.out.println("Sorry, there is no data for total student " + searchTotal + " right now.");
        }

        scanner.close();
    }
}