I have some problem code I pulled from a book that should not be saying a non-static variable or method needs to be static. The error on the variable comes without me changing anything with that code. The error in the method came after I added code to it but now even when I take the code out it still gives me the error. I have the variable error in Product.java in the getFormattedPrice method in the format currency statement. The method error is in the main method when I call writeProducts.
public class Product
{
private String code;
private String description;
private double price;
public Product(String code, String description, double price)
{
this.code = code;
this.description = description;
this.price = price ;
}
public Product()
{
this("", "", 0);
}
public void setCode(String code)
{
this.code = code;
}
public String getCode(){
return code;
}
public void setDescription(String description)
{
this.description = description;
}
public String getDescription()
{
return description;
}
public void setPrice(double price)
{
this.price = price;
}
public double getPrice()
{
return price;
}
public static String getFormattedPrice()
{
NumberFormat currency = NumberFormat.getCurrencyInstance();
return currency.format(price);
}
public String getFormattedPrice(double price)
{
NumberFormat currency = NumberFormat.getCurrencyInstance();
return currency.format(price);
}
public boolean equals(Object object)
{
if (object instanceof Product)
{
Product product2 = (Product) object;
if
(
code.equals(product2.getCode()) &&
description.equals(product2.getDescription()) &&
price == product2.getPrice()
)
return true;
}
return false;
}
public String toString()
{
return "Code: " + code + "\n" +
"Description: " + description + "\n" +
"Price: " + this.getFormattedPrice() + "\n";
}
}
main method
public class XMLTesterApp
{
private static String productsFilename = "products.xml";
public static void main(String[] args)
{
System.out.println("Products list:");
ArrayList<Product> products = readProducts();
printProducts(products);
for(Product p2 : products){
System.out.println(p2.getPrice());
}
Product p1 = new Product("test", "XML Tester", 77.77);
products.add(p1);
writeProducts(products);
System.out.println("XML Tester has been added to the XML document.\n");
System.out.println("Products list:");
products = readProducts();
printProducts(products);
products.remove(2);
writeProducts(products);
System.out.println("XML Tester has been deleted from the XML document.\n");
System.out.println("Products list:");
products = readProducts();
printProducts(products);
}
private static ArrayList<Product> readProducts()
{
ArrayList<Product> products = new ArrayList<>();
Product p = null;
XMLInputFactory inputFactory = XMLInputFactory.newFactory();
try{
FileReader fileReader = new
FileReader("C:\\Users\\AndrewSpiteri\\Documents\\Classes\\Baker\\CS 242\\java\\netbeans\\ex_starts\\ch19_ex1_XMLTester\\products.xml");
XMLStreamReader reader = inputFactory.createXMLStreamReader(fileReader);
while(reader.hasNext()){
int eventType = reader.getEventType();
switch(eventType){
case XMLStreamConstants.START_ELEMENT:
String elementName = reader.getLocalName();
if(elementName.equals("Product")){
p = new Product();
String code = reader.getAttributeValue(0);
p.setCode(code);
}
if(elementName.equals("Description")){
String description = reader.getElementText();
p.setDescription(description);
}
if(elementName.equals("Price")){
String priceString = reader.getElementText();
double price = Double.parseDouble(priceString);
p.setPrice(price);
}
break;
case XMLStreamConstants.END_ELEMENT:
elementName = reader.getLocalName();
if(elementName.equals("Product"))
products.add(p);
break;
default:
break;
}
reader.next();
}
}
catch(IOException | XMLStreamException e){
System.out.println(e);
}
// add code that reads the XML document from the products.xml file
return products;
}
private void writeProducts(ArrayList<Product> products)
{
XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
try{
FileWriter fileWriter = new
FileWriter("C:\\Users\\AndrewSpiteri\\Documents\\Classes\\Baker\\CS 242\\java\\netbeans\\ex_starts\\ch19_ex1_XMLTester\\products.xml");
XMLStreamWriter writer = outputFactory.createXMLStreamWriter(fileWriter);
writer.writeStartDocument("1.0");
writer.writeStartElement("Products");
for(Product product : products){
writer.writeStartElement("Product");
writer.writeAttribute("Code", product.getCode());
writer.writeStartElement("Description");
writer.writeCharacters(product.getDescription());
writer.writeEndElement();
writer.writeStartElement("Price");
double price = product.getPrice();
writer.writeCharacters(Double.toString(price));
writer.writeEndElement();
writer.writeEndElement();
}
writer.writeEndElement();
writer.flush();
writer.close();
}
catch(IOException | XMLStreamException e){
System.out.println(e);
}
}
private static void printProducts(ArrayList<Product> products)
{
for (Product p : products)
{
printProduct(p);
}
System.out.println();
}
private static void printProduct(Product p)
{
String productString =
StringUtils.padWithSpaces(p.getCode(), 8) +
StringUtils.padWithSpaces(p.getDescription(), 44) +
p.getFormattedPrice();
System.out.println(productString);
}
}
Remove the static from this method.
public static String getFormattedPrice()
{
NumberFormat currency = NumberFormat.getCurrencyInstance();
return currency.format(price);
}
You get the error because price in an instance variable, not a static class variable.
And add static to private void writeProducts in order to call writeProducts from another static method.
Related
public void alphabeticalListing()
{
BufferedReader br = null;
List<String> lineList = new ArrayList<String>();
try
{
br = new BufferedReader(new FileReader(wishlistname + ".txt"));
String line;
while((line = br.readLine())!=null)
{
lineList.add(line);
}
Collections.sort(lineList);
for(String output : lineList) {
System.out.println(output);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
The file Contains Movie Details...
Example:
MovieName:DirectorName:ProducerName:Rating:Review
Terminator: Arfath: Khalid : 8 : VeryGood
Hangover : John : Lucas : 7 : NotBad
Jumanji : Rock : Brock : 9 : Good
I want to select ProducerName Column and do SOP in alphabetically like,
Output:
Brock
Khalid
Lucas
You can use java Compartor for sorting by creating Movie as model class. You can achieve this using below code:
public static void readDataFromFile(String filePath) throws FileNotFoundException
{
List<Movie> movies = new ArrayList<Movie>();
File file = new File(filePath);
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
{
String txtLine = sc.nextLine();
//Extract data from single from txt file row
String[] data = txtLine.split(":");
Movie movie = new Movie(data[0], data[1], data[2], data[3], data[4]);
//Add to movies list
movies.add(movie);
}
System.out.println("Unsorted-----------");
System.out.println(movies);
System.out.println("Sorting by director-----------");
Collections.sort(movies, new DirectorSorter());
System.out.println(movies);
System.out.println("Sorting by producer-----------");
Collections.sort(movies, new ProducerSorter());
System.out.println(movies);
}
public static class Movie
{
private String name;
private String director;
private String producer;
private String rating;
private String review;
public Movie(){}
public Movie(String name, String director, String producer, String rating, String review){
this.name = name;
this.director = director;
this.producer = producer;
this.rating = rating;
this.review = review;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getProducer() {
return producer;
}
public void setProducer(String producer) {
this.producer = producer;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public String getReview() {
return review;
}
public void setReview(String review) {
this.review = review;
}
#Override
public String toString() {
return "Movie : " + name + " - " + director + " - " + producer + " - " + rating + " - " + review + "\n";
}
}
public static class DirectorSorter implements Comparator<Movie>{
#Override
public int compare(Movie o1, Movie o2) {
return o1.getDirector().compareTo(o2.getDirector());
}
}
public static class ProducerSorter implements Comparator<Movie>{
#Override
public int compare(Movie o1, Movie o2) {
return o1.getProducer().compareTo(o2.getProducer());
}
}
I'm working on a shop program and i'm trying to find the total value of the products in stock. The data related to each item is present in a row of the file named "SHOP.txt", like : "H;L;10;€10,50;83259875;YellowPaint"(that is the first line of the file where all the products are saved in this format, separated by ";" : department,unityOfmeasure,quantity,price,code,name).To calculate the total value, the program read each token from the aforementioned line and calculate the value by multiplying quantity for price.
I already saved in the file about 10 products but when i try to compile my code, I keep getting an error and it calculate the value only of the first product.
public static void main(String[] args) throws IOException {
while (running) {
System.out.println("\nPress 0 to load the inventory. " + "\nPress 1 to save and close"
+ "\nPress 2 to add products to the inventory" + "\nPress 3 to find products"
+ "\nPress 4 for the total value of the inventory");
int answer = in.nextInt();
switch (answer) {
case 0:
System.out.println("insert the name of the file to load");
Loading(in.next());
break;
case 1:
saveAndQuit();
break;
case 2:
addProduct();
break;
case 3:
inputCode();
break;
case 4:
inventoryValue();
break;
}
}
System.exit(0);
}
private static void inventoryValue() throws FileNotFoundException {
Scanner scanner = new Scanner(new File("SHOP.txt"));
scanner.useDelimiter(";|\n");
Product[] products = new Product[0];
while (scanner.hasNext()) {
String department = scanner.next();
String unityOfMeasure = scanner.next();
int quantity = scanner.nextInt();
double price = scanner.nextDouble();
String code = scanner.next();
String name = scanner.next();
Product newProduct = new Product(department, unityOfMeasure, quantity, price, code, name);
products = newProduct(products, newProduct);
double totalValue = Arrays.stream(products).mapToDouble(p -> p.quantity * p.price).sum();
System.out.println("Total Value: " + totalValue + "\n\n");
for (Product product : products) {
System.out.println(product);
}
}
}
private static Product[] newProduct(Product[] products, Product productToAdd) {
Product[] newProducts = new Product[products.length + 1];
System.arraycopy(products, 0, newProducts, 0, products.length);
newProducts[newProducts.length - 1] = productToAdd;
return newProduct;
}
This is the complete code as requested.
Product Class:
public class Product implements Serializable {
protected String department;
protected String unityOfMeasure;
protected int quantity;
protected double price;
protected String code;
protected String name;
private static NumberFormat formatter = new DecimalFormat("#0.00");
public Product(String dep, String uom, int qnt, double prz, String cod, String nm) {
reparto = dep;
unitaDiMisura = uom;
quantità = qnt;
prezzo = prz;
codice = cod;
nome = nm;
}
// setters
public void setDep(String rep) {
this.department = department;
}
public void setPrz(double prz) {
this.price = price;
}
public void setUdm(String udm) {
this.unityOfMeasure = unityOfMeasure;
}
public void setQnt(int qnt) {
this.quantity = quantity;
}
public void setCod(String cod) {
this.code = code;
}
public void setNm(String nm) {
this.name = name;
}
// getters
public String getDep() {
return department;
}
public String getUom() {
return unityOfMeasure;
}
public double getPrz() {
return price;
}
public int getQnt() {
return quantity;
}
public String getCod() {
return code;
}
public String getNm() {
return name;
}
public double getTotal() {
return quantity * price;
}
public void remove() {
this.quantity--;
}
public String toString() {
// ----quantity not less than 0 ----
if (quantity < 0) {
System.out.println(quantity = 0);
}
return String.format(department + ";" + unityOfMeasure + ";" + quantity + ";" + "€" + formatter.format(price) + ";"
+ code+ ";" + name + " \n");
}
}
Shop Class:
public class Shop implements Serializable {
public List<Product> collection;
public Shop() {
collection = new ArrayList<Product>();
}
public void addProduct(Product product) {
collection.add(product);
}
public void sellProduct(String name) {
for (Product product : collection) {
if (name.equals(product.getNm())) {
if (product.getQnt() >= 0) {
prodotto.remove();
}
return;
}
}
}
public void duplicatedProduct(String code) {
for (Product product : collection) {
if (code.equals(product.getCod())) {
System.out.println("Error. Duplicated product");
}
return ;
}
}
#Override
public String toString() {
String total = "\n";
Iterator<Product> i = collection.iterator();
while (i.hasNext()) {
Product l = (Product) i.next();
total = total + l.toString();
}
return total;
}
}
Main Class:
public class Main {
static String fileName = null;
static Shop shp = new Shop();
static Scanner in = new Scanner(System.in);
static boolean running = true;
public static void main(String[] args) throws IOException {
while (running) {
System.out.println("\nPress 0 to load inventory. " + "\nPress 1 to save and quit"
+ "\nPress 2 to add product to the inventory" + "\nPress 3 to find a product"
+ "\nPress 4 for the total value of the inventory");
int answer = in.nextInt();
switch (answer) {
case 0:
System.out.println("Insert the name file to load.");
Loading(in.next());
break;
case 1:
saveAndQuit();
break;
case 2:
addProduct();
break;
case 3:
inputCode();
break;
case 4:
inventoryValue();
break;
}
}
System.exit(0);
}
private static void inventoryValue() throws FileNotFoundException {
Scanner scanner = new Scanner(new File("SHOP.txt"));
scanner.useDelimiter(";|\n");
Product[] products = new Product[0];
while (scanner.hasNext()) {
String department = scanner.next();
String unityOfMeasure = scanner.next();
int quantity = scanner.nextInt();
double price = scanner.nextDouble();
String code = scanner.next();
String name = scanner.next();
Product newProduct = new Product(department, unityOfMeasure, quantity, price, code, name);
products = newProduct(products, newProduct);
double totalValue = Arrays.stream(products).mapToDouble(p -> p.quantity * p.price).sum();
System.out.println("Total Value: " + totalValue + "\n\n");
for (Product product : products) {
System.out.println(product);
}
}
}
private static Product[] newProduct(Product[] products, Product productToAdd) {
Product[] newProducts = new Product[products.length + 1];
System.arraycopy(products, 0, newProducts, 0, products.length);
newProducts[newProducts.length - 1] = productToAdd;
return newProduct;
}
private static void inputCode() throws IOException {
String code;
String line = null;
System.out.println("\nInsert code: ");
code = in.next();
try {
FileReader fileReader = new FileReader("SHOP.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
String[] token = line.split(";");
if ((";" + line + ";").contains((";" + code + ";"))) {
System.out.println(line);
}
}
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println("Impossible to open the file ");
} catch (IOException ex) {
System.out.println("error opening the file ");
}
}
private static void addProduct() {
String department;
String unityOfMeasure;
int quantity;
double price;
String code;
String name;
System.out.println("\ninsert department: ");
department= in.next();
System.out.println("\ninsert unity of measure: ");
unityOfMeasure = in.next();
System.out.println("\ninserit quantity: ");
quantity = in.nextInt();
System.out.println("\ninsert price: ");
price = in.nextDouble();
System.out.println("\ninsert code: ");
code = in.next();
System.out.println("\ninsert name: \n");
name = in.next();
Product p = new Product(department, unityOfMeasure, quantity, price, code, name);
shp.addProduct(p);
}
private static void saveAndQuit() {
running = false;
PrintWriter printWriter = null;
try {
printWriter = new PrintWriter(new FileWriter("SHOP.txt", true));
printWriter.println(shp);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (printWriter != null) {
printWriter.close();
}
}
}
private static void Loading(String name) throws IOException {
FileReader fr;
fr = new FileReader("SHOP.txt");
BufferedReader br;
br = new BufferedReader(fr);
String s;
while (true) {
s = br.readLine();
if (s == null)
break;
System.out.println(s);
}
br.close();
fr.close();
}
}
This is the content of the txt File (SHOP.txt) where products are stored :
H;L;10;10,50;83259875;YellowPaint
E;U;20;1,50;87678350;Lamp
H;L;10;10,50;83259891;BluePaint
H;L;10;10,00;83259892;RedPAint
H;U;30;12,00;98123742;Hammer
G;U;80;15,00;87589302;Seeds
G;U;3;130,00;17483921;Lawnmower
this is the error that i expect to solve:
Total value: 105.0
H;L;10;€10,50;83259875;YellowPaint
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Main.inventoryValue(Main.java:68)
at Main.main(Main.java:47)
How can I solve this problem?
In your file where you say it is storing a double for the price, it should just be a decimal value. You have a '€' symbol in front of it and a ',' instead of a '.'. scanner.nextDouble() will not work if there is another symbol there. I'd recommend to store your prices without the currency symbol and a decimal rather than a comma and just append the '€' in front of wherever you plan on showing your total as so:
System.out.println("Total Value: €" + totalValue + "\n\n");
I'm unfamiliar with getters and setters (and basically just Java) but I have to use them for this assignment, so if I did anything wrong with those please tell me.
The more important issue is the error that I am getting on my method. The word for word instructions from my assignment for the particular method I'm working on are:
Your processData() method should take all the record data from your ArrayList and add the data into each of your instance fields via your setters.
But I keep getting an error that says:
Type mismatch: cannot convert from element type String[] to List
On the line that says "for (List<String> rowData: content)" on the word content.
Thank you very much for any help you can give me.
My code so far:
public abstract class Client {
String file = "bank-Detail.csv";
ArrayList<String[]> bank = new ArrayList<>();
static Client o[] = new Client[12];
public Client(String file) {
this.file = file;
}
private String ID;
private String Age;
private String Sex;
private String Region;
private String Income;
private String Married;
private String Children;
private String Car;
private String Save_Act;
private String Current_Act;
private String Mortgage;
private String Pep;
public List<String[]> readData() throws IOException {
//initialize variable
int count = 0;
//name file
String file = "bank-Detail.txt";
//make array list
List<String[]> content = new ArrayList<>();
//trycatch for exceptions
try {
//file reader
BufferedReader br = new BufferedReader(new FileReader(file));
//string to add lines to
String line = "";
while ((line = br.readLine()) != null) {
content.add(line.split(","));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
processData(content);
return content;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getAge() {
return Age;
}
public void setAge(String age) {
this.Age = age;
}
public String getSex() {
return Sex;
}
public void setSex(String sex) {
Sex = sex;
}
public String getRegion() {
return Region;
}
public void setRegion(String region) {
Region = region;
}
public String getIncome() {
return Income;
}
public void setIncome(String income) {
Income = income;
}
public String getMarried() {
return Married;
}
public void setMarried(String married) {
Married = married;
}
public String getChildren() {
return Children;
}
public void setChildren(String children) {
Children = children;
}
public String getCar() {
return Car;
}
public void setCar(String car) {
Car = car;
}
public String getSave_Act() {
return Save_Act;
}
public void setSave_Act(String save_Act) {
Save_Act = save_Act;
}
public String getCurrent_Act() {
return Current_Act;
}
public void setCurrent_Act(String current_Act) {
this.Current_Act = current_Act;
}
public String getMortgage() {
return Mortgage;
}
public void setMortgage(String mortgage) {
this.Mortgage = mortgage;
}
public String getPep() {
return Pep;
}
public void setPep(String pep) {
Pep = pep;
}
public String toString() {
return "[ID = " + ", age=";
/// ect....
}
public void processData(List<String[]> content) {
int index = 0;
for (List<String> rowData : content) {
//initialize array of objects
//o[index] = new Client();
//use setters to populate your array of objects
o[index].setID(rowData.get(0));
o[index].setAge(rowData.get(1));
o[index].setRegion(rowData.get(3));
o[index].setSex(rowData.get(2));
o[index].setIncome(rowData.get(4));
o[index].setMarried(rowData.get(5));
o[index].setChildren(rowData.get(6));
o[index].setCar(rowData.get(7));
o[index].setSave_Act(rowData.get(8));
o[index].setCurrent_Act(rowData.get(9));
o[index].setMortgage(rowData.get(10));
o[index].setPep(rowData.get(11));
System.out.println(rowData);
index++;
}
}
public void printData() {
}
}
The problem is in the processData method. The type of content is List<String[]>. So when you try to loop this list, each element is a String array, not List. Also, since each element in your list is a String array, you can access the elements of each of the String Array elements of the list by using the normal array square brackets, instead of get method of List. Try the following fix:
public void processData(List<String[]> content) {
int index=0;
for (String[] rowData: content){
//initialize array of objects
//o[index] = new Client();
//use setters to populate your array of objects
o[index].setID(rowData[0]);
o[index].setAge(rowData[1]);
o[index].setRegion(rowData[3]);
o[index].setSex(rowData[2]);
o[index].setIncome(rowData[4]);
o[index].setMarried(rowData[5]);
o[index].setChildren(rowData[6]);
o[index].setCar(rowData[7]);
o[index].setSave_Act(rowData[8]);
o[index].setCurrent_Act(rowData[9]);
o[index].setMortgage(rowData[10]);
o[index].setPep(rowData[11]);
System.out.println(rowData);
index++;
}
}
As your error hints at... content is a List<String[]>, so it contains String[] elements, not List<String> elements.
If your end goal is a list of Client objects, just make the method List<Client> readData() instead.
List<Client> clients = new ArrayList<Client>();
BufferedReader br = null;
try {
//file reader
br = new BufferedReader(new FileReader(file));
//string to add lines to
String line = "";
Client c = null;
while ((line = br.readLine()) != null) {
c = new Client();
String[] rowData = line.split(",");
c.setID(rowData.get(0));
...
clients.add(c);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (Exception e) {}
}
return clients;
New to Java.
I have a txt file:
hat, 20, 1
pants, 50, 45
shoes, 100, 10
In one class called Goods I have been able to read it, split it using delimiter, add it to an ArrayList.
I have another class called GoodsList where I will be creating an ArrayList which should have the above as an object that I can use if the user requests it. Thanks
I think you are asking about java generics.
If so, create your Goods class since you need to access it as an object via the ArrayList.
public Class Goods implements Serializable {
private String goodName;
private double price;
private int quantity;
public String getGoodName() {
return goodName;
}
public void setGoodName(String goodName) {
this.goodName = goodName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
and then Write your GoodsList class to create the list with Goods object you set:
public class GoodsList {
public static void main(String args[]) {
Goods g = new Goods();
Goods g2 = new Goods();
Goods g3 = new Goods();
g.setGoodName("hat");
g.setQuantity(50);
g.setPrice(100.00);
g2.setGoodName("pants");
g2.setQuantity(50);
g2.setPrice(100.00);
g3.setGoodName("shoes");
g3.setQuantity(50);
g3.setPrice(100.00);
List < Goods > goodsList = new ArrayList < Goods > ();
goodsList.add(g);
goodsList.add(g2);
goodsList.add(g3);
//printing goods:
for (Goods g: goodsList) {
System.out.println(g.getGoodName() + "," + g.getQuantity() + "," + g.getPrice());
}
}
}
is that what you're looking for?
Are you looking for something like:
public class FileReaderExample
{
public class Goods
{
private String goodName = null;
private String price = null;
private String quantity = null;
public Goods(String goodName ,String price,String quantity)
{
this.goodName = goodName;
this.price = price;
this.quantity = quantity;
}
public String getGoodName()
{
return goodName;
}
public void setGoodName(String goodName)
{
this.goodName = goodName;
}
public String getPrice()
{
return price;
}
public void setPrice(String price)
{
this.price = price;
}
public String getQuantity()
{
return quantity;
}
public void setQuantity(String quantity)
{
this.quantity = quantity;
}
}
private ArrayList<Goods> populateGoods()
{
ArrayList<Goods> goodsList = new ArrayList<Goods>();
File file = new File("d:\\text.txt");
try
{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null)
{
String[] itemsOnLine = line.trim().split(",");
goodsList.add(new Goods(itemsOnLine[0],itemsOnLine[1],itemsOnLine[2]));
}
}
catch (IOException e)
{
e.printStackTrace();
}
return goodsList;
}
public static void main(String[] args)
{
FileReaderExample fileReaderExample = new FileReaderExample();
ArrayList<Goods> goodsList = fileReaderExample.populateGoods();
for (Goods goods : goodsList)
{
System.out.println(goods.getGoodName());
}
}
}
I'm learning java and my programming skills are are good. I have been asked to find out the problem with codes below. when I paste them on netbeans, the error that had been detected was in the public class CheckoutProgram (String wordIn = Keyboard.readInput(); and wordIn = Keyboard.readInput();) and I noticed that the public static void method was empty but I'm not sure it has anything to do with the error. I have tried to find a solution myself but I can't sort it out. Can you help me with this issue? please
import java.io.*;
import java.text.DecimalFormat;
public class CheckoutProgram {
public static void main (String[] args) {
}
public void start() {
SalesItem[] items = getStock();
System.out.print("Type item code (press enter to finish):");
String wordIn = Keyboard.readInput();
SalesItem[] goods = new SalesItem[1000];
int count = 0;
while (wordIn.length()>=4 && wordIn.length()<=4){
for (int i=0;i<items.length;i++) {
if (items[i] != null && wordIn.equals(items[i].getItemCode())){
System.out.println(items[i]);
goods[count] = items[i];
}
}
System.out.print("Type item code (press enter to finish):");
wordIn = Keyboard.readInput();
count++;
}
System.out.println();
System.out.println("==========Bill==========");
double amountDue = 0.0;
for (int i=0; i<count; i++){
System.out.println(goods[i]);
amountDue = amountDue + goods[i].getUnitPrice();
}
System.out.println();
System.out.println("Amount due: $" + new DecimalFormat().format(amountDue));
System.out.println("Thanks for shopping with us!");
}
// method to read in "stock.txt" and store the items for sale in an array of type SalesItem
private SalesItem[] getStock(){
SalesItem[] items = new SalesItem[1000];
try {
BufferedReader br = new BufferedReader(new FileReader("stock.txt"));
String theLine;
int count = 0;
while ((theLine = br.readLine()) != null) {
String[] parts = theLine.split(",");
items[count] = new SalesItem(parts[0],parts[1],Double.parseDouble(parts[2]));
if (parts.length==4){
String discount = parts[3];
String numPurchases = discount.substring(0, discount.indexOf("#"));
String price = discount.substring(discount.indexOf("#")+1);
items[count].setNumPurchases(Integer.parseInt(numPurchases));
items[count].setDiscountedPrice(Double.parseDouble(price));
}
count++;
}
}
catch (IOException e) {
System.err.println("Error: " + e);
}
return items;
}
}
import java.text.DecimalFormat;
public class SalesItem {
private String itemCode; //the item code
private String description; // the item description
private double unitPrice; // the item unit price
// An item may offer a discount for multiple purchases
private int numPurchases; //the number of purchases required for receiving the discount
private double discountedPrice; // the discounted price of multiple purchases
// the constructor of the SalesItem class
public SalesItem (String itemCode, String description, double unitPrice){
this.itemCode = itemCode;
this.description = description;
this.unitPrice = unitPrice;
}
// accessor and mutator methods
public String getItemCode(){
return itemCode;
}
public void setItemCode(String itemCode){
this.itemCode = itemCode;
}
public String getDescription(){
return description;
}
public void setDescription(String description){
this.description = description;
}
public double getUnitPrice(){
return unitPrice;
}
public void setUnitPrice(double unitPrice){
this.unitPrice = unitPrice;
}
public int getNumPurchases(){
return numPurchases;
}
public void setNumPurchases(int numPurchases){
this.numPurchases = numPurchases;
}
public double getDiscountedPrice(){
return discountedPrice;
}
public void setDiscountedPrice(double discountedPrice){
this.discountedPrice = discountedPrice;
}
// the string representation of a SalesItem object
public String toString(){
return description + "/$" + new DecimalFormat().format(unitPrice);
}
}
Keyboard most likely doesn't exist. It isn't a part of the standard Java library. You would have to import a class that uses Keyboard if you are trying to use some custom class to read user input.
I assume you are getting the error because you do not have the class Keyboard. Check for a file called Keyboard.java.. This is more of a comment than an answer.
Firstly you are using public for a class CheckoutProgram so the file name should be same as the class name when you used public access specifier for a class.
Secondly the Keyboard class is missing in your program so please check with these issues.