Это домашнее задание, но мне нужно «подтолкнуть». Я не могу найти, как сортировать по имени.Попытка понять способ сортировки. Java Homework
Мои вопросы: (Пожалуйста держите ответы начинающему дружеский)
- ли что бы выглядеть правильно до сих пор?
- Как сортировать?
- У кого-нибудь есть рекомендации по оптимизации/очистке этого?
Вот задание:
инвентаризации Программа Часть 2 контрольно-пропускной пункт, который должен быть представлен в 6-й неделе имеет следующие требования:
Модифицируйте программу инвентаризации поэтому приложение может обрабатывать несколько элементов. Используйте массив для хранения элементов.
На выходе должна отображаться информация по одному продукту за раз, включая номер позиции, название продукта, количество единиц в запасе, стоимость каждой единицы и стоимость инвентаря этого продукта ,
Кроме того, на выходе должно отображаться значение всего инвентаря.
Создайте метод расчета стоимости всего инвентаря.
Создайте еще один способ сортировки элементов массива по наименованию продукта.
Чтобы удовлетворить эти требования, вам необходимо добавить следующие строки в Inventory класс (не класс продукта):
1) Объявите массив типа продукта (частный переменный экземпляр)
2) Внутри вашей основной в то время как петли, сделайте следующее:
a. Instantiate a product object b. Populate the product object with the input from the console (like Inventory Part 1 does) c. Add the product object reference to the next element in your array d. Destroy the reference to the product object variable (note this object was added to your array so you can set the local variable that refers to the object to null)
3) За пределами вашей основной в то время как петли, сделайте следующее:
a. Call a method in your Inventory class to sort the array of Product objects. Note you need to sort an array of Product objects by the Product Name instance variable. To do this, you will need to create a separate .java file that implements the Comparator interface. You will pass the Product array and implemented Comparator interface class as arguments to the sort method of the Arrays class (part of the Java API). b. Create a For Loop that iterates through the array of Product objects (similar to the one I have below). Invoke the get method on each instance variable and format the output by calling printf. Sample For Loop to use: for (Product product : productArray) { Add statements here } c. Call a method in your Inventory class to calculate the total inventory value of all the Product objects in your array.
Вот мой код
public class InvTest2{// main method begins
public static void main(String args[]) {
int version = 2;// Version number
final int invLeng = 5;// Declare Inv length
// Welcome message
System.out.printf("\n%s%d\n" ,
"Welcome to the Inventory Program v.", version);
Inv[] DVDs = new Inv[invLeng];
DVDs[0] = new Inv("The Invisible Man", 0, 8.50); // new DVD constructor
DVDs[1] = new Inv("The Matrix", 1, 17.99);
DVDs[2] = new Inv("Se7en", 7, 12.99);
DVDs[3] = new Inv("Oceans Eleven", 11, 9.99);
DVDs[4] = new Inv("Hitch Hikers Guide to the Galaxy", 42, 18.69);
// Display formatted results
int c = 0;
double runningValue = 0;
System.out.printf("\n%s\n", "Inventory of DVD movies");
while(c != DVDs.length){
System.out.printf("\n\n%s%d\n%s%s\n%s%d\n%s%,.2f\n%s%,.2f\n",
"Item Number: ",c,
"DVD Title: ",DVDs[c].getdvdTitle(),
"Copies in stock: ",DVDs[c].getdvdInStock(),
"Price each disk: $",DVDs[c].getdvdValue(),
"Value of copies: $",DVDs[c].getdvdStockValue());//End print
runningValue += DVDs[c].getdvdStockValue();
c++;
}
System.out.printf("\n%s%,.2f\n",
"Collection Value: $",runningValue);
}// end method main
}//end class Inventory1
Вот инвентарь
public class Inv {//Begin DVD class
// Declare instance variables
String dvdTitle;// Declare title as string
int dvdInStock;// Declare dvdInStock as float
double dvdValue;// Declare dvdValue as float
// constructor initializes DVD information
public Inv(String title, int inStock, double value) { // Initialize (clear) instance variables here
dvdTitle = title;
dvdInStock = inStock;
dvdValue = value;
} // end constructor
public String getdvdTitle() {// public method to get the DVD name
return dvdTitle;}// end method getdvdTitle
public int getdvdInStock() {// public method to retrieve the dvdInStock
return dvdInStock;} // end method get dvdInStock
public double getdvdValue() {// public method to retrieve the dvdValue
return dvdValue;} // end method get dvdValue
public double getdvdStockValue() {// public method to dvdStockValue
return (dvdValue * dvdInStock);}// end method get dvdStockValue
} // end class Inv
Вы код не соответствует требованиям, предъявляемым вашим инструктором. Вы можете начать там. – doomspork
Извините, что редактируйте clobber. Верните рулон обратно, если чувствуете, что я сделал плохую работу. – Welbog
проблема с просьбой о домашней помощи заключается в том, что никто, кто никогда не должен делать домашнее задание снова, хочет это сделать. вам лучше спросить кучу более конкретных вопросов о реальных проблемах, которые у вас есть – mkoryak