java program to search product from name in object code example
Example: java program to search item from name in class
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*
public class Catalog{
private static int MAX_ITEMS = 10;
private Products[] list;
private int nextItem;
public Catalog(){
list = new Products[MAX_ITEMS];
nextItem = 0;
}
public void loadList(String fileName)
throws FileNotFoundException {
if ( (fileName != null) && (!fileName.equals("")) ) {
Scanner input = new Scanner(new File(fileName));
String newLine = null;
String name = null;
int quantity = 0;
double price = 0.0;
while (input.hasNextLine() && nextItem < MAX_ITEMS) {
if (input.hasNext()) {
name = input.next();
} else {
System.err.println("ERROR Not a String");
System.exit(2);
}
if (input.hasNextInt()) {
quantity = input.nextInt();
} else {
System.err.println("ERROR Not an integer");
System.exit(2);
}
if (input.hasNextDouble()) {
price = input.nextDouble();
} else {
System.err.println("ERROR Not a double");
System.exit(2);
}
list[nextItem] = new Products(name, quantity, price);
newLine = input.nextLine();
nextItem += 1;
}
}
return;
}
public double getTotalPrice(){
double total = 0.0;
for(int i=0; i < nextItem; i++){
Products products = list[i];
total+=products.getTotalPrice();
}
return total;
}
public Products getProducts(String name){
**
for(int i=0; i<nextItem; i++){
Products item = list[i];
if(item.equals(name)){
return item;
}
public static void main(String[] args)
throws FileNotFoundException {
Catalog catalog= new Catalog();
catalog.loadList(args[0]);
System.out.println();
System.out.format("Total Price = %9.2f\n", catalog.getTotalPrice());
}
}