Beginner Java (getting class assignment to compile) - java

This is a lab I am working for for a CSE 201. The program is supposed to read information about students and their scores from a file, and output the name of each student with all his/her scores and the total score, plus the average score of the class, and the name and total score of the students with the highest and lowest total score.
The exact assignment can be seen here.
I'm having a little trouble getting it to compile, especially with the variable "students".
Any help would be great.
/*
* The program will read information about students and their
* scores from a file, and output the name of each student with
* all his/her scores and the total score, plus the average score
* of the class, and the name and total score of the students with
* the highest and lowest total score.
*/
import java.util.Scanner;
public class Lab7
{
public static void main(String[] args)
{
// Input file name
Scanner in = new Scanner(System.in);
String filename = getFileName(in);
// Input number of students
int Student[students] = getStudents(FileIOHelper.getNumberOfStudents(filename));
// Input all students records and create Student array and
// integer array for total scores
int[] totalScores = new int[students.length];
for(int i = 0; i < students.length; i++){
for(int j = 1; j < 4; j++){
totalScores[i] += students[i].getScore(j);
}
}
// Compute total scores and find students with lowest and
// highest total score
int maxIndex = 0, minIndex = 0;
for(int i = 0; i < students.length; i++){
if(totalScores[i] > totalScores[maxIndex]){
maxIndex = i;
}else if(totalScores[i] < totalScores[minIndex]){
minIndex = i;
}
}
// Compute average total score
int average = 0;
for(int i = 0; i < totalScores.length; i++){
average += totalScores[i];
}
average /= students.length;
// Output results
outputResults(students, totalScores, maxIndex, minIndex, average);
}
// Given a Scanner in, this method prompts the user to enter
// a file name, inputs it, and returns it.
private static String getFileName(Scanner in)
{
System.out.print("Enter input file name: ");
return in.nextLine();
}
// Given the number of students records n to input, this
// method creates an array of Student of the appropriate size,
// reads n student records using the FileIOHelper, and stores
// them in the array, and finally returns the Student array.
private static Student[] getStudents(int n)
{
Student[] student = new Student[n];
for(int i = 0; i < student.length; i++){
student[i] = FileIOHelper.getNextStudent();
}
return student;
}
// Given an array of Student records, an array with the total scores,
// the indices in the arrays of the students with the highest and
// lowest total scores, and the average total score for the class,
// this method outputs a table of all the students appropriately
// formatted, plus the total number of students, the average score
// of the class, and the name and total score of the students with
// the highest and lowest total score.
private static void outputResults(
Student[] students, int[] totalScores,
int maxIndex, int minIndex, int average
)
{
System.out.println("\nName \t\tScore1 \tScore2 \tScore3 \tTotal");
System.out.println("--------------------------------------------------------");
for(int i = 0; i < students.length; i++){
outputStudent(students[i], totalScores[i], average);
System.out.println();
}
System.out.println("--------------------------------------------------------");
outputNumberOfStudents(students.length);
outputAverage(average);
outputMaxStudent(students[maxIndex], totalScores[maxIndex]);
outputMinStudent(students[minIndex], totalScores[minIndex]);
System.out.println("--------------------------------------------------------");
}
// Given a Student record, the total score for the student,
// and the average total score for all the students, this method
// outputs one line in the result table appropriately formatted.
private static void outputStudent(Student s, int total, int avg)
{
System.out.print(s.getName() + "\t");
for(int i = 1; i < 4; i++){
System.out.print(s.getScore(i) + "\t");
}
System.out.print(total + "\t");
if(total < avg){
System.out.print("-");
}else if(total > avg){
System.out.print("+");
}else{
System.out.print("=");
}
}
// Given the number of students, this method outputs a message
// stating what the total number of students in the class is.
private static void outputNumberOfStudents(int n)
{
System.out.println("The total number of students in this class is: \t" + n);
}
// Given the average total score of all students, this method
// outputs a message stating what the average total score of
// the class is.
private static void outputAverage(int average)
{
System.out.println("The average total score of the class is: \t" + average);
}
// Given the Student with highest total score and the student's
// total score, this method outputs a message stating the name
// of the student and the highest score.
private static void outputMaxStudent(
Student student,
int score
)
{
System.out.println(student.getName() + " got the maximum total score of: \t" + score);
}
// Given the Student with lowest total score and the student's
// total score, this method outputs a message stating the name
// of the student and the lowest score.
private static void outputMinStudent(
Student student,
int score
)
{
System.out.println(student.getName() + " got the minimum total score of: \t" + score);
}
}

First of all: it's always useful to actually pay attention to the compiler error. Java's compier errors are very clear and useful most of the time, and tell you exactly what's wrong once you're learned to understand them. And generally, it's much easier for people here on SO to help you if you include the actual text of an error rather than saying "I have trouble getting it to compiler"
This is the first obviously wrong line:
int Student[students] = getStudents(FileIOHelper.getNumberOfStudents(filename));
A variable declaration in Java consists of (slightly simplified):
The type of the variable
its name
optionally an assignment of an initial value
In the above line, you start with type int, but the next part Student[students] makes no sense - it looks like an array instantiation, certainly not a name. What you probably meant is:
Student[] students = getStudents(FileIOHelper.getNumberOfStudents(filename));
i.e. the type is Student[] (an array of Student objects), the name is 'students', and it's assigned the return value of the getStudents() method. An int is not involved anywhere (you don't have to specify the size of the array here, since it is created inside the getStudents() method).

The size of your array cannot be specified on the lefthand side.
The student array declaration should look like this:
int noOfStudents = FileIOHelper.getNumberOfStudents(filename);
//create an array of students of the given length
Student[] students = new Student[noOfStudents];

This part looks to be an issue:
// Input number of students
int Student[students] = getStudents(FileIOHelper.getNumberOfStudents(filename));
You probably want to first get the number of students, then use that variable to call getStudents. Also, if you want the array to be called students it should not be in the brackets.
Student[] students = .....

The line where you're having trouble is the very first line at the top of main():
int Student[students] = getStudents(FileIOHelper.getNumberOfStudents(filename));
I always recommend reading through a problematic line with the same mindset as a compiler: it doesn't know anything except what you've told it, top to bottom, left to right.
So let's start at the beginning:
int
I know what an int is! You want to declare one! Awesome! Moving on...
Student
What the heck is a Student? I don't see anywhere in the code that would tell me what that is! As a human, I can infer that it's supposed to be the name of a class, since class names are always capitalized in Java, but it's not declared so the compiler cannot be sure. Is it perhaps supposed to be the name of this class (instead of Lab7)?
More importantly, if it is a class then you have just named two datatypes in a row: int and Student. Which type did you intend to use? Presumably if you want a list of Students, the int is not relevant at all. If you want the number of students, then just the int is relevant.
Moving on:
students
What the heck is a students? I again don't see anywhere in the code that would tell me what that is!
Let's back away for a moment. What are you really trying to do here? You're trying to obtain an array of all the students in the file. The getStudents() function presumably achieves that. (It may be buggy, but that's not our problem at the moment. We're just calling it here, so we will assume that it works.)
But how are you supposed to know how big to make the array if you haven't yet read it? Conveniently, you don't have to know! You can simply write:
Student[]
You are instantiating the array down in getStudents(), and there you've correctly given it a size. Here in main() you're simply declaring it, and no size is necessary.
Okay, so can you just write:
Student[] = getStudents(FileIOHelper.getNumberOfStudents(filename));
No, 'cause your variable doesn't have a name. How about something like this:
Student[] students = getStudents(FileIOHelper.getNumberOfStudents(filename));
I suspect that's what you intended, but since you got stuck somewhere along the way it's important to be able to get "unstuck," and mentally walking through what the compiler sees is a useful way to do that.

Related

School Assignment Multidimensional Array Trouble

I am currently working on an assignment for my Java programming class. I seem to have got myself in a bit of a bind. Any assistance in helping me realize what I am doing wrong would be greatly appreciated.
Assignment
Write a program that does the following:
Put the data below into a multi-dimensional array
Prompts the user for the company they would like employee salary statistics.
Write a method that returns the average employee salary as a double. Pass the company number and employee Wages to this method.
Write a method that returns the total employee salary as an int. Pass the company number and employee Wages to this method.
Write a method that returns the number of employees as an int. Pass the company number and employee Wages to this method.
In the main method call the other methods and out put the results.
Keep in mind that I am still new and struggling to understand some of the principles of programming.
When I run the program I am getting locations instead of method calculations (bad output):
Here is what I have so far:
package salaries;
import java.util.Scanner;
public class Salaries {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//declare, instantiate, and define value of multi array [3] [12]
double [][] mSalary = { { 49920, 50831, 39430, 54697, 41751, 36110,
41928, 48460, 39714, 49271, 51713, 38903},
{ 45519, 47373, 36824, 51229, 36966, 40332,
53294, 44907, 36050, 51574, 39758, 53847},
{ 54619, 48339, 44260, 44390, 39732, 44073,
53308, 35459, 52448, 38364, 39990, 47373}};
//declare, instantiate, and define value
//of single array for company names
//and output values to user for selection
String [] company = { "Alhermit", "Logway", "Felter" };
for( int i = 0; i < company.length; i++ )
System.out.println( "Company " + i + " : " +company[i] );
Scanner scan = new Scanner( System.in );
int cCompany;
do{
//ouput for user to select a company
System.out.print("Select company: (0)" +company[0]+ ", (1)"
+company[1]+ "; (2)" +company[2]+ " > ");
//scan user input into cCompany
cCompany = scan.nextInt();
//call number method
num nums = new num();
nums.number(mSalary, cCompany);
//call total method
total sum = new total();
sum.total(mSalary, cCompany);
//call average method
avg cAvg = new avg();
cAvg.average(mSalary, cCompany);
//output statistics to user on selected company
System.out.println( "You have selected the company " + company[cCompany] + ". " );
System.out.println( company[cCompany] + " has " + nums + " of employees." );
System.out.println( "A total employee salary of " + sum + "." );
System.out.println( "The average employee salary is " + cAvg );
}
while( cCompany < 0 || cCompany > 2);
}
}
//total class to calculate
//salary of user selected company
class total {
public static int total( double [][] mSalary, int cCompany ){
//assign variables
int sum = 0;
//for loop to calculate salary total of user input company
for( int j = 0; j < mSalary[cCompany].length; j++ ){
sum += mSalary[cCompany][j];
}
//return statement
return sum;
}
}
//average class to calculate
//average of user selected company
class avg {
public static double average( double [][] mSalary, int cCompany){
//assign variables
int cAvg = 0;
int sum = 0;
int count = 0;
//totals the values for the selected company by
//iterating through the array with count.
while( count < mSalary[cCompany].length){
sum += mSalary[cCompany][count];
count +=1;
}
cAvg = sum / mSalary[cCompany].length;
return cAvg;
}
}
//number class to calculate amount of
//employees in user selected company
class num {
public static int number( double [][] mSalary, int cCompany){
//assign variables
int nums = 0;
//number of employees based on length of colomn
nums = mSalary[cCompany].length;
return nums;
}
}
nums, sum, and cAvg are all instances of classes that you have, you're printing out the instances of those classes.
(By the way - you should change the name of these classes. Classes start with a capital letter. It differentiates them from variables.)
There are two things wrong with this.
You are instantiating a class which contains no data and has no toString method.
You're instantiating a class which only has static methods to return the data from. You don't need to instantiate the class at all; instead, just print the result of the method call.
That would change at least one of these calls to something like:
System.out.println( company[cCompany] + " has " + num.number(mSalary, cCompany); + " of employees." );
I leave the rest as an exercise for the reader.

Generate and distribute random numbers fairly in java

Hi I have been trying to figure this quiz out
A lottery company shares out prizes to winning contestants every week. Most weeks, more than one contestant wins, in which case they try to share out the prizes as fairly as possible. Their prize distribution office has hired you to write a program that they will use to distribute prizes in the fairest way possible.
The program you write should take two lines of input:
A comma-separated list of this week's prizes' values
A comma-separated names of this week's winners
For example, the input could be:
100,800,200,500,400,1000
Joshua,Mahesh,Lilian
The program should then output the fairest possible distribution of prizes, by displaying one line for each winner, with the values of the prizes allocated to them. For example, given the input above, the output could be:
Joshua:100,400,500
Mahesh:1000
Lilian:800,200
The example above gives a perfect solution, where all winners get the same value of prizes (total value of 1000 each). In many cases, this will not be possible, but all prizes must be distributed and cannot be divided. Part of your job is to decide how you define 'fair' for these cases. For example, given the input
400,400,500,600
Barry,Sheila,Onyango,Wekesa
The following would be acceptable output, because there is no fairer distribution possible:
Barry:400
Sheila:400
Onyango:500
Wekesa:600
I am using java and so far this is what I have come up with
import java.util.Scanner;
import java.util.Arrays;
public class Main {
private static String amounts;
private static String names;
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print(
"Please enter the lottery amounts separated by commas: ");
if (userInput.hasNext()) {
amounts = userInput.next();
// System.out.println("You entered: " + amounts);
}
System.out.print("Please enter the contestants names: ");
if (userInput.hasNext()) {
names = userInput.next();
// System.out.println("You entered: " + names);
}
String amountArray[] = amounts.split(",");
String nameArray[] = names.split(",");
award(nameArray, amountArray);
}
// Method that awards the amounts to the winners
public static void award(String names[], String amounts[]) {
int randomAmount;
int randomName;
for (int i = 0; i < amounts.length; i++) {
randomAmount = (int) (Math.random() * amounts.length);
int usedValue[] = new int[amounts.length];
usedValue[i] = randomAmount;
if (checkValueUsed(randomAmount, usedValue)) {
randomName = (int) (Math.random() * names.length);
int usedName[] = new int[names.length];
System.out.println(names[randomName] + " = "
+ amounts[randomAmount]);
} else {
break;
}
}
}
private static boolean checkValueUsed(int currentState, int[] myArray) {
boolean found = false;
for (int i = 0; !found && (i < myArray.length); i++) {
if (myArray[i] == currentState) {
found = true;
}
}
return found;
}
private void checkUsedValue(int currentState, int[] myArray) {
for (int i = 0; (i < myArray.length); i++) {
if (myArray[i] == currentState) {
}
}
}
}
My idea of fair is to select a random amount and assign it to a random winner.
1) This looks like an interview/exam question. I'm not to judge but... really?
2) Your idea of fair is NOT what is intended. By the examples given, fair means all prizes are distributed and each winners total is as close to each other as possible.
3) From the above - this is a known problem. A greedy algorithm is likely to perform well. (I can't really see why not, unless you get very specific on the optimization part of the problem)
For a "fair" distribution you could try something like this:
Randomly order the winners.
For each winner, assign them the current highest available prize; so using your first example, winner one gets 1000, winner two gets 800, winner three gets 500.
If there are prizes left to distribute, for all but the first winner, assign them the current highest available prize that doesn't take them above the prize total of the first winner; winner two would get 200 (matching the 1000 of winner one), winner three gets 400 (to make 900).
Repeat step three until there are no more prizes or no prizes have been allocated; winner three gets 100 to match the 1000 of the other two.
If there are still prizes to allocate, sort the winners in descending order based on total prizes, and start allocating the lowest available prizes to all but the first winner.
Repeat step five until all prizes are allocated.

Novice at Java. Loop to enter height of people and find tallest

I am studying loops and am attempting a sample question here to use only a loop to ask the user to enter in the name of the person, height in feet first, then inches and then to find the tallest. I understand how to do the majority of it.
Could anyone point out where I am going wrong? I began writing the code and realised that I can't declare the persons names without knowing how many people the user will enter. I can't get my head around it.
I want to prompt the user with the questions but also update it to person [2], person [3], person [4] etc. depending on how many people they entered in initially.
Apologies for not wording this correctly. Any help is appreciated. I understand lines 10, 11 and 12 are probably wrong.
class HeightTest
{
public static void main(String[] args)
{
int noOfPeople;
int index;
int feet;
int inches;
String personOne;
String personTwo;
String personThree;
System.out.print("Enter a number of people ");
noOfPeople = EasyIn.getInt();
for (index = 1; index <=noOfPeople; index++)
{
System.out.println("Enter the name of person " + index);
personOne = EasyIn.getString();
System.out.println("Enter feet portion for " + personOne);
feet = EasyIn.getInt();
System.out.println("Enter inches portion for " + personOne);
inches = EasyIn.getInt();
}
}
}
You have a very good start. All you need to do now is keep track of the heights that are entered, and compare them to the largest one input so far. If the height for the current loop iteration is larger than the current largest, store it as the largest.
In pseudocode:
int largestHeightInches = 0;
for( i = 1; i <= noOfPeople; index++ ) {
currentHeightFeet = GetInt();
currentHeightInches = GetInt();
currentHeight = currentHeightInches + currrentHeightFeet * 12;
if( largestHeightInches < currentHeight ) {
largestHeightInches = currentHeight;
}
}
You would have to create an array of Persons to acheive what you want.
Here's a snippet.
Create a class called Person
public class Person
{
int index;
int feet;
int inches;
String name;
}
create a main Test class to contain your main method, and do something like this
public class Main{
public static void main (String[] args)
{
// get the number of people in noOfPeople as you do now.
Person[] pArray= new Person[nOfPeople]
for(Person p: pArray)
{
System.out.println("Enter the name of person " + index);
p.name = EasyIn.getString();
// ...etc
}
}
}

java- I got wrong results of counting

I wrote a program which counts the number of rooms for each class (art, sport, etc).
For example, each class contains a maximum of 3 students. If I have 9 students, with 6 music students and 3 art students,the results have to be: 1 room for art and 2 rooms for music.
When I run the code, I get these wrong results: the number of rooms for art equals 2 instead of 1 and the number of rooms for music equals 1 instead of 2.
Here is the result of execution of this program:
Insert numbers of participants:
9
Insert student in class:
1
Insert student in class:
1
Insert student in class:
1
The number of rooms for Music is:1
Insert student in class:
1
Insert student in class:
1
Insert student in class:
1
Insert student in class:
2
Insert student in class:
2
Insert student in class:
2
The number of rooms for Art is:2
This is my code:
import java.util.Scanner;
public class GroupActivity
{
public static void main()
{
Scanner GActivity=new Scanner(System.in);
System.out.println("Insert numbers of participants:");
int participantNo= GActivity.nextInt();//Insert numbers of participants
int music= 1;int art=2; int theatre= 3; int sport= 4; // Representation of each class by numbers.
int countM=0; //This variable contains the number of the participants in music class.
int countA=0; //This variable contains the number of the participants in art class.
int countT=0; //This variable contains the number of the participants in theatre class.
int countS=0; //This variable contains the number of the participants in sport class.
int countOFR=0;
for(int i=0;i<participantNo;i++)
{
System.out.println("Insert student in class:");
int p= GActivity.nextInt();// // Representation of student by number.int
if(p==music)
//for(
{
countM++;
int M=countM;
//System.out.println("student in class:"+music);
//System.out.println("Total music class:"+M);
if(M==3)
{
countOFR++;
int countOfRoom=+countOFR;
System.out.println("The number of rooms for Music is:"+countOfRoom);
}
}
else if(p==art)
{
countA++;
int A=countA;
// System.out.println("student in class:"+art);
if(A==3)
{
countOFR++;
int countOfRoom=+countOFR;
System.out.println("The number of rooms for Art is:"+countOfRoom);
}
//System.out.println("Total student in art class:"+A);
}
else if(p==theatre)
{
countT++;
int T=countT;
// System.out.println("student in class:"+theatre);
//System.out.println("Total thaetre class:"+T);
if(T==3)
{
countOFR++;
int countOfRoom=+countOFR;
System.out.println("The number of rooms for Theatre is:"+countOfRoom);
}
}
else{
countS++;
int S=countS;
if(S==3)
{
countOFR++;
int countOfRoom=+countOFR;
System.out.println("The number of rooms for Sport is:"+countOfRoom);
}
//System.out.println("Total sport class:"+S);
}
}
}
}
The problem is with countOFR. You are using this to store the no of rooms for all classes, instead of any one. Thus when you read data for class, the older value of countOFR gets added.
if(M==3)
{
countOFR++; // This should not be common for all
int countOfRoom=+countOFR;
System.out.println("The number of rooms for Music is:"+countOfRoom);
}
instead use different variables
int countOFR_music = 0;
int countOFR_art = 0;
int countOFR_theatre = 0;
int countOFR_sport = 0;
then use it like this
if(M==3)
{
countOFR_music++; // This should not be common for all
int countOfRoom=+countOFR_music;
System.out.println("The number of rooms for Music is:"+countOfRoom);
}
likewise for arts class
if(A==3)
{
countOFR_art++;
int countOfRoom=+countOFR_art;
System.out.println("The number of rooms for Art is:"+countOfRoom);
}
I think you should count students on each class, then process them at the end.
First, declare one or more object to hold number of student. Your declaration could work fine, but to shorten your code, you should use an array:
int numOfStudent[] = new int[4]; // 4 is for 4 types of class
Then in the for loop, do a check before increase counter, may be ask use input again (it's up to you):
// ...
int p= GActivity.nextInt();
int idx = p - 1; // Convert to zero-base index
if (idx >= 0 && idx < numOfStudent.length()) {
numOfStudent[idx]++;
}
Finally, out of for loop, just process them. Because each class contains maximum 3 student, we have:
int numOfMusicClass = (int)Math.ceil(numOfStudent[music - 1] / 3.0);
// ... Do the same for other class
Hopefully, this solution help you!
In addition, your class type is defined by number, thus, you should print out what number represents. For example:
Insert student in class (1 - music, 2 - art, 3 - theatre, 4 - sport):
It will make user aware what he/she input.
Here is a much shorter code:
public class GroupActivity
{
public static void main()
{
Scanner GActivity=new Scanner(System.in);
System.out.println("Insert numbers of participants:");
int participantNo= GActivity.nextInt();//Insert numbers of participants
int music= 1;int art=2; int theatre= 3; int sport= 4; // Representation of each class by numbers.
int[] counts = new int[4]; //This variable contains the number of the participants in music, arts, theatre and sports classes in its 4 cells.
for(int i=0;i<participantNo;i++)
{
System.out.println("Insert student in class:");
int p= GActivity.nextInt();// // Representation of student by number.int
if(p<=4)
counts[p-1]++;
}
System.out.println("The number of rooms for Music is:" + Math.ceil(counts[music-1]/3.0));
System.out.println("The number of rooms for Art is:" + Math.ceil(counts[art-1]/3.0));
System.out.println("The number of rooms for Theatre is:" + Math.ceil(counts[theatre-1]/3.0));
System.out.println("The number of rooms for Sports is:" + Math.ceil(counts[sport-1]/3.0));
}
}
Write smaller functions. This is too big to read.

How to create a String Array and link it to a Grade array

I have a project that I need to create 2 Arrays, one to hold Student Names and one to hold Student Scores. The user inputs the size of the array, and the array needs to be sorted using BubbleSort (putting the high scores at the top). I have started the project, created the first array for scores, I have successfully done bubble sort and sorted the grades. Now I can't figure out how to make an array for Names, and once I do how do I make the names array correspond to the Grades array BubbleSort?
Here is the code I have so far.
import java.util.Scanner;
public class Grades {
public static void main(String[]args){
{
Scanner GradeIn = new Scanner(System.in);
Scanner NameIn = new Scanner(System.in);
System.out.print( "How many students are there? " );
int[]GradeArray = new int[GradeIn.nextInt()];
String[]nameArray = new String[GradeIn.nextInt()];
for( int i=0 ; i<GradeArray.length ; i++ )
{
System.out.print( "Enter Grade for Student " + (i+1) + ": " );
GradeArray[i] = GradeIn.nextInt();
System.out.print( "Enter Name of Student " + (i+1) + ": " );
nameArray[i] = NameIn.nextLine();
}
bubbleSort(GradeArray, nameArray);
for( int i : GradeArray ) System.out.println( i );
System.out.println();
}
}
private static void bubbleSort(int[]GradeArray, String[] nameArray){
int n = GradeArray.length;
int temp = 0;
String temp2;
for(int i=0; i<n; i++){
for(int j=1; j<(n-i);j++){
if(GradeArray[j-1]<GradeArray[j]){
//swap
temp=GradeArray[j-1];
GradeArray[j-1]=GradeArray[j];
GradeArray[j]=temp;
temp2=nameArray[j-1];
nameArray[j=1]=nameArray[j];
nameArray[j]=temp2;
}
}
}
}
}
Also how do I change the grades to Double? I started with Int and when I try to change everything to double I get an error saying "Found Double, expected Int".
What the Professor is asking for:
Write a program that prompts the user to enter the number of students, the students' names, and their scores, and prints the names in decreasing order according to their scores.
ADDITIONAL INFO:
You will need two arays. One to hold strings. Another to hold the students' scores. (doubles)
The size of the arrays will be entered by the user.
You will have to sort the arrays in the main() method. I recommend using the BubbleSort (http://www.java-examples.com/java-bubble-sort-example) but not as a separate method. HINT: While sorting the grades array, you will need to sort the names array according to the grades.
And finally, you should include a method (void printAnswer(String [] names)) to print out the names array after it has been sorted.
Make a custom object. This is the entire idea of object oriented programming. You don't have a name and a grade, you have a Student who has a name and a grade. Then you manipulate the student in whatever way you see fit.
public class Student {
private String name;
private int grade;
public Student(String name, int grade) {
this.name = name;
this.grade = grade;
}
public String getName() {
return name;
}
public int getGrade() {
return grade;
}
}
Then where you have
int[]GradeArray = new int[UserIn.nextInt()];
Do this instead:
Student[] studentArray = new Student[UserIn.nextInt()];
I leave the rest of the changes as an exercise for you to get used to how it should work. Though, remember that a Student[] is full of null, as you read in the data, you have to create a new Student(name, grade) each time.
Alternate solution
The above is the correct way to do this. Do not learn anything from the below answer, becuase it defeats the entire purpose of learning Java. I would email the professor if the above solution is acceptable.
That being said, as you do each grade swap, you could do exactly the same swap in the String name array, i.e.
// change method signature
private static void bubbleSort(int[] gradeArray, String[] nameArray){
int n = gradeArray.length;
int temp = 0;
String temp2;
for(int i=0; i<n; i++){
for(int j=1; j<(n-i);j++){
if(gradeArray[j-1]<gradeArray[j]){
//swap
temp=gradeArray[j-1];
gradeArray[j-1]=gradeArray[j];
gradeArray[j]=temp;
// New code begin
temp2=nameArray[j-1];
nameArray[j-1]=nameArray[j];
nameArray[j]=temp2;
// New code end
}
}
}
}
Again, DO NOT DO THIS IN THE REAL WORLD ONCE YOU ARE NO LONGER IN SCHOOL. It is MUCH SLOWER and much more confusing.

Categories

Resources