Question

How would you make it hold both the student's name and their teacher? then be able...

How would you make it hold both the student's name and their teacher? then be able to sort based on either the students name or who their teacher is?

import java.util.Scanner; //for taking user input

public class StudentName{ //you can change class name

public static void main(String[] args);

{

Scanner in = new Scanner(System.in);

//finding length of array studentNames

System.out.print("how many students? :") ;

int totalStudents = in. nextInt() ;

String[] studentNames = new String[totalStudents] ;

//input user name

for(int j=0;j<studentNames.length;j++)

{

System. out. println(j) ;

System. out.print("enter student name:") ;

studentNames[j]=in.nextline();

}

for (String element : studentName)

{

System. out. println(element) ;

}

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Code:

import java.util.Scanner;
import java.util.Arrays;
class Student
{
   // Class variables for student and their teacher names
   public String studentName;
   public String teacherName;
  
   // Constructor parameters
   Student(String studentName,String teacherName)
   {
       this.studentName = studentName;
       this.teacherName = teacherName;
   }
  
   public String toString()
   {
       return "Student:" + studentName + " Teacher:" + teacherName;
   }
  
   void setStudentName(String newStudentName)
   {
       studentName = newStudentName;
   }
  
   void setTeacherName(String newTeacherName)
   {
       teacherName = newTeacherName;
   }
  
}

// An class of Generic Type
class CustomArrayList<E>
{
   // This variable is used to create an Array of type object of size initial list capacity
   private static final int INITIAL_LIST_CAPACITY = 5;
   // An array of type Object
   private Object data[] = {};
   // This variable is used to store the size of the custom arrayList
   private int size = 0;
  
   // Constructor
   public CustomArrayList()
   {
       // Initializing the array with size of initial list capacity
       data = new Object[INITIAL_LIST_CAPACITY];
   }
  
   // An method to add values to the custom arrayList
   public void add(E e)
   {
       // If there is no space to add values to the arrayList, double the size of the arrayList
       if(size == data.length)
       {
           increaseCapacity();
       }
      
       // Adding the value to the arrayList
       data[size++] = e;
   }
  
   @SuppressWarnings("unchecked")
   public E get(int index)
   {
       if ( index <0 || index>= size)
       {
           throw new IndexOutOfBoundsException("Index: " + index + ", Size " + index);
       }
       return (E) data[index];
   }
  
   public void set(int index,Student s)
   {
       if ( index <0 || index>= size)
       {
           throw new IndexOutOfBoundsException("Index: " + index + ", Size " + index);
       }
      
       data[index] = s;
   }
  
   // An method to remove values from the custom arrayList
   public Object remove(int index)
   {
       // If the value of the index is 0 or negative
       if(index < 0 || index >= size)
       {
           // Throw an IndexOutOfBoundsException if the index is invalid
           throw new IndexOutOfBoundsException("Index: " + index + ", Size " + index);
       }
      
       Object removedElement = data[index];
      
       // Update the list
       for(int i = index;i<size-1;i++)
       {
           data[i] = data[i+1];
       }
      
       // Decrementing the size of the list by 1
       size--;
      
       // Returning the removed element
       return removedElement;
   }
  
   // An method to increase the list capacity
   private void increaseCapacity()
   {
       // Calculating the new capacity
       int newIncreasedCapacity = data.length * 2;
       // Updating the list
       data = Arrays.copyOf(data, newIncreasedCapacity);
   }
  
   // Displaying the elements of the list
   public void display()
   {
       // Printing the elements of the list
       for(int i=0;i<size;i++)
       {
           System.out.println(data[i]);
       }
   }
}


public class StudentData2
{
   // QuickSort where the comparison is based on student name
   static int QuickSortStudentName(CustomArrayList<Student> s, int low, int high)
{
Student pivot_data = s.get(high);
       // index of smaller element
int i = (low-1);
for (int j=low; j<high; j++)
{
              
           if ( s.get(j).studentName.compareTo(pivot_data.studentName) <=0)
           {
               i++;
               // swap student objects at index i and j
               Student temp = new Student(s.get(i).studentName,s.get(i).teacherName);
               s.set(i,s.get(j));
               s.set(j,temp);
           }              

}

  // swap student objects at index i+1 and high
       Student temp = new Student(s.get(i+1).studentName,s.get(i+1).teacherName);
       s.set(i+1,s.get(high));
       s.set(high,temp);
return i+1;
}
  
// QuickSort where the comparison is based on student name
   static int QuickSortTeacherName(CustomArrayList<Student> s, int low, int high)
{
       Student pivot_data = s.get(high);
       // index of smaller element
int i = (low-1);
       // Sort based on teacher name
       for (int j=low; j<high; j++)
{
           if ( s.get(j).teacherName.compareTo(pivot_data.teacherName) <=0)
           {
               i++;
               // swap student objects at index i and j
               Student temp = new Student(s.get(i).studentName,s.get(i).teacherName);
               s.set(i,s.get(j));
               s.set(j,temp);
           }
              
       }
       // swap student objects at index i+1 and high
       Student temp = new Student(s.get(i+1).studentName,s.get(i+1).teacherName);
       s.set(i+1,s.get(high));
       s.set(high,temp);
       return i+1;
   }
  
   static void sort(CustomArrayList<Student> s, int low, int high,int choice)
{
       if(choice==1)
       {
           if (low < high)
           {
               /* pi is partitioning index, Student object at index pi is now at right place */
               int pi = QuickSortStudentName(s, low, high);
  
               // Recursively sort elements before
               // partition and after partition

               sort(s, low, pi-1,1);
               sort(s, pi+1, high,1);
           }
       }
      
       else if(choice==2)
       {
           if (low < high)
           {
               /* pi is partitioning index, Student object at index pi is now at right place */
               int pi = QuickSortTeacherName(s, low, high);
  
               // Recursively sort elements before
               // partition and after partition

               sort(s, low, pi-1,2);
               sort(s, pi+1, high,2);
           }          
       }
}  
  
   public static void main(String[] args)
   {
       // Creating an object of Custom arrayList
       CustomArrayList<Student> students = new CustomArrayList<Student>();
      
       // Scanner object which is used to read inputs
       Scanner in = new Scanner(System.in);
       // Prompting the user to enter number of students data to be entered
       System.out.print("how many students?:");
       // Reading the input
       int totalStudents = Integer.parseInt(in.nextLine());
      
       // This for loop is iterated totalStudents times
       for(int j = 0; j<totalStudents;j++)
       {
           // Prompting the user to enter student name
           System.out.printf("Enter name of student %d:",j+1);
           // Reading the student name
           String studentName = in.nextLine();
           // Prompting the user to enter teacher name
           System.out.printf("Enter name of the teacher for student %d:",j+1);
           // Reading the teacher name
           String teacherName = in.nextLine();
          
           // Adding the data to the custom arrayList
           students.add(new Student(studentName,teacherName));
       }
      
       // Prompting the user to enter their choice for sort
       System.out.println("Enter 1 to sort the array based on student name");
       System.out.println("Enter 2 to sort the array based on teacher name");
       System.out.print("Enter your choice:");
      
       // Reading the choice
       int choice = in.nextInt();
      
       // If choice is 1
       if(choice==1)
       {
           // Sort the array based on student name
           sort(students,0,totalStudents-1,1);
           System.out.println("The array after sort based on student name:");
       }
      
       // If choice is 2
       else if(choice==2)
       {
           // Sort the array based on teacher name
           sort(students,0,totalStudents-1,2);
           System.out.println("The array after sort based on teacher name:");
       }
      
       // If the choice is not either 1 or 2
       else
       {
           System.out.println("Invalid choice");
           // Terminating the program
           System.exit(0);
       }
students.display();
   }
}

OUTPUT:

Add a comment
Know the answer?
Add Answer to:
How would you make it hold both the student's name and their teacher? then be able...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • java programming how would i modify the code below to add a GUI (with a main menu with graphics and buttons, etc...) and include an option to print a list of all students added in a grid format and sh...

    java programming how would i modify the code below to add a GUI (with a main menu with graphics and buttons, etc...) and include an option to print a list of all students added in a grid format and short by name, course, instructor, and location. ///main public static void main(String[] args) { Scanner in = new Scanner(System.in); ArrayList<Student>students = new ArrayList<>(); int choice; while(true) { displayMenu(); choice = in.nextInt(); switch(choice) { case 1: in.nextLine(); System.out.println("Enter Student Name"); String name...

  • You will create a class to keep student's information: name, student ID, and grade. The program...

    You will create a class to keep student's information: name, student ID, and grade. The program will have the following functionality: - The record is persistent, that is, the whole registry should be saved on file upon exiting the program, and after any major change. - The program should provide the option to create a new entry with a student's name, ID, and grade. - There should be an option to lookup a student from his student ID (this will...

  • Below I have my 3 files. I am trying to make a dog array that aggerates...

    Below I have my 3 files. I am trying to make a dog array that aggerates with the human array. I want the users to be able to name the dogs and display the dog array but it isn't working. //Main File import java.util.*; import java.util.Scanner; public class Main {    public static void main(String[] args)    {    System.out.print("There are 5 humans.\n");    array();       }    public static String[] array()    {       //Let the user...

  • JAVA Can you make this return the first letter of  first and last name capitalized? import java.io.File;...

    JAVA Can you make this return the first letter of  first and last name capitalized? import java.io.File; import java.io.IOException; import java.util.*; public class M1 {    public static void main(String[] args) {        //scanner input from user    Scanner scanner = new Scanner(System.in); // System.out.print("Please enter your full name: "); String fullname = scanner.nextLine(); //creating a for loop to call first and last name separately int i,k=0; String first="",last=""; for(i=0;i<fullname.length();i++) { char j=fullname.charAt(i); if(j==' ') { k=i; break; } first=first+j;...

  • In this same program I need to create a new method called “int findItem(String[] shoppingList, String...

    In this same program I need to create a new method called “int findItem(String[] shoppingList, String item)” that takes an array of strings that is a shopping list and a string for an item name and searches through the “shoppingList” array for find if the “item” exists. If it does exist print a confirmation and return the item index. If the item does not exist in the array print a failure message and return -1. import java.util.Scanner; public class ShoppingList...

  • Complete the do-while loop to output 0 to countLimit. Assume the user will only input a...

    Complete the do-while loop to output 0 to countLimit. Assume the user will only input a positive number. import java.util.Scanner; public class CountToLimit { public static void main (String [] args) { Scanner scnr = new Scanner(System.in); int countLimit = 0; int printVal = 0; // Get user input countLimit = scnr.nextInt(); printVal = 0; do { System.out.print(printVal + " "); printVal = printVal + 1; } while ( /* Your solution goes here */ ); System.out.println(""); return; } }

  • I need to add a method high school student, I couldn't connect high school student to...

    I need to add a method high school student, I couldn't connect high school student to student please help!!! package chapter.pkg9; import java.util.ArrayList; import java.util.Scanner; public class Main { public static Student student; public static ArrayList<Student> students; public static HighSchoolStudent highStudent; public static void main(String[] args) { int choice; Scanner scanner = new Scanner(System.in); students = new ArrayList<>(); while (true) { displayMenu(); choice = scanner.nextInt(); switch (choice) { case 1: addCollegeStudent(); break; case 2: addHighSchoolStudent(); case 3: deleteStudent(); break; case...

  • /*--------------------------------------------------------------------------- // AUTHOR: // SPECIFICATION: This program is for practicing the use of classes, constructors, //...

    /*--------------------------------------------------------------------------- // AUTHOR: // SPECIFICATION: This program is for practicing the use of classes, constructors, // helper methods, and the this operator. // INSTRUCTIONS: Read the following code skeleton and add your own code // according to the comments //-------------------------------------------------------------------------*/ import java.util.Scanner; public class { public static void main(String[] args) { // Let's make two students using all two constructors // Write code to create a new student alice using constructor #1 //--> Student alice = // Write code to...

  • import java.util.Scanner; public class TriangleMaker {    public static void main(String[] args) {        //...

    import java.util.Scanner; public class TriangleMaker {    public static void main(String[] args) {        // TODO Auto-generated method stub        System.out.println("Welcome to the Triangle Maker! Enter the size of the triangle.");        Scanner keyboard = new Scanner(System.in);    int size = keyboard.nextInt();    for (int i = 1; i <= size; i++)    {    for (int j = 0; j < i; j++)    {    System.out.print("*");    }    System.out.println();    }    for (int...

  • import java.util.Scanner; // TASK #1 Add the file I/O import statement here /** This class reads...

    import java.util.Scanner; // TASK #1 Add the file I/O import statement here /** This class reads numbers from a file, calculates the mean and standard deviation, and writes the results to a file. */ public class StatsDemo { // TASK #1 Add the throws clause public static void main(String[] args) { double sum = 0; // The sum of the numbers int count = 0; // The number of numbers added double mean = 0; // The average of the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT