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.
Related
First, sorry if title is misleading or unclear, I'm new to Java and I couldn't find the correct way to describe it.
Below is a piece of my code, I have 3 classes, housing, management, and mainTest.
housing.java
public class housing {
private String occupantsName;
private double price;
public housing() {
occupantsName = "Noone";
price = 100.00;
}
public housing(String name, double pricing){
occupantsName = name;
price = pricing;
}
public void setName(String name){
occupantsName = name;
}
public void setPrice(double pricing){
price = pricing;
}
public String getName(){
return occupantsName;
}
public double getPrice(){
return price;
}
public String toString(){
return "Room occupied by " + occupantsName + " is priced at " + price;
}
}
management.java
public class management {
private housing[] house;
private int c;
public management(){
house = new housing[7];
c = 7;
}
public management(int noOfRoom){
if (noOfRoom>0&&noOfRoom<=10){
house = new housing[noOfRoom];
c = noOfRoom;
}
else{
house = new housing[7];
c = 7;
}
for (int i=0;i<c;i++){
house[i] = new housing();
if ((i|1)>i&&i!=0){
house[i].setPrice(150.00);
}
}
}
public String displayEven()
{
String all = "";
for (int i = 0;i<c;i++)
{
if ((i|1)>i&&i!=0)
all = all + house[i].toString() +"\n";
}
return all;
}
}
mainTest.java
import java.util.*;
public class mainTest {
public static void main(String[] args){
Scanner a = new Scanner(System.in);
management bad = new management(5);
System.out.println(bad.displayEven());
}
}
Current output when I run the program:
Room occupied by Noone is priced at 150.0
Room occupied by Noone is priced at 150.0
Is there any way to give an identifier representing the position of the data in the array index? In this case they are [2] and [4]. For example, something like:
2. Room occupied by Noone is priced at 150.0
4. Room occupied by Noone is priced at 150.0
Yes just how Guy Incognito discribed it change this
public String displayEven()
{
String all = "";
for (int i = 0;i<c;i++)
{
if ((i|1)>i&&i!=0)
all = all + house[i].toString() +"\n";
}
return all;
}
to this
public String displayEven()
{
String all = "";
for (int i = 0;i<c;i++)
{
if ((i|1)>i&&i!=0)
all = all + i + ". " + house[i].toString() +"\n";
}
return all;
}
I have been working on an assignment and i am stuck at here. Basically i have 1 class which defines all functions and members.
And another class to initialize and manipulate objects.
Here is my first class code.
public class cyryxStudent_association {
String studentID, studentName, studentCourse_level, studentTitle;
int course_completed_year;
static double registration_fee;
double activity_fee;
double total_amt;
//Default constructor
cyryxStudent_association ()
{
studentID = "Null";
studentName = "Null";
studentCourse_level = "Null";
studentTitle = "Null";
course_completed_year = 0;
}
//Parameterized Constructor
cyryxStudent_association (String id, String name, String course_level, String title, int ccy)
{
this.studentID = id;
this.studentName = name;
this.studentCourse_level = course_level;
this.studentTitle = title;
this.course_completed_year = ccy;
}
//Getters
public String getStudentID ()
{
return studentID;
}
public String getStudentName ()
{
return studentName;
}
public String getStudentCourse_level ()
{
return studentCourse_level;
}
public String getStudentTitle ()
{
return studentTitle;
}
public int getCourse_completed_year ()
{
return course_completed_year;
}
public double getRegistration_fee ()
{
return registration_fee;
}
public double getActivity_fee ()
{
return findActivity_fee(registration_fee);
}
public double getTotal_amt ()
{
return total_amt(registration_fee, activity_fee);
}
//Setters
public void setStudentID (String id)
{
studentID = id;
}
public void setStudentName (String name)
{
studentName = name;
}
public void setStudentCourse_level (String course_level)
{
studentCourse_level = course_level;
}
public void setStudentTitle (String title)
{
studentTitle = title;
}
public void setCourse_completed_year (int ccy)
{
course_completed_year = ccy;
}
//Find registration fee method
public static double findRegistration_fee (String course_level)
{
if (course_level.equalsIgnoreCase("Certificate"))
{
registration_fee = 75;
}
else if (course_level.equalsIgnoreCase("Diploma"))
{
registration_fee = 100;
}
else if (course_level.equalsIgnoreCase("Degree"))
{
registration_fee = 150;
}
else if (course_level.equalsIgnoreCase("Master"))
{
registration_fee = 200;
}
return registration_fee;
}
//Find activity method
public static double findActivity_fee (double registration_fee)
{
return registration_fee * 0.25;
}
//Find total amount
public static double total_amt (double registration_fee, double activity_fee)
{
return registration_fee + activity_fee;
}
//To string method
public String toString ()
{
return "ID: "+getStudentID()+"\nName: "+getStudentName()+"\nCourse Level:
"+getStudentCourse_level()+"\nTitle: "+getStudentTitle()+"\nCourse Completed Year:
"+getCourse_completed_year()+"\nRegistration Fee: "+getRegistration_fee()+"\nActivity Fee:
"+getActivity_fee()+"\nTotal Amount: "+getTotal_amt ();
}
}
And here is my second class code.
import java.util.Scanner;
public class test_cyryxStudent_association {
public static void main (String[] args)
{
Scanner sc = new Scanner (System.in);
int num, i;
System.out.println("Welcome!");
System.out.println("\nEnter the number of students: ");
num = sc.nextInt();
sc.nextLine();
cyryxStudent_association Std[] = new cyryxStudent_association[num];
for (i = 0; i < Std.length; i++)
{
System.out.println("\nEnter ID: ");
Std[i].setStudentID(sc.nextLine());
System.out.println("Enter Name: ");
Std[i].setStudentName(sc.nextLine());
System.out.println("Enter Course Level [Certificate, Diploma, Degree, Master]: ");
Std[i].setStudentCourse_level(sc.nextLine());
System.out.println("Enter Title: ");
Std[i].setStudentTitle(sc.nextLine());
Std[i].getRegistration_fee();
Std[i].getActivity_fee();
Std[i].getTotal_amt();
}
for (i = 0; i < Std.length; i++)
{
System.out.println("\nStudent " + i + 1 + " Information");
System.out.println("===================================");
Std[i].toString();
}
sc.close();
}
}
I get an error when values in the for loop. Can someone help me? I'm pretty new to programming and studying java for 2 months now. What am i doing wrong?
Here is my objectives.
Create an array of objects and get user input for number of objects to be manipulated.
Read and display array of object values.
Thank you!
You have to initialize the objects of your array.
After the line:
cyryxStudent_association Std[] = new cyryxStudent_association[num];
do a for loop like:
for(i = 0; i<std.length; i++){
std[i] = new cyryxStudent_association();
}
I'm not sure y this coding is not receiving the input for the adjust variable and gets terminated before it runs completely
public class Question {
int id;
String name;
String type;
double amt;
public Question(int id, String name, String type, double amt) {
this.id = id;
this.name = name;
this.type = type;
this.amt = amt;
}
public static void main(String[] args)
{ }
}
import java.util.*;
public class Answer {
public static void gettype(Question[] q,String adjust)
{
for(int i=0;i<2;i++)
{
if(q[i].getType()==adjust)
{
System.out.println(q[i].getId());
}
}}
public static void main(String[] args) {
int id;
String name,type,adjust;
double amt;
Scanner s=new Scanner(System.in);
Answer a=new Answer();
System.out.println("enter 2 car inputs");
Question[] q=new Question[2];
for(int i=0;i<2;i++)
{
id=s.nextInt();
s.nextLine();
name=s.nextLine();
type=s.nextLine();
amt=s.nextDouble();
q[i]= new Question(id,name,type,amt);
}
adjust=s.nextLine();
a.gettype(q,adjust);
}
}
While running the code i am able to get the inputs for the car object array.But after that i am not able to get the values for the variable adjust.
So please need help with this one.
I have tried simply to print the objects at the constructor side.
But not able to receive the 9th input which will be assigned to the var adjust
I think this is better. You should understand why mine works.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Question {
private int id;
private String name;
private String type;
private double amt;
Question(int id, String name, String type, double amt) {
this.id = id;
this.name = name;
this.type = type;
this.amt = amt;
}
int getId() {
return id;
}
String getName() {
return name;
}
String getType() {
return type;
}
double getAmt() {
return amt;
}
#Override
public String toString() {
final StringBuffer sb = new StringBuffer("Question{");
sb.append("id=").append(id);
sb.append(", name='").append(name).append('\'');
sb.append(", type='").append(type).append('\'');
sb.append(", amt=").append(amt);
sb.append('}');
return sb.toString();
}
}
class Answer {
public static final int NUM_QUESTIONS = 2;
public static void main(String[] args) {
int numQuestions = (args.length > 0) ? Integer.valueOf(args[0]) : NUM_QUESTIONS;
List<Question> questions = new ArrayList<>();
Scanner s = new Scanner(System.in);
for (int i = 0; i < numQuestions; ++i) {
System.out.println(String.format("Question %d", i));
System.out.print("id: ");
int id = s.nextInt();
System.out.print("name: ");
String name = s.next();
System.out.print("type: ");
String type = s.next();
System.out.print("amt: ");
double amt = s.nextDouble();
questions.add(new Question(id, name, type, amt));
}
System.out.println(questions);
}
}
Hello I am having a problem with printing an ArrayList of objects. I would like to import the values from a CSV file (this works) and then save the values into an object I created (StudentInfo) and then I would like to iterate through and print out each objects information.
I have researched and was unable to solve this, I changed a few things in my code and I am able to get one object to print as expected and that seems to be the last object stored into the ArrayList.
I have traced my code (using debugger in Eclipse) and found it is only entering the while loop one time, and I cant understand why.
I believe the problem is within my printResults() method although I cant figure out why it is only going into the while loop one time (and as I said earlier seems to be only the last index of the ArrayList).
Please see the below blocks of code. Thank you for taking the time to review this and thank you for any assistance you may be able to provide. This is homework so we were told to use tokenizer (although the professor said there are better ways that we will learn in the future).
package excercise12Dot1;
public class StudentInfo {
private String type;
private String fName;
private String lName;
private double testOne;
private double testTwo;
private double testThree;
private double finalGrade;
public StudentInfo() {
this.type = "";
this.fName = "";
this.lName = "";
this.testOne = 0;
this.testTwo = 0;
this.testThree = 0;
this.finalGrade = 0;
}
public StudentInfo(String type, String fname, String lName, double testOne, double testTwo, double testThree, double finalGrade){
this.type = type;
this.fName = fname;
this.lName = lName;
this.testOne = testOne;
this.testTwo = testTwo;
this.testThree = testThree;
this.finalGrade = finalGrade;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public double getTestOne() {
return testOne;
}
public void setTestOne(double testOne) {
this.testOne = testOne;
}
public double getTestTwo() {
return testTwo;
}
public void setTestTwo(double testTwo) {
this.testTwo = testTwo;
}
public double getTestThree() {
return testThree;
}
public void setTestThree(double testThree) {
this.testThree = testThree;
}
public double getFinalGrade() {
return finalGrade;
}
public void setFinalGrade(double finalGrade) {
this.finalGrade = finalGrade;
}
}
package excercise12Dot1;
import java.io.File;
import java.util.StringTokenizer;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
public class NonCreditCourseGrades {
private Scanner csvReader;
private int counter = 0;
private ArrayList<StudentInfo> finalStudentGradesArray;
public void openFile(){
try{
csvReader = new Scanner(new File("StudentsScores.csv"));
while (csvReader.hasNext()){
String studentRecord = csvReader.nextLine();
StringTokenizer tokenizer = new StringTokenizer(studentRecord, ",");
String type = tokenizer.nextToken();
String fName = tokenizer.nextToken();
String lName = tokenizer.nextToken();
double testOne = Double.parseDouble(tokenizer.nextToken());
double testTwo = Double.parseDouble(tokenizer.nextToken());
double testThree = Double.parseDouble(tokenizer.nextToken());
double finalScore = 0;
StudentInfo newStudent = new StudentInfo(type, fName, lName, testOne, testTwo, testThree, finalScore);
finalStudentGradesArray = new ArrayList<StudentInfo>();
finalStudentGradesArray.add(newStudent);
++counter;
}
}catch(FileNotFoundException ex){
System.err.println("FILE NOT FOUND");
}
csvReader.close();
}
public void printResults(){
Iterator<StudentInfo> itr = finalStudentGradesArray.iterator();
while (itr.hasNext()){
StudentInfo results = (StudentInfo)itr.next();
System.out.println("Student Type:\t" + results.getType() + "\nFirst Name:\t" + results.getfName() + "\nLast Name:\t" + results.getlName() + "\nTest 1:\t\t" + results.getTestOne() + "\nTest 2:\t\t" + results.getTestTwo() + "\nTest 3:\t\t" + results.getTestThree() + "\nFinal Score: \t" + results.getFinalGrade() + "\n\n");
}
}
package excercise12Dot1;
public class NonCreditCourseGradesRunner {
public static void main(String[] args) {
NonCreditCourseGrades test = new NonCreditCourseGrades();
test.openFile();
test.printResults();
}
}
You recreated the results array every iteration through the loop reading the CSV file:
finalStudentGradesArray = new ArrayList();
I was create a book inventory program.
I has two classes one is the main class, and the other one is the constructor class name Item.
On the main class, i has create a array (Item[] book = new Item[100]) to store my input.
And in my Item class, i want to create a function below
public boolean addItem(Item[] iArray, String itemCode){
boolean c = false;
for(int i=0; i<iArray.length; i++){
if(iArray[i].getItemCode().equals(itemCode)){
c = true;
}
else{
c = false;
}
}
return c;
}
how to i make that Item[] iArray sync with the book array in main class?
public class Item {
private String itemCode;
private String description;
private int quantity;
private double costprice;
private double sellprice;
private String status = "Available";
private boolean check;
private double discount;
public Item(){
this("A000","default",0,0.00,0.00,0.25,"Available");
}
//construtor with parameter
public Item(String itemCode, String description, int quantity, double costprice, double sellprice, double discount, String status){
this.setItemCode(itemCode);
this.setDescription(description);
this.setQuantity(quantity);
this.setCostprice(costprice);
this.setSellprice(sellprice);
this.setStatus(status);
this.setDiscount(discount);
}
//setter and getter methods
public void setItemCode(String itemCode){
this.itemCode = itemCode;
}
public String getItemCode(){
return this.itemCode;
}
public void setDescription(String description){
this.description = description;
}
public String getDescription(){
return this.description;
}
public void setQuantity(int quantity){
this.quantity = quantity;
}
public int getQuantity(){
return this.quantity;
}
public void setCostprice(double costprice){
this.costprice = costprice;
}
public double getCostprice(){
return this.costprice;
}
public void setSellprice(double sellprice){
this.sellprice = sellprice;
}
public double getSellprice(){
return this.sellprice;
}
public void setStatus(String status){
this.status = status;
}
public String getStatus(){
return this.status;
}
public void setDiscount(double discount){
this.discount = discount;
}
public double getDiscount(){
return this.discount;
}
public void setCheck(boolean check){
this.check = check;
}
public boolean getCheck(){
return this.check;
}
public boolean addItem(Item[] iArray, String itemCode){
boolean c = false;
for(int i=0; i<iArray.length; i++){
if(iArray[i].getItemCode().equals(itemCode)){
c = true;
}
else{
c = false;
numberofobject++;
}
}
return c;
}
public void displaymenu(){
System.out.println("Menu");
System.out.println("1. Add New Item");
System.out.println("2. Search");
System.out.println("3. Edit Details");
System.out.println("4. Edit Quantity");
System.out.println("5. Stop Sell");
System.out.println("6. List");
System.out.println("7. Exit");
}*/
public String toString(){
String msg = "";
msg = this.getItemCode()+"\t\t\t\t"+this.getDescription()+"\t\t\t\t"+this.getQuantity()+"\t\t\t\t"+this.getCostprice()+"\t\t\t\t"+this.getSellprice()+"\t\t\t\t"+this.getDiscount()+"\t\t\t\t"+this.getStatus();
return msg;
}
this is my Item class.
import java.util.*;
public class Driver {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int choice,quantity,NOI=0;
double cprice,sprice,discount;
String itc,name,status = "Available";
boolean check = true;
Item[] book = new Item[100];
Scanner s1 = new Scanner(System.in);
do{
Item display = new Item();
display.displaymenu();
System.out.print("Please Select Menu: ");
choice = s1.nextInt();
if(choice==1){
do{
System.out.print("Please Enter the Item Code: ");
itc = s1.next();
//for(int i=0; i<book.length; i++){
//book[i].addItem(book, itc);
if(display.addItem(book, itc)==true){
System.out.println("the book item code already exist."+NOI);
check = false;
}
else
{
check = true;
} //This is the question where i faced.
//}
}while(check==false);
System.out.print("Please Enter the Description: ");
name = s1.next();
System.out.print("Please Enter the Quantity: ");
quantity = s1.nextInt();
System.out.print("Please Enter the Cost Price: ");
cprice = s1.nextDouble();
System.out.print("Please Enter the Sell Price: ");
sprice = s1.nextDouble();
System.out.print("Please Enter the Discount: ");
discount = s1.nextDouble();*/
book[NOI] = new Item(itc,name,quantity,cprice,sprice,discount,status);
NOI++;
}
when i add the second item, there was a error (Exception in thread "main" java.lang.NullPointerException),
how to solve it?
Your method does not do what you want, because even if you find the item code, the loop continues. You probably want something like this instead:
public boolean addItem(Item[] iArray, String itemCode){
for (Item item : iArray) {
if (item.getItemCode().equals(itemCode)) {
return true;
}
}
return false;
}
Note that the method you posted seems oddly named, because it does not add anything anywhere.
You might also consider using a List<Item> (ArrayList, etc.) instead of an Item[].
I am not sure I understand what you are looking for so if my answer is irrelevant just comment it and I will delete.
I assume you are trying to store information : add new item with its code to an array. But I'm not sure if you're:
trying to insure the uniqueness of your item in the array before inserting it:
maybe you can use a set of codes, it will simplify your problem, just check with .contains() and then add it or not
trying to add it to the list and if it already exist perform something (incrementation of the number of book for the code?)
maybe you can use a HashMap with code as key and book as item.
In your current state, your method addItem does not add anything, just return if your last book in the array matches your code...