Sorting three different arrays [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
This is the problem: Write a program that prompts the user to enter goods sale information including the name of the goods, quantity, and amount. First, the user is required to input the number of goods, and then input goods sale information one by one. Then the program will print out the goods information sort by quantity (from largest to smallest), and sort by amount (from largest to smallest) respectively. I'm having trouble sorting the information from the user by quantity and amount. For example, the output should be something like this:
Sort by quantity:
Item Qty Amount
CD 32 459.20
T-Shirt 22 650.80
Book 14 856.89
Sort by amount:
Item Qty Amount
Book 14 856.89
T-Shirt 22 650.80
CD 32 459.20
import java.util.Scanner;
public class SalesAnalysis {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter the number of goods");
int number=1;
int goods=input.nextInt();
for(int i=1;i<=goods;i++){
System.out.println("Enter information for item"+ number);
number++;
System.out.println("Name:");
String name=input.next();
String array[]=new String[]{name};
System.out.println("Quantity:");
int quantity=input.nextInt();
int ar[]=new int[]{quantity};
System.out.println("Amount (in USD):");
double amount=input.nextDouble();
double a[]=new double[]{amount};
getQuantity(array,ar,a);
getAmount(array,ar,a);
}
public static void getQuantity(String array[],int ar[],double a[]){
System.out.println("Sort by Quantity:");
System.out.println("--------------------");
System.out.print("Item"+" " +"Qty"+ "Amount" );
}
}

Seems like you don't know java well.
Create a class for Item. Keep name, quantity and amount as fields in it.
implement comparable interface while creating this class. Implete compareTo method to compare based on quantity.
While taking inputs from user, keep creating a object for a every single item with required details, keep adding these items in a arraylist.
Sort that arraylist (it will sort on quantity as you have implemented compareTo method).
Iterate over list, and print details.
I know you don't many of the things I mentioned here, but you will end up learning quite a few things about OOP and Java, this way.

EDIT: New and improved answer.
So to start out doing this you are going to want to make an Item class, that can store information such as the item's name, the items quantity, and the items price. Here is how I have done this:
public class Item {
private String name;
private int quantity;
private double price;
public void setName (String name) {
this.name = name;
}
public String getName () {
return this.name;
}
public void setQuantity (int quantity) {
this.quantity = quantity;
}
public int getQuantity () {
return this.quantity;
}
public void setPrice (double price) {
this.price = price;
}
public double getPrice () {
return this.price;
}
}
As you can see, I have made all of the stored variables private so I am using getters and setters.
From here you are going to want to make a way for users to input items. I have not set up an UI for this but instead I have made it where the program reads the file in its folder named input.txt. I did this like so:
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class ItemManager {
public Item[] items;
public Item[] sortedByQuantity;
public Item[] sortedByPrice;
public static void main(String[] args) {
String filepath = "input.txt";
if(args.length >= 1) {
if(args[0] != null) {
filepath = args[0];
}
}
ItemManager runProgram = new ItemManager();
runProgram.AssignValues(filepath);
runProgram.Display();
}
From here the system then analyzes the contents of input.txt using a scanner such as you have done. The input file should be formatted like this:
ItemName(no spaces) Quantity Price
new line for new item
public void AssignValues(String filepath) {
try{
Scanner scanner = new Scanner(new File(filepath));
StringBuilder sb = new StringBuilder();
while(scanner.hasNextLine()){
sb.append(scanner.nextLine());
if(scanner.hasNextLine()){
sb.append(" ");
}
}
String content = sb.toString();
tokenizeTerms(content);
}
catch(IOException e){
System.out.println("InputDocument File IOException");
}
}
This method uses string builder to compile a single string out of the input text. From here it calls tokenizeTerms on the content. This method splits the string into a String[], using a space as a delimiter, hence not being able to use spaces in the item names.
public void tokenizeTerms(String content) {
String[] tokenizedTerms = content.split(" ");
Item[] itemArray = new Item[tokenizedTerms.length/3];
int currToken = 0;
for(int i = 0; i < itemArray.length; i++) {
itemArray[i] = new Item();
try {
itemArray[i].setName(tokenizedTerms[currToken]);
currToken++;
int foo = Integer.parseInt(tokenizedTerms[currToken]);
itemArray[i].setQuantity(foo);
currToken++;
double moo = Double.parseDouble(tokenizedTerms[currToken]);
itemArray[i].setPrice(moo);
currToken++;
} catch (Exception e) {
System.out.println("Error parsing data.");
}
}
this.sortedByPrice = itemArray;
this.sortedByQuantity = itemArray;
this.items = itemArray;
}
In this method it also creates a temporary array of Items. Which are then iterated though using a for-loop and the items are assigned there corresponding tokenized values from the input text. Now all we have to do is sort the arrays and print them in the console. As you can see above in the main method, we call Display().
public void Display() {
Arrays.sort(sortedByQuantity, (Item i1, Item i2) -> Double.compare(i1.getQuantity(), i2.getQuantity()));
Arrays.sort(sortedByPrice, (Item i1, Item i2) -> Double.compare(i1.getPrice(), i2.getPrice()));
System.out.println("Sorted by quantity:");
for(Item currItem : sortedByQuantity) {
System.out.println("Name: " + currItem.getName() + " Quantity: " + currItem.getQuantity() + " Price: " + currItem.getPrice());
}
System.out.println("Sorted by price:");
for(Item currItem : sortedByPrice) {
System.out.println("Name: " + currItem.getName() + " Quantity: " + currItem.getQuantity() + " Price: " + currItem.getPrice());
}
}
The code starts out by first using lambda expressions to sort the arrays based off a custom compare method. From here we just iterate through each array and print each value.
That is the basic setup for what you are looking for, you can now modify these methods to your liking and apply them in whatever way seems fit. You also could also modify it to allow users to directly input the values in the software, or modify it to allow item names to have spaces. Best of luck.

Related

Using the ArrayList<Object> feature to store Array from Method [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am about 95% done I believe, the only thing that is stopping me is that I have to print the results from printInfo() into an element.
The program is gathering input, and the input is based on whether or not the item is a plant. After the input is entered and the setters are ran, I am suppose to access the
printInfo() from plant for example, and store it as an element in the myGarden array.
Then I will call a method that prints the elements of the object array. Those elements will be the information from printInfo() from the plant, and the flower class.
update: I removed casting and simply changed to , Modified the method as well. Remove the print command since it won't work for what we are trying to do and instead assign myGarden.get(i) to call upon the elements.
package labpackage;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class PlantArrayListExample {
// TODO: Define a printArrayList method that prints an ArrayList of plant (or flower) objects
public static void printArrayList(ArrayList<Plant> myGarden) {
for (int i = 0; i < myGarden.size(); ++i) {
myGarden.get(i).printInfo();
}
}
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String input;
// TODO: Declare an ArrayList called myGarden that can hold object of type plant
ArrayList<Object> myGarden = new ArrayList<>();
// TODO: Declare variables - plantName, plantCost, colorOfFlowers, isAnnual
String plantName;
String plantCost;
String colorOffFlowers;
boolean isAnnual;
input = scnr.next();
while(!input.equals("-1")){
// TODO: Check if input is a plant or flower
if (input.contains("plant")) {
Plant plant = new Plant();
plantName = scnr.next();
plantCost = scnr.next();
plant.setPlantName(plantName);
plant.setPlantCost(plantCost);
System.out.println();
myGarden.add(plant);
// missing code to add print result as an element
}
if (!input.contains("plant")) {
Flower flower = new Flower();
plantName = scnr.next();
plantCost = scnr.next();
isAnnual = scnr.nextBoolean();
colorOffFlowers = scnr.next();
flower.setPlantName(plantName);
flower.setPlantCost(plantCost);
flower.setPlantType(isAnnual);
flower.setColorOfFlowers(colorOffFlowers);
System.out.println();
// missing code to add print result as an element
myGarden.add(flower);
}
input = scnr.next();
}
// TODO: Call the method printArrayList to print myGarden
printArrayList(myGarden);
}
}
package labpackage;
public class Plant {
protected String plantName;
protected String plantCost;
public void setPlantName(String userPlantName) {
plantName = userPlantName;
}
public String getPlantName() {
return plantName;
}
public void setPlantCost(String userPlantCost) {
plantCost = userPlantCost;
}
public String getPlantCost() {
return plantCost;
}
public void printInfo() {
System.out.println("Plant Information: ");
System.out.println(" Plant name: " + plantName);
System.out.println(" Cost: " + plantCost);
}
}
package labpackage;
public class Flower extends Plant {
private boolean isAnnual;
private String colorOfFlowers;
public void setPlantType(boolean userIsAnnual) {
isAnnual = userIsAnnual;
}
public boolean getPlantType(){
return isAnnual;
}
public void setColorOfFlowers(String userColorOfFlowers) {
colorOfFlowers = userColorOfFlowers;
}
public String getColorOfFlowers(){
return colorOfFlowers;
}
#Override
public void printInfo(){
System.out.println("Plant Information: ");
System.out.println(" Plant name: " + plantName);
System.out.println(" Cost: " + plantCost);
System.out.println(" Annual: " + isAnnual);
System.out.println(" Color of flowers: " + colorOfFlowers);
}
}
To print the plant or flower info update printArrayList method. You cannot pass a method that returns void to "System.out.println" as a parameter, you must call the method directly because it returns void.
public static void printArrayList(ArrayList<Plant> objList) {
for (i = 0; i < objList.size(); ++i) {
objList.get(i).printInfo();
}
}
Instead of using Object as type of elements in your collection (which is most generic), you have to narrow down range of possible types. Since you have good hierarchy here you can use base class. Replace
ArrayList <Object> myGarden = new ArrayList();
with
List<Plant> myGarden = new ArrayList<>();
And you will be able to call printInfo() method, because all objects in collection will definitely be at least Plant or any subclass of that class which means they all will have printInfo() method.
public static void printArrayList(Collection<Plant> plants) {
for (Plant p : plants) {
p.printInfo();
}
}
Or shorter using Java Stream API
myGarden.stream().forEach(Plant::printInfo);
Hope it helps!

Java - How to find and remove an element in an ArrayList made of a custom class using one of that classes attributes

I am trying to find and remove an element from my ArrayList list (made from a custom master class ShoppingBasket) based on a user inputted String itemSearch whereby they would enter say Apple if they wanted to remove that from the basket, regardless of if the quantity is higher than 1.
The project is setup so that I have a masterclass ShoppingCart, with several subclasses Fruit, Dairy. Each class has a itemName and itemQuantity attribute.
Here is my Fruit class:
public class Fruit extends ShoppingBasket {
Fruit(String itemName, int itemQuantity){
super(itemName, itemQuantity);
}
}
Here is my Dairy sub-class code:
public class Dairy extends ShoppingBasket{
Dairy(String itemName, int itemQuantity){
super(itemName, itemQuantity);
}
}
For my ShoppingCard class I have hard-coded examples of instances of the Fruit and Diary classes and added them to a list to use as test data. I then try to iterate through that list and check each item against the name of the item the user has inputted and when it has found the correct item I try to remove it and print out the result. However, when it goes to print out the result, the program has not removed the item. When Debugging and using a Stop point I notice the program does not enter the if statement.
Below is the code for the master ShoppingBasket class:
import java.util.*;
import javax.swing.plaf.basic.BasicComboBoxUI.ItemHandler;
public class ShoppingBasket {
public String itemName;
public int itemQuantity;
static String itemSearch;
ShoppingBasket(String itemName, int itemQuantity){
this.itemName = itemName;
this.itemQuantity = itemQuantity;
}
public static void main(String[] args) {
List<ShoppingBasket> list = new ArrayList<ShoppingBasket>();
list.add(new Fruit("Apple", 2));
list.add(new Fruit("Orange", 4));
list.add(new Dairy("Semi-Skimmed Milk", 1));
list.add(new Dairy("Full Fat Milk", 3));
Scanner scnr = new Scanner(System.in);
System.out.println("What is the item that you want to remove from your basket? ");
itemSearch = scnr.nextLine();
for(ShoppingBasket s: list){
if(s.getItemName() != null && s.getItemName().contains(itemSearch)){
list.remove(itemSearch);
}
}
System.out.println(list.toString());
}
public String toString() {
return "Item name: " + this.itemName + " | Quantity: " + this.itemQuantity;
}
public String getItemName(){
return itemName;
}
}
Any help or hints of where I am going wrong would be appreciated. I apologise if this code is messy, I am new and trying to grasp the basics like Super Class and Sub Classes as well as other concepts of Java.
The clear mistake on your code was the line below:
list.remove(itemSearch);
You used the itemSearch String variable to remove the element from the list which was wrong. You should supply the element you want to delete to the remove method.
SOLUTION
To fix it you can simply replace the line mentioned above with:
list.remove(s);
In java 8 or above you can try the solution below with java streams:
List<ShoppingBasket> filteredList = list.stream()
.filter(shoppingBasket -> shoppingBasket.getName() != null && !shoppingBasket.getItemName().containsIgnoreCase(itemSearch))
.collect(Collectors.toList());
Use this to remove instead:
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getItemName() != null && list.get(i).getItemName().contains(itemSearch)) {
list.remove(list.get(i));
}
}

Finding specific instance of class? [duplicate]

This question already has answers here:
How to find an object in an ArrayList by property
(8 answers)
Closed 5 years ago.
I've just started learning java and I'm trying to create an application to register students.
Based on this question how-would-i-create-a-new-object... I created a while loop to create an instance of a class.
public class RegStudent {
ArrayList<Student> studentList = new ArrayList<>();
Scanner input = new Scanner(System.in);
public void reggaStudent(int start) {
while (start != 0) {
String programNamn, studNamn;
int totalPoint, antalKurser;
System.out.println("Vad heter programmet?");
programNamn = input.nextLine();
System.out.println("Vad heter studenten");
studNamn = input.nextLine();
System.out.println("Hur många poäng har studenten?");
totalPoint = input.nextInt();
System.out.println("Hur många kurser är studenten registrerad på?");
antalKurser = input.nextInt();
// Add student to list of students
studentList.add(new Student(totalPoint, antalKurser,
programNamn, studNamn));
System.out.println("Vill du registrera in en fler studenter? "
+ "Skriv 1 för ja och 0 för nej");
start = input.nextInt();
input.nextLine();
} // End of whileloop
}
}
The class is:
public class Student {
private int totalPoint;
private int antalKurser;
private String programNamn;
private String studNamn;
private static int counter;
public Student(int totalPoint, int antalKurser, String program, String studNamn) {
this.totalPoint = totalPoint;
this.antalKurser = antalKurser;
this.programNamn = program;
this.studNamn = studNamn;
counter++;
}
public int getTotalPoint() {
return totalPoint;
}
public void setTotalPoint(int totalPoint) {
this.totalPoint = totalPoint;
}
public int getAntalKurser() {
return antalKurser;
}
public void setAntalKurser(int antalKurser) {
this.antalKurser = antalKurser;
}
public String getProgramNamn() {
return programNamn;
}
public void setProgramNamn(String programNamn) {
this.programNamn = programNamn;
}
public String getStudNamn() {
return studNamn;
}
public void setStudNamn(String studNamn) {
this.studNamn = studNamn;
}
public static int getCount(){
return counter;
}
#Override
public String toString() {
return String.format(" Namn: %s, Program: %s, Antal poäng: %d, "
+ "Antal kurser: %d\n ", studNamn, programNamn, totalPoint, antalKurser);
}
}
How do I go about to get and set the instance variables in specific instance? I.e find the instances.
I understand it might be bad design but in that case I would appreciate some input on how to solve a case where i wanna instantiate an unknown number of students.
I've added a counter just to see I actually created some instances of the class.
You simply query objects for certain properties, like:
for (Student student : studentList) {
if (student.getProgramName().equals("whatever")) {
some match, now you know that this is the student you are looking for
In other words: when you have objects within some collection, and you want to acquire one/more objects with certain properties ... then you iterate the collection and test each entry against your search criteria.
Alternatively, you could "externalize" a property, and start putting objects into maps for example.
studentList.add(new Student(totalPoint, antalKurser,
programNamn, studNamn));
You now have your Student objects in a list. I assume you have something like
List<Student> studentList = new ArrayList<>();
somewhere in your code. After you populate the list with Student objects, you can use it to find instances. You need to decide what criteria to use for a search. Do you want to find a student with a specific name? Do you want to find all students in a given program? Do you want to find students with more than a certain number of points?
Maybe you want to do each of these. Start by picking one and then get a piece of paper to write out some ideas of how you would do the search. For example, say you want to find a student with the name "Bill". Imagine that you were given a stack of cards with information about students. This stack of cards represents the list in your program. How would you search this stack of cards for the card with Bill's name on it? Describe the steps you need to take in words. Don't worry about how you will code this yet. The first step in writing a computer program is breaking the solution down into small steps. After you have a clear idea how you might do this by hand in the physical world, you can translate your description into Java code.

How to search through arraylist containing string, int and double with JTextField and JButton

I currently have a working GUI program that has a few buttons on it to simply step through my arraylist of items. These simply display the first, last or next and previous index results. This list has String, int and double inside of it. Now I have added a JTextField for input and a search button. My question is how do I get my search button to search through this array list? I was reading this answer but I don't understand the datum thing. Do I have to convert the entire arraylist to string before searching through it? Would something like
ArrayList<inventoryItem> inventory = new ArrayList<>(); ....
JTextField input = new JTextField(18); ...
JButton searchButton = new JButton("Search");
searchButton.setToolTipText("Search for entry");
searchButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
String usrInput = input.getText();
for (String s : inventory) {
if (usrInput.contains(s)) {
inventory.get(currentIndex);
outputText.append(" somehow put whatever the index is equal to here");
}
}
}
});
The error I get is that inventoryItem cannot be converted to string. The second problem: I am having is how to I make it output everything in that index. For example my output looks like this:
class officeSupplyItem extends inventoryItem {
public officeSupplyItem(String itemName, int itemNumber, int inStock, double unitPrice) {
super(itemName, itemNumber, inStock, unitPrice);
}
#Override
public void output(JTextArea outputText) {
outputText.setText("Item Name = " + itemName + " \n"); //print out the item name
outputText.append("Item Number = " + itemNumber + " \n"); //print out the item number
outputText.append("In Stock = " + inStock + " \n"); //print out how many of the item are in stock
outputText.append("Item Price = $" + formatted.format(unitPrice) + " \n"); //print out the price per item
outputText.append("Restocking fee is $" + formatted.format(restockingFee) + " per item \n");
outputText.append("Value of item inventory = $" + formatted.format(value) + " \n"); //print out the value of the item inventory
outputText.append("Cost of inventory w/restocking fee = $" + formatted.format(inventoryValue) + " \n"); //print out the total cost of inventory with restocking fee
}
}
I would also like to understand what the datum portion of the mentioned link means.
I am not quite clear on what you mean by "This list has String, int and double inside of it".
You are comparing an object field with the text entered. You need not convert InventoryItem to a string. What you need to do is identify which fields you want to compare and use them in the comparison.
From what I see the text being entered to the JTextField is the search criteria for your code. If I assume it to be itemName, your code should be as follows :
searchButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
String usrInput = input.getText();
for (InventoryItem s : inventory) {
if (usrInput.equalsIgnoreCase(s.getItemName())) {
//you can call output string here
outputText.append(" somehow put whatever the index is equal to here");
}
}
}
});
This is for the case if the JTextField input is the itemName. If this is any different than you expect, please comment.
From the link you shared, the difference is that his List contains only Strings, that is why "datum" is a String. This cannot be used for your case.
Hope this helps!
As per my understanding, what ever the searchText is (itemName or itemNumber) the results should be listed. Therefore, you could write a search method that compares and returns whether it matches the search string as follows in the InventoryItem class.
public boolean isSearchTextAvailable(String searchText) {
if (this.itemName.equals(searchText)) {
return true;
} else {
try {
int no = Integer.parseInt(searchText);
if (this.itemNumber == no) {
return true;
}
} catch (NumberFormatException e) {
System.out.println("Not a integer");
}
}
return false;
}
You can enhance this method to any number of fields you want to be searched within.
Then use this method in the action for the searchButton.
searchButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
String usrInput = input.getText();
for (InventoryItem invItem : inventory) {
if (invItem.isSearchTextAvailable(usrInput)) {
invItem.output(outputText);
}
}
}
});
You have to make input (JTextField) a field in this class to make it work.
Few tips to increase quality of your code:
Separate InventoryItem and OfficeSupplyItem classes to different files
Notice the naming convention for class names is PascalCase
Better to have JavaGUIFixed class extended from JFrame and all its components defined as fields and not local variables since you use them in various other methods other than makeWindow() method where you actually create the JFrame
Do not use invItem.output(outputText) type of methods, where you pass a JTextField to a object Method to write to it. What you could do instead is write a method like getOutputString() in InventoryItem class which will return a formatted string of what needs to be printed and then call outputText.setText(invItem.getOutputString()) - Your implementation is restricting you to have all classes as inner classes to JavaGUIFixed.
Hope this helps!
Your enhanced for loop is saying for each String element s in ArrayList inventory... But inventory is declared to be an ArrayList of inventoryItem objects, not a list of strings, and the for loop isn't accessing the variables where the values you are trying to search are stored, as each index of inventory is just storing a reference to an object.
If your main goal is taking input, storing, sorting, and outputting it, you might consider taking and storing it as strings in a string collection. You can always parse to int or double if you need to at some point, but it will be easier to sort and search with a homogenous data type.
Where I saw datum used in that link was just as a variable name, the same way you used 's' in your code.
I have marked #maheeka 's response as the answer. I however had to modify his code because of the way that I had previously written my program. It now looks as follows:
searchButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
String usrInput = input.getText();
for (int i = 0; i < inventory.size(); i++) {
if (usrInput.equalsIgnoreCase(inventory.get(i).getItemName())) {
currentIndex = i;
displayItem(outputText);
I also had to set up my getter on the itemName as I apparently had forgotten that part. Thank you #Aadi Droid for that.

Implementing classes and objects in java, calling a method

I'm having trouble with calling a method. The basis of the program is to read in data from data.txt, grab the name token given, then all of the grades that follow, then implement some operations on the grades to give details of the person's grades. I do all of the methods in a separate file named Grades.java, which has the Grades class. I'm just having trouble because I MUST have the testGrades method in my code (which I don't find necessary). I have done everything I need to do for the results to be perfect in a different program without having two different .java files. But it's necessary to do it this way. I think I have mostly everything pinned down, I'm just confused on how to implement and call the testGrades method. I commented it out and have the question on where it is in the program. Quite new to classes and objects, and java in general. Sorry for the lame question.
public class Lab2 {
public static void main(String[] args) {
Scanner in = null; //initialize scanner
ArrayList<Integer> gradeList = new ArrayList<Integer>(); //initialize gradeList
//grab data from data.txt
try {
in = new Scanner(new File("data.txt"));
} catch (FileNotFoundException exception) {
System.err.println("failed to open data.txt");
System.exit(1);
}
//while loop to grab tokens from data
while (in.hasNext()) {
String studentName = in.next(); //name is the first token
while (in.hasNextInt()) { //while loop to grab all integer tokens after name
int grade = in.nextInt(); //grade is next integer token
gradeList.add(grade); //adding every grade to gradeList
}
//grab all grades in gradeList and put them in an array to work with
int[] sgrades = new int[gradeList.size()];
for (int index = 0; index < gradeList.size(); index++) {
sgrades[index] = gradeList.get(index); //grade in gradeList put into grades array
}
//testGrades(sgrades); How would I implement this method call?
}
}
public static void testGrades(Grades grades) {
System.out.println(grades.toString());
System.out.printf("\tName: %s\n", grades.getName());
System.out.printf("\tLength: %d\n", grades.length());
System.out.printf("\tAverage: %.2f\n", grades.average());
System.out.printf("\tMedian: %.1f\n", grades.median());
System.out.printf("\tMaximum: %d\n", grades.maximum());
System.out.printf("\tMininum: %d\n", grades.minimum());
}
}
This is a little snippet of the beginning of the Grades.java file
public class Grades {
private String studentName; // name of student Grades represents
private int[] grades; // array of student grades
public Grades(String name, int[] sgrades) {
studentName = name; // initialize courseName
grades = sgrades; // store grades
}
public String getName() {
return studentName;
} // end method getName
public int length() {
return grades.length;
}
well your test grades take a Grades object so you need to construct a Grades object using your data and pass it to your test grades method
i.e.
Grades myGrade = new Grades(studentName,sgrades);
testGrades(myGrade);
It looks like what you need to do is have some type of local variable in your main method, that would hold your custom Grade type. So you need add a line like..
Grades myGrades = new Grades(studentName, sgrades);
Then you can call your testGrades method with a line like...
testGrades(myGrades);
Looks like you may also need a toString method in your Grades class.
Seems like homework, so I tried to leave a bit to for you to figure out :)

Categories