Я пишу программу покупок для домашнего задания. Я уже поместил метод получения и установки, чтобы проверить, есть ли какие-либо элементы в классе Item, прежде чем помещать их в корзину. Я не уверен, как использовать их в моей основной программе, чтобы проверить наличие товара перед тем, как положить его в корзину, и показать «Нет в наличии», если он недоступен после того, как пользователь введет код товара.
Я почти завершил код моей программы покупок. Я знаю, что должен использовать getInStock (), чтобы прочитать текущее значение, и setInStock (), чтобы обновить счетчик inStock для выбранного элемента, но я не уверен, как я могу проверить наличие элемента, а затем вычесть 1 из inStockпеременная в моем основном классе.
Ниже приведен код для моего основного:
import java.util.Scanner;
import java.util.InputMismatchException;
public class BooksAndClothesPolymorphism {
private static Item[] shoppingCart = new Item[10]; // contains items in user's shopping cart
private static int shoppingCartCount = 0; // number of total items in the cart
// define an array of books and shirts
private static final Item[] ITEM_LIST = {
new Book(1176,"ULYSSES", "James Joyce", 1918, 32.95, 16 ),
new Book(1252,"THE GREAT GATSBY", "F. Scott Fitzgerald", 1925, 13.95, 30 ),
new Book(1376,"BRAVE NEW WORLD", "Aldous Huxley", 1931 , 14.95, 28 ),
new Book(1463,"TO THE LIGHTHOUSE", "Virginia Woolf", 1927, 36.95, 19 ),
new Book(1545,"THE SOUND AND THE FURY", "William Faulkner", 1929, 17.95, 11 ),
new Book(1605,"CATCH-22", "Joseph Heller", 1961, 38.95, 25 ),
new Book(1824,"THE DEATH OF THE HEART", "Elizabeth Bowen", 1938, 26.95, 44 ),
new Book(1873,"DARKNESS AT NOON", "Arthur Koestler", 1940, 39.95, 6 ),
new Book(1909,"THE GRAPES OF WRATH", "John Steinbeck", 1939, 12.95, 32 ),
new Book(1945,"1984", "George Orwell", 1949, 24.95, 24 ),
new Shirt(2443,"T-shirt", "Guess", "M", "Blue", 14.95, 23),
new Shirt(2867,"Dress shirt", "Ralph Lauren", "M", "White", 39.95, 5),
new Shirt(2868,"Dress shirt", "Ralph Lauren", "L", "White", 39.95, 4),
new Shirt(2869,"Dress shirt", "Ralph Lauren", "XL", "White", 39.95, 1),
new Shirt(2905,"Blouse", "Versace", "S", "Yellow", 44.95, 6),
new Shirt(2923,"Tank top", "Zoned Out", "XLT", "White", 15.45, 2),
};
public static void main(String[] args) {
// create the stdin object (to use the keyboard)
Scanner stdin = new Scanner(System.in);
int itemSelected = 0; // Item ID selected by user, 0 for not available
int itemIndex = 0; // selected index into array of items
// display items in the arrays using the toString method
System.out.printf ("%-4.4s %6.6s %-11.11s\n", "Item", "Price", "Description");
for (Item b : ITEM_LIST) { System.out.println(b); }
System.out.println ("\nSelect an item by its item number. Enter 0 to quit");
do {
try {
System.out.printf ("item #%d: ", shoppingCartCount+1);
itemSelected = stdin.nextInt( ); // read line from keyboard
if (shoppingCartCount == shoppingCart.length)
{
System.out.println("Your shopping cart is full");
break;
}
if (itemSelected == 0)
continue; // exit the loop
// Search ITEM_LIST looking for the user's requested itemID
for (itemIndex=0; itemIndex<ITEM_LIST.length; itemIndex++)
if (itemSelected == ITEM_LIST[itemIndex].getItemID())
break; // it was found, itemIndex = position in the LIST
if (itemIndex == ITEM_LIST.length) // reached the end and not found
System.out.println("Item is not available");
else { // The item was found
shoppingCart[shoppingCartCount] = ITEM_LIST[itemIndex];
shoppingCartCount++; // keep track of items in the cart
}
}
catch (InputMismatchException | StringIndexOutOfBoundsException e) {
System.out.println ("Illegal selection. Try again");
}
} while (itemSelected != 0); // loop until a '0' is entered
// display the shopping cart
System.out.println("\n\nThank you for shopping at dan-azon");
double total=0;
for (int i=0; i<shoppingCartCount; i++) {
System.out.println(shoppingCart[i]);
total += shoppingCart[i].getPrice();
}
System.out.println(shoppingCartCount + " items in your cart");
System.out.printf("Your total is $%.2f\n\n", total);
}
}
Ниже приведен код для моего класса предметов
public abstract class Item {
protected int itemID;
protected double price;
protected int inStock;
// constructors
Item( ) { }
// getters
public double getPrice( ) { return price; }
public int getInStock() { return inStock; }
public int getItemID() { return itemID; }
// setters
public double setPrice (double price) {
this.price=price;
return this.price;
}
public int setInStock(int inStock) {
this.inStock=inStock;
return this.inStock;
}
public int setItemID(int itemID) {
this.itemID = itemID;
return this.itemID;
}
}
Ниже приведен коддля моего класса Книги
public class Book extends Item {
private static final double MAX_BOOK_PRICE = 100.00;
private String title;
private String author;
private int date;
private static int bookCount = 0;
// default constructor
Book ( ) {
bookCount++; // keep track of the number of books
};
// constructor with five arguments
Book (int itemID, String title, String author, int date, double price, int inStock) {
setItemID(itemID);
setTitle(title);
setAuthor(author);
setDate(date);
setPrice(price); // code in the superclass
setInStock(inStock); // code in the superclass
bookCount++; // keep track of the number of books
}; // end of five argument constructor
///////// getters and setters //////////
public String getTitle( ) { return title; }
public String getAuthor( ) { return author; }
public int getDate( ) { return date; }
public static int getBookCount() { return bookCount; }
// setters
public String setTitle (String t) { title=t; return title; }
public String setAuthor (String a) { author=a; return author; }
public int setDate (int d) { date=d; return date; }
@Override
public double setPrice(double price) {
if (price < 0) {
this.price = 0.00;
System.out.println ("Negative price not allowed");
}
else if (price > MAX_BOOK_PRICE) {
this.price = MAX_BOOK_PRICE;
System.out.println ("Attempted to set pice too high");
}
else
this.price = price;
return this.price;
} // end of setPrice( )
@Override
public String toString() {
return String.format ("%d %6.2f %s, by %s",
getItemID(), getPrice(), getTitle(), getAuthor());
}
}; // end of class Book
Ниже приведен код для класса моей рубашки
public class Shirt extends Clothing {
private String size;
private static int shirtCount = 0;
// getters
public String getSize() { return size; }
// setters
public String setSize( String size ) {
this.size=size;
return this.size; }
///// constructors
Shirt() {
shirtCount++; // keep track of the number of shirts
}
Shirt(int itemID, String type, String brand, String size, String color, double price, int inStock) {
setItemID(itemID);
setType(type);
setBrand(brand);
setSize(size);
setColor(color);
setPrice(price); // located in the superclass
setInStock(inStock); // located in the superclass
shirtCount++; // keep track of the number of shirts
} // end of the six argument constructor
@Override
public String toString() {
return String.format ("%d %6.2f %s, by %s - %s",
getItemID(), getPrice(), getType(), getBrand(), getSize());
}
}
Ниже приведен код для класса одежды:
public class Clothing extends Item {
private String type;
private String brand;
private String color;
///// getters
public String getType ( ) { return type; }
public String getBrand( ) { return brand; }
public String getColor( ) { return color; }
//// setters
public String setType ( String type ) {
this.type=type;
return this.type;
}
public String setBrand( String brand ) {
this.brand=brand;
return this.brand;
}
public String setColor( String color ) {
this.color=color;
return this.color;
}
// constructors
Clothing( ) { } // empty default constructor
Clothing( String type, String brand, String color) {
setType(type);
setBrand(brand);
setColor(color);
} // end of three-argument constructor
}
Я ожидаю, чтопрограмма покажет «Нет в наличии», если элемент, который вводит пользователь, недоступен. Большое спасибо за вашу помощь!