No Suitable Found for add String - java

Am trying to retrieve data I Chosen From mysql and filter table the Item I choose by getting value of chosen Item I created A list this list am trying to add on it the chosen Item but I fount an underlined error No Suitable Found for add String
this is my main.java contains code I use
List<Menu> listItem = new ArrayList<Menu>();
if (insertedNumberOfCovers) {
Menu m = new Menu();
m.getAllRows();
while (orderNotFinished) {
System.out.println("Please Choose Item From Menu List");
input = new Scanner(System.in);
itemChosen = input.nextLine();
boolean insertedMenuItemId = db.goTodataBase.checkMenuItemInDB(itemChosen);
if (insertedMenuItemId) {
System.out.println("You Choose Item ID: " + itemChosen);
listItem.add(m.getAllRows(itemChosen));
System.out.print("Do you need to add more Items ? ");
hasFinished = input.nextLine();
orderNotFinished = hasFinished.equals("yes");
} else {
System.out.println("Item Chosen doen't exist");
}
}
and this is Menu.java that I retrieve data from
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package enitities;
import javax.swing.JTable;
public class Menu {
private int Menu_Id;
private String Name;
private float Price;
private String Type;
private String Category;
public int getMenu_Id() {
return Menu_Id;
}
public void setMenu_Id(int Menu_Id) {
this.Menu_Id = Menu_Id;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public float getPrice() {
return Price;
}
public void setPrice(float Price) {
this.Price = Price;
}
public String getType() {
return Type;
}
public void setType(String Type) {
this.Type = Type;
}
public String getCategory() {
return Category;
}
public void setCategory(String Category) {
this.Category = Category;
}
public void getAllRows() {
db.goTodataBase.printData("menu");
}
public Menu getAllRows(Menu itemChosen) {
db.goTodataBase.printData("menu");
return itemChosen;
}
public String getValueByName(String itemChosen) {
String strSelect = "select Menu_Id from menu"
+ "where name=" + Name;
return itemChosen;
}
}
and this method that am Using to Print Table Values
public static void printData(String tableNameOrSelectStatement) {
try {
setConnection();
Statement stmt = con.createStatement();
ResultSet rs;
String strSelectPart = tableNameOrSelectStatement.substring(0, 4).toLowerCase();
String strSelect;
if ("select ".equals(strSelectPart)) {
strSelect = tableNameOrSelectStatement;
} else {
strSelect = "select * from " + tableNameOrSelectStatement;
}
rs = stmt.executeQuery(strSelect);
ResultSetMetaData rsmd = rs.getMetaData();
int c = rsmd.getColumnCount();
while (rs.next()) {
for (int i = 1; i <= c; i++) {
if (i > 1) {
System.out.print(", ");
}
String columnValue = rs.getString(i);
// System.out.print(columnValue + " " + rsmd.getColumnName(i));
System.out.print(columnValue + " ");
}
System.out.println("");
}
} catch (Exception e) {
Tools.msgBox(e.getMessage());
}
}
the error in this line
listItem.add(m.getAllRows(itemChosen));

The type error is pretty clear to me:
Menu.getAllRows(...) returns String.
listItem.add(...) takes Menu as an argument.
A String is not a Menu. Therefore you have a type error.
That said: you have many, many other things wrong with this code. Names that defy standard Java naming conventions, methods that don't do anything useful (why does getAllRows take Object as an argument but just cast it to a String to return it?), using float to store a currency value, and probably more.

Related

How to input data in the very best way in object programming Java

Just to let you know:
I know how to use Scanner od BufferedReader, just dont know where to use it in this case.
I am working on my first bigger app in Java.
(I had to use SQLite as a DB)
That's some kind of gym app, where I will add my workouts (4 simple variables)
And then it will be saved in DB and sorted to read out.
My question is...
How should I add an Input from the user?
I have setters and getters and no Idea where this input should be added.
In main class? Should I build a new method?
package bazadanych;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
DBConnector d = new DBConnector();
d.addWorkout( "bicek", 12, 5,22052019);
List<Workout> workouts = d.allWorkouts();
for (int i=0; i < workouts.size(); i++) {
System.out.println("---------------------------------");
System.out.println("The name of the excersise: " + workouts.get(i).getName());
System.out.println(" Number of reps: " + workouts.get(i).getReps());
System.out.println(" Weight: " + workouts.get(i).getWeight() + "kg");
System.out.println("Date: " + workouts.get(i).getDate());
System.out.println("---------------------------------");
}
}
package bazadanych;
public class Workout extends DBConnector {
private int workoutId;
private String name;
private int reps;
private int weight;
private int date;
public Workout(int workoutId, String name, int weight, int reps, int date)
{
setWorkoutId(workoutId);
setName(name);
setWeight(weight);
setReps(reps);
setDate(date);
}
// Getters
public int getDate()
{
return date;
}
public int getWorkoutId()
{
return workoutId;
}
public String getName()
{
return name;
}
public int getReps()
{
return reps;
}
public int getWeight()
{
return weight;
}
//Setters
public void setDate(int date)
{
this.date = date;
}
public void setName(String name)
{
this.name = name;
}
public void setReps(int reps)
{
this.reps = reps;
}
public void setWorkoutId(int workoutId)
{
this.workoutId = workoutId;
}
public void setWeight(int weight)
{
this.weight = weight;
}
}
package bazadanych;
import java.sql.*;
import java.util.LinkedList;
import java.util.List;
public class DBConnector {
// connection with datebase
private Connection conn;
// The object used to execute a static SQL statement and returning the results
private Statement stat;
// Construct
public DBConnector()
{
try
{
Class.forName("org.sqlite.JDBC");
}
catch (ClassNotFoundException e)
{
System.err.println("There is no JDBC driver");
e.printStackTrace();
}
try
{
conn = DriverManager.getConnection("jdbc:sqlite:GymApp.db"); // GymApp will be the name of the datebase
stat = conn.createStatement();
}
catch (SQLException e)
{
System.err.println("I can not connect");
}
CreateStructure();
}
public boolean CreateStructure()
{
// Rule to delete the table and create new, when we want to rework number of columnes etc.
// String dropFirst = "DROP TABLE IF EXISTS workouts;";
String sql = "CREATE TABLE IF NOT EXISTS workouts"
+ "("
+ "workoutId INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "name varchar(100),"
+ "reps INTEGER, "
+ " weight INTEGER,"
+ " date INTEGER"
+ ")";
try
{
// stat.execute(dropFirst);
stat.execute(sql);
}
catch (SQLException e)
{
System.err.println("There is a problem by Structure creation");
e.printStackTrace();
return false;
}
return true;
}
public boolean addWorkout( String name, int reps, int weight, int date)
{ String sql = " insert into workouts values (Null,?,?,?,?);";
try
(PreparedStatement pStmt = conn.prepareStatement(sql)){
pStmt.setString(1, name);
pStmt.setInt(2,reps);
pStmt.setInt(3,weight);
pStmt.setInt(4, date);
pStmt.execute();
}
catch(SQLException e)
{
System.err.println("Can not add a new contact");
e.printStackTrace();
return false;
}
return true;
}
public List<Workout> allWorkouts()
{
List<Workout> workouts = new LinkedList<Workout>();
try {
ResultSet show = stat.executeQuery("SELECT * FROM workouts ORDER BY date");
int id;
String name;
int reps;
int weight;
int date;
while (show.next())
{
id = show.getInt("workoutId");
name = show.getString("name");
reps = show.getInt("reps");
weight = show.getInt("weight");
date = show.getInt("date");
workouts.add(new Workout(id, name,reps,weight,date));
}
}
catch (SQLException e)
{
e.printStackTrace();
return null;
}
return workouts;
}
public void closeConnection() {
try{
conn.close();
}
catch (SQLException e) {
System.err.println("There is connection closing error");
e.printStackTrace();
}
}
}
To answer your main question, you should add the input from the user in the main method. You'd use an instance of Scanner to read the values of workout name, reps and weight. Date you could simply pick up the current date, code sample below.
A few other recommendations:
1 - Change the workout date to long, that's a standard in the industry.
2 - The method CreateStructure does not follow Java coding standards, rename it to createStructure.
3 - You are storing the workout ID as NULL, that could cause you trouble later when trying to retrieve the data from the database.
Code sample:
public static void main(String[] args) {
DBConnector d = new DBConnector();
// Retrieve input from the user
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
int reps = sc.nextInt();
int weight = sc.nextInt();
// create the workout with the data
d.addWorkout( name, reps, weight, LocalDate.now().toEpochDay());
List<Workout> workouts = d.allWorkouts();
// print workouts
}

How to Choose more than one item in method in java

I have just created a senario that looping which was I have to choose columns what I have selected from data base like this javaMain which have the senario
package myrestorderproject;
import enitities.Menu;
import enitities.Tables;
import java.awt.List;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* #author DELL
*/
public class MyRestOrderProject {
private static Scanner input;
public static void main(String[] args) {
// TODO code application logic here
input = new Scanner(System.in);
System.out.println("*-*-*-*-*-*Welcome to MyRestaurant*-*-*-*-*-*\n");
System.out.println("Please Choose Table From Tables List");
Tables t = new Tables();
t.getAllRows();
ArrayList<String> listItem = new ArrayList<String>();
boolean orderNotFinished = true;
while (orderNotFinished) {
System.out.print("Enter Table Number: ");
String tableNumber = input.nextLine();
boolean insertedTableNumber = db.goTodataBase.checkTableNumber(tableNumber);
if (insertedTableNumber) {
System.out.println("You Choose Table Number: " + tableNumber);
Menu m = new Menu();
m.getAllRows();
while (orderNotFinished) {
System.out.println("Please Choose Item From Menu List");
input = new Scanner(System.in);
String itemChosen = input.nextLine();
boolean insertedMenuItemId = db.goTodataBase.checkMenuItemInDB(itemChosen);
if (insertedMenuItemId) {
System.out.println("You Choose Item ID: " + itemChosen);
listItem.add(m.getAllRows(itemChosen));
System.out.print("Do you need to add more Items ? ");
String hasFinished = input.nextLine();
orderNotFinished = hasFinished.equals("yes");
} else {
System.out.println("Item Chosen doen't exist");
}
}
} else {
System.out.println("Table number does not exist");
}
}
}
}
I need now in the part which print "Please Choose Item From Menu List" after I choose the right Item Close the while loop,and I need also to choose more than one item that if I choose Items from menu give me the items was chosen with details getting from menu table
Like If I Choose Item ID 1 +Item ID 2 + Item ID 3 says that you have chosen
Item 1 Vegetable Pakora 20.00 veg Starters
Item 1 Vegetable Pakora 20.00 veg Starters
Item 1 Chicken Tikka 20.00 Non-veg Starters
after that exit the while loop
as every column have an ID, name, price, type and Category
and this method that am using in previous senario
public static boolean checkMenuItemInDB(String menuId) {
try {
setConnection();
Statement stmt = con.createStatement();
String strCheck = "select * from menu where "
+ "Menu_Id=" + menuId;
stmt.executeQuery(strCheck);
while (stmt.getResultSet().next()) {
return true;
}
} catch (Exception e) {
}
return false;
}
this is menu Class
package enitities;
import javax.swing.JTable;
/**
*
* #author DELL
*/
public class Menu {
private int Menu_Id;
private String Name;
private float Price;
private String Type;
private String Category;
public int getMenu_Id() {
return Menu_Id;
}
public void setMenu_Id(int Menu_Id) {
this.Menu_Id = Menu_Id;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public float getPrice() {
return Price;
}
public void setPrice(float Price) {
this.Price = Price;
}
public String getType() {
return Type;
}
public void setType(String Type) {
this.Type = Type;
}
public String getCategory() {
return Category;
}
public void setCategory(String Category) {
this.Category = Category;
}
public void getAllRows() {
db.goTodataBase.printData("menu");
}
public String getAllRows(String itemChosen) {
db.goTodataBase.printData("menu");
return itemChosen;
}
}
this is a method which I calls in getAllRows
public static void printData(String tableNameOrSelectStatement) {
try {
setConnection();
Statement stmt = con.createStatement();
ResultSet rs;
String strSelectPart = tableNameOrSelectStatement.substring(0, 4).toLowerCase();
String strSelect;
if ("select ".equals(strSelectPart)) {
strSelect = tableNameOrSelectStatement;
} else {
strSelect = "select * from " + tableNameOrSelectStatement;
}
rs = stmt.executeQuery(strSelect);
ResultSetMetaData rsmd = rs.getMetaData();
int c = rsmd.getColumnCount();
while (rs.next()) {
for (int i = 1; i <= c; i++) {
if (i > 1) {
System.out.print(", ");
}
String columnValue = rs.getString(i);
// System.out.print(columnValue + " " + rsmd.getColumnName(i));
System.out.print(columnValue + " ");
}
System.out.println("");
}
} catch (Exception e) {
Tools.msgBox(e.getMessage());
}
}
About the loop :
Programmer tips : You need to avoid as much as possible while(true)-loop.
In your case you could use a system of flag, it will look like :
boolean customerHasFinished = false;
while(!customerHasFinished){
...
//Do your stuff
...
System.out.print("Have you finished ? ");
String hasFinished = input.nextLine();
customerHasFinished = hasFinished.equals("yes");
}
About multiple items :
The best way to store multiple items is to use collection.
In your case, you will probably need to create a Java class that represent an Item. Having fields like name, cost, etc. And then create a collection of Item.
An example with an ArrayList :
List<Item> listItem = new ArrayList<Item>();
boolean orderNotFinished = true;
while (orderNotFinished) {
System.out.println("Please Choose an Item From Menu List");
input = new Scanner(System.in);
String itemChosen = input.nextLine();
boolean insertedMenuItemId = db.goTodataBase.checkMenuItemInDB(itemChosen);
if (insertedMenuItemId) {
System.out.println("You Choose Item ID: " + itemChosen);
listItem.add(Item.getItemByName(itemChosen)); //Add the chosen item to the list
System.out.print("You want something else ? ");
String hasFinished = input.nextLine();
orderNotFinished = hasFinished.equals("yes");
}else {
System.out.println("Item Chosen doen't exist");
}
}

Making a class-array dynamic in Java

I've created a Java class called 'Book'. Using this class I'm willing to update information about a new object 'book1'. I'm also wanting to add Author information into the object 'book1'. So, I've dynamically allocated memory using a class-array called 'Author[ ]'. By this I mean there's a separate code in which I've created a class called 'Author' with its own set of instance variables. I'm not getting into that now. However, when I'm testing the class 'Book' using another class called 'TestBook' there's no compilation error BUT I'm getting the following message in the console window when I'm running the code:
Exception in thread "main" java.lang.NullPointerException
at Book.addAuthors(Book.java:34)
at TestBook.main(TestBook.java:12)
The code for 'Book' is shown below:
public class Book {
private String name;
private Author[] A = new Author[];
private int numAuthors = 0;
private double price;
private int qtyInStock;
public Book(String n, Author[] authors, double p) {
name = n;
A = authors;
price = p;
}
public Book(String n, Author[] authors, double p, int qIS) {
name = n;
A = authors;
price = p;
qtyInStock = qIS;
}
public Book(String n, double p, int qIS) {
name = n;
price = p;
qtyInStock = qIS;
}
public String getName() {
return name;
}
/*
public Author getAuthors() {
return A;
}
*/
public void addAuthors(Author newAuthor) {
A[numAuthors] = newAuthor; // THIS LINE IS WHERE THE ERROR POINTS TO
++numAuthors;
}
public void printAuthors() {
/*
for (int i = 0; i < A.length; i++) {
System.out.println(A[i]);
}
*/
for (int i = 0; i < numAuthors; i++) {
System.out.println(A[i]);
}
}
public void setPrice(double p) {
price = p;
}
public double getPrice() {
return price;
}
public void setqtyInStock(int qIS) {
qtyInStock = qIS;
}
public int getqtyInStock() {
return qtyInStock;
}
/*
public String getAuthorName() {
return A.getName();
}
public String getAuthorEmail() {
return A.getEmail();
}
public char getAuthorGender() {
return A.getGender();
}
*/
public String toString() {
/*
return getName() + " " + getAuthor() + " Book price: " + getPrice() +
" Qty left in stock: " + getqtyInStock();
*/
//return getName() + " is written by " + A.length + " authors.";
return getName() + " is written by " + numAuthors + " authors.";
}
}
The code for 'TestBook' is shown below:
public class TestBook {
public static void main(String args[]) {
//Author[] authors = new Author[2];
//authors[0] = new Author("Tapasvi Dumdam Thapashki", "tapasvi#thapashki.com", 'M');
//authors[1] = new Author("Paul Rand", "paulie#aol.com", 'M');
Book book1 = new Book("The Quickie Man", 69.00, 5);
//System.out.println(book1.toString());
//book1.setqtyInStock(5);
//System.out.println(book1.toString());
//System.out.println(book1.getAuthorName() + " " + book1.getAuthorEmail());
//book1.printAuthors();
book1.addAuthors(new Author("Linda Lee", "lindalee#grinchtown.com", 'F'));
book1.addAuthors(new Author("Joseph Caputo", "caputo#lfp.com", 'M'));
System.out.println(book1.toString());
book1.printAuthors();
}
}
The code for 'Author' is shown below:
public class Author {
private String name;
private String email;
private char gender;
public Author(String n, String e, char g) {
name = n;
email = e;
gender = g;
}
public String getName() {
return name;
}
public void setEmail(String e) {
email = e;
}
public String getEmail() {
return email;
}
public char getGender() {
return gender;
}
public String toString() {
return getName() + " [" + getGender() + "] " + getEmail();
}
}
I'd like some help with this.
Initialize Author array with proper size like private Author[] A = new Author[4];
You forgot to specify the size of the Array.
private Author[] A = new Author[15];
For making a dynamic array you can use ArrayList.
private ArrayList<Author> list = new ArrayList<Author>();
addAuthors()
public void addAuthors(Author newAuthor) {
list.add(newAuthor);
}
printAuthors()
public void printAuthors() {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}

How do I fix "cannot find symbol" error?

i get three error message on my BookTest class and it says cannot find symbol on getCode(), getCategory, and calculateTax. how do i fix this? im trying to print these out in a dialog box but these three are the only ones not working.
import javax.swing. JOptionPane;
public class BookTest
{
public static void main(String args[])
{
double charge;
double grandTotal= 0;
String dataArray[][] = {{"NonFiction", "Abraham Lincoln Vampire Hunter","Grahame-Smith","978-0446563079","13.99","Haper","NY","US","Political"},
{"NonFiction", "Frankenstein","Shelley","978-0486282114","7.99","Pearson", "TX","England", "Historical"},
{"Fiction", "Dracula","Stoker","978-0486411095","5.99","Double Day", "CA","4918362"},
{"NonFiction", "Curse of the Wolfman"," Hageman","B00381AKHG","10.59","Harper", "NY","Transylvania","Historical"},
{"Fiction", "The Mummy","Rice","978-0345369949","7.99","Nelson","GA","3879158"}};
Book bookArray[] = new Book[dataArray.length];
int quantityArray[] = {12, 3, 7, 23, 5};
for (int i = 0; i < dataArray.length; i++)
{
if (dataArray[i][0] == "NonFiction")
{
bookArray[i] = new NonFictionBook(dataArray[i][1], dataArray[i][2], dataArray[i][3], Double.parseDouble(dataArray[i][4]),
new Publisher(dataArray[i][5], dataArray[i][6]), dataArray[i][7], dataArray[i][8]);
}
else
{
bookArray[i] = new FictionBook(dataArray[i][1], dataArray[i][2], dataArray[i][3], Double.parseDouble(dataArray[i][4]),
new Publisher(dataArray[i][5], dataArray[i][6]), Integer.parseInt(dataArray[i][7]));
}
}
String msg = "";
for (int i = 0; i < bookArray.length; i++)
{
charge = bookArray[i].calculateTotal(quantityArray[i]);
grandTotal = charge + grandTotal;
msg += String.format("%s %s %d $%.2f $%.2f\n", bookArray[i].getTitle(), bookArray[i].getCategory(), bookArray[i].getCode(), bookArray[i].calculateTax, charge); //this is where i get the 3 error messages. im trying to print all in one dialog box the title, category of the book, charge and tax for each book.
}
msg += String.format("Grand Total $%.2f ", grandTotal);
JOptionPane.showMessageDialog(null, msg);
}
}
**************************************************************
public abstract class Book implements Tax
{
private String title;
private String author;
private String isbn;
private Double price;
private Publisher publisher;
public Book()
{
setTitle("");
setAuthor("");
setIsbn("");
setPrice(0.0);
setPublisher(new Publisher());
}
public Book(String t, String a, String i, double p, Publisher n)
{
setTitle(t);
setAuthor(a);
setIsbn(i);
setPrice(p);
setPublisher(n);
}
public void setTitle(String t)
{
title = t;
}
public String getTitle()
{
return title;
}
public void setAuthor(String a)
{
author = a;
}
public String getAuthor()
{
return author;
}
public void setIsbn(String i)
{
isbn = i;
}
public String getIsbn()
{
return isbn;
}
public void setPrice(double p)
{
price = p;
}
public double getPrice()
{
return price;
}
public void setPublisher(Publisher n)
{
publisher = n;
}
public Publisher getPublisher()
{
return publisher;
}
public abstract double calculateTotal(int quantity);
public double calculateTax(double a)
{
return a * .08;
}
public String toString()
{
return( " Title " + title + " Author " + author + " Isbn " + isbn
+ " Price " + price + " Publisher " + publisher.toString());
}
}
********************************************************
public class NonFictionBook extends Book
{
private String country;
private String category;
public NonFictionBook()
{
super();
setCountry("");
setCategory("");
}
public NonFictionBook(String t, String a, String i, double p, Publisher n, String c, String ca)
{
super(t,a,i,p,n);
setCountry(c);
setCategory(ca);
}
public void setCountry(String c)
{
country = c;
}
public void setCategory(String ca)
{
category = ca;
}
public String getCountry()
{
return country;
}
public String getCategory()
{
return category;
}
public String toStirng()
{
return( super.toString() + "Country " + country + " Category " + category);
}
public double calculateTotal(int quantity)
{
double charge =0;
charge = (quantity * getPrice());
if( country != "US" )
charge += 50;
return charge;
}
}
*********************************************
public class FictionBook extends Book
{
private int code;
public FictionBook()
{
super();
setCode(0);
}
public FictionBook(String t, String a, String i, double p, Publisher n, int c)
{
super(t,a,i,p,n);
setCode(c);
}
public void setCode(int c)
{
code = c;
}
public int getCode()
{
return code;
}
public String toString()
{
return (super.toString() + " Code " + code);
}
public double calculateTotal(int quantity)
{
double charge =0;
charge = (quantity * getPrice());
if (quantity > 5)
charge += 5 * (quantity - 5);
return charge;
}
}
The tree methods are implemented in subclasses of Books. So you have to cast the value to the subclass.
if (bookArray[i] instanceof FictionBook){
FictionBook fb = (FictionBook)bookArray[i];
msg += String.format("%s %s %d $%.2f $%.2f\n", fb.getTitle(), "", fb.getCode(), 0, charge);
}
if (bookArray[i] instanceof NonFictionBook){
NonFictionBook fb = (NonFictionBook)bookArray[i];
msg += String.format("%s %s %d $%.2f $%.2f\n", nfb.getTitle(), nfb.getCategory(), nfb.getCode(), nfb.calculateTax, charge);
}
and so on
Also you have to use equals() for comparing string. Not ==
In the line you get error you try to print fields that are not instances of the Book class but of its subclasses.
You got an array of Books, you iterate on them and try to print the information. But not all the Books have getCode() method (only the fiction books) and only the non fiction books have getCategory() method. So you can't do this for ALL books.
You can change your print depending on the book type or you can make a method in Book class and each subclass can override it that prints the information you have for this class (like the toString method). Then use that in the main class.
And also as pointed in comments test if strings are equal with equals operator and not == or !=
Your array uses the type book:
Book bookArray[] = new Book[dataArray.length];
Later, you add sub-classes into this array, like NonFictionBook. Since code, category etc. are only part of the sub-classes, you cannot access them using the Book array reference.
// won't work because class Book does not have these methods, properties
bookArray[i].getCategory(), bookArray[i].getCode(), bookArray[i].calculateTax
You need to cast the object (based on what type is in the array).

Java Keyboard.readInput() error

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.

Categories