Items not getting add into array - java

I have 3 classes for this program. I want to print out the total price of the items after shopping, but there is a problem with the output. Though each time shopping are different in the number of items, the output are all the same. Could you please help me to fix it?
Here are my code:
This is the first class:
public class LineItem {
private String name;
private int quantity;
private double pricePerUnit;
/**
*
*/
public LineItem(String name, int quantity, double pricePerUnit) {
this.name = name;
this.quantity = quantity;
this.pricePerUnit = pricePerUnit;
}
public double getCost() {
return quantity*pricePerUnit;
}
public void setQuantity(int newQuantity) {
quantity=newQuantity;
}
}
This is the second class:
import java.util.ArrayList;
public class ShoppingCart {
/**
*
*/
private LineItem[] item;
private int check;
public ShoppingCart() {
item = new LineItem[10];
check = 10;
}
public void add(LineItem newItem) {
int i = 0;
while (item[i] == null && check != 0){
item[i] = newItem;
i++;
check -= check;
}
}
public double getTotalCost() {
double totalCost = 0.0;
for(int i=0; i< item.length;i++){
if(item[i]!=null)
totalCost += item[i].getCost();
}
return totalCost;
}
}
This is the third class:
public class ShoppingCartTester{
public static void main(String[] args){
ShoppingCart singleItemCart = new ShoppingCart();
LineItem item1 = new LineItem("Dove shampoo",1,4.52);
singleItemCart.add(item1);
System.out.println(singleItemCart.getTotalCost());
//
ShoppingCart typicalCart = new ShoppingCart();
item1 = new LineItem("Dove shampoo",1,4.52);
typicalCart.add(item1);
LineItem item2 = new LineItem("apples",5,10.80);
typicalCart.add(item2);
LineItem item3 = new LineItem("avocados",5,20);
typicalCart.add(item3);
LineItem item4 = new LineItem("chocolate",1,4.25);
typicalCart.add(item4);
LineItem item5 = new LineItem("green onions",3,3.49);
typicalCart.add(item5);
System.out.printf("%.2f", typicalCart.getTotalCost());
System.out.println();
}
}
I think the problem is in the add method, but i have no idea how to fix it.
Thank you in advance

I suggest to maintain a global variable with current item in cart (noOfItems),
So that while adding you can directly add new item
So instead of
public void add(LineItem newItem) {
int i = 0;
while (item[i] == null && check != 0){
item[i] = newItem;
i++;
check -= check;
}
}
use
public void add(LineItem newItem){
item[++noOfItems] = newItem;
}
or second way
its better to create ArrayList instead of array of object

Problem is in your Add method:
public void add(LineItem newItem) {
int i = 0; <--- Problem begins
while (item[i] == null && check != 0){
item[i] = newItem;
i++;
check -= check;
}
}
Everytime you are calling add i is getting reset to 0.
Fix1:: To have a list instead of array. Array comes with a fix size which you might want to avoid.

Related

How do I take an array of objects and update the object data file after changing variables in the array?

I have an array of objects and I am trying to change the values of the objects and then re-update the storage file where the object-in-file are stored. When I try changing the storage file it either clears the file or does nothing. Here is my code..
public class InventoryManager implements Serializable{
String name;
String code;
double price;
int inventory;
String expireDate;
boolean frozen;
String type;
int shoeSize;
double screenSize;
boolean medical;
Object myObject;
Controller l;
FileOutputStream storage = new FileOutputStream("Storage.dat");
ObjectOutputStream out = new ObjectOutputStream(storage);
Pharmacy ph;
TVS tv;
Shoes shoe;
Fruit fruit;
Scanner input = new Scanner(new File("inp.dat"));
public InventoryManager(Object x) throws IOException{
myObject = x;
if(x instanceof Item){
name = ((Item) x).getName();
code = ((Item) x).getCode();
price = ((Item) x).getPrice();
inventory = ((Item) x).getInventory();
}
out.writeObject(x);
out.close();
}
public class Controller implements ActionListener {
GUI myGui;
InventoryManager[] myManager;
JButton myButton;
int quantity;
String nameofproduct = "";
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getSource() instanceof JButton){
myButton = (JButton) arg0.getSource();
String x = myButton.getText();
for(int i = 0; i<myManager.length; i++){
if(x.equals(myManager[i].name)){
nameofproduct = myManager[i].name;
}
}
if(x.equals("Purchase")){
try{
quantity = Integer.parseInt(myGui.qtnInput.getText());
if(nameofproduct == ""){
JOptionPane.showMessageDialog(null, "Select a Product");
}
else{
for(int i = 0; i<myManager.length; i++){
if(nameofproduct.equals(myManager[i].name)){
myManager[i].inventory = myManager[i].inventory - quantity;
myGui.qtnLeft.setText("Quantity: "+myManager[i].inventory);
myGui.CartInv.setText(myGui.CartInv.getText() + myManager[i].name + " " + quantity+"\n");
myGui.description.setText(myManager[i].toString());
}
}
}
}
catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "That is not a number");
myGui.qtnInput.setText("");
}
}
for(int i = 0; i<myManager.length; i++){
if(x.equals(myManager[i].name)){
myGui.qtnLeft.setText("Quantity: "+myManager[i].inventory);
myGui.description.setText(myManager[i].toString());
}
}
}
}
}
public void getIM(InventoryManager[] myManager){
this.myManager = myManager;
}
}
imaging bytes in a file as LegoTM blocks on a base plate each close to each other.
If you want to change some blocks in the middle you have to move all the blocks after the changed position and move them backwards by the number of bytes the changed content part is longer than the old one.
Almost the same is true for the byte on your hard disk.
This means the easiest way is to overwrite the whole file in the first place.

Hello! I'm having trouble printing (Java)

The program is meant to modify the List items (defined at top), and there appears to be trouble printing the modified version to console.
Could I get some tips as to where (and perhaps what, for efficiency) to modify?
import java.util.*;
public class Quiz4 {
public static class ItemHolder{
private List<Integer> items = new ArrayList<>();
public List<Integer> getItems(){
return items;
}
public void addItems(Integer item){
items.add(item);
}
public int size(){
return items.size();
}
public String toString(){
return items.toString();
}
public void remove(Object obj) {
items.remove(obj);
}
public boolean equals(int a, int b){
boolean ret = false;
if (a == b){
ret = true;
}
return ret;
}
public int get(int index){
return items.get(index);
}
}
public static ItemHolder modify(ItemHolder items){
for (int i = 0; i < items.size(); ){
if(items.get(i) == (items.get(i+1))){
items.remove(items.get(i));
}
}
return items;
}
public static void main(String[] args){
ItemHolder items = new ItemHolder();
Scanner up = new Scanner(System.in);
items.getItems();
for (int i = 0; i < 6; i++){
System.out.println("Please enter number. -1 to quit");
String input = up.nextLine();
int check = Integer.parseInt(input);
if (check >= 0){
items.addItems(check);
}
else{
continue;
}
}
modify(items);
System.out.println(items);
up.close();
}
}
Thank you!
Modify your Modify method it will work
for (int i = 0; i < items.size()-1;i++ ){
if(items.get(i) == (items.get(i+1))){
items.remove(items.get(i));
}

How can I add a string to an array?

I've been trying to figure out how add a string to an array.
I have a class which represents a list and I want to add "cup" to the list by calling addTo.
I've tried this, but it fills the entire array and then when the method is called again it overwrites the entire array:
private String[] option;
private int position;
public Menu()
{
option = new String[0];
position = 0;
}
public void addTo(java.lang.String option)
{
option = new String[20];
++position;
option[position] = option;
}
Hope this is better.
This line
option = new String[20];
is clearing your list.
You should initilize your list only in a constructor, for example.
Your Menu class can be something like:
public class Menu{
private final int LIMIT = 20;
private String[] option;
private int position;
public Menu()
{
option = new String[LIMIT];
position = 0;
}
public void addTo(String item)
{
if(position == LIMIT)
{
// We do not want a IndexOutOfBoundsException here
return;
}
option[position++] = item;
}
public void printList(){
for(int i = 0; i< LIMIT; i++)
{
System.out.println( i + ": " + option[i] );
}
}
public static void main(String[] args)
{
Menu m = new Menu();
m.addTo("book");
m.addTo("cup");
m.addTo("test");
m.printList();
}
}
Tested and working!
Best regards,
Miguel

java.lang.NullPointerException when object is instantiated?

So I'm fairly certain that this code should work, but when I run it it spits out that.
Problem occurs at:
return planetArray[arr[0].viewPosition()].testCost();
My code is posted below. I've scoured over this but cannot see how it's null?
The purpose is to take the currentPosition of the Player[x] and use it to check the cost of the planet Player[x] is on and return the cost.
Sorry if I posted too much / not enough code, wasn't sure where the error was.
public class Launcher
{
private static Planet returnCost;
private static Planet myTest;
private static PlanetInfo myPlanetInfo;
private static PlanetInfo[] planetArray;
private static Player[] arr; //NEED THIS FOR arr = myArray.getPlayerArray(); to work..
public static void main(String[] args)
{
Planet myPlanetArray = new Planet();
PlayerArray myArray = new PlayerArray();
myPlanetArray.getPlanetArray();
myArray.getPlayerArray();
planetArray = myPlanetArray.getPlanetArray();
arr = myArray.getPlayerArray(); //holy moses this worked...
System.out.println("player 1's ID: " + arr[0].viewID());
System.out.println("player 1's balance: " + arr[0].viewBalance());
arr[0].playerGo();
System.out.println("You've landed on: " /* + myPlanetArray.returnName()*/ + " it costs: " + myPlanetArray.returnCost());/*arr[0].viewPosition());*/
//^^^this line causes the error
}
}
and...
public class PlanetInfo
{
Scanner scan = new Scanner(System.in);
private static PlanetInfo[] planetArray;
private static Player[] arr;
private String name; //same with this
private int cost; // doesnt need setter or getter methods, it's permanent.
private int position; // same with this
private int group; // same with this
private int owner;
private int rent; // done
private int town;
private int city;
private int sellValue; // same with this
public void setRent()
{
System.out.println("How many towns would you like to add?");
town = scan.nextInt();
if(position != 39 && town == 1) {rent *= 5;}
else if(position == 39 && town == 1){rent = 200;}
if(town == 2) {rent *= 3;}
if(position <= 13 && town == 3) {rent *= 3;}
else if(position > 13 && town == 3) {rent *= 2.5;}
if(position < 20 && town == 4) {rent *= 1.45;}
else if((position > 20 && position < 40) && town == 4) {rent *= 1.3;}
}
public int getRent(){return rent;}
//public void setOwner(){owner = arr[0].viewID();}
//public int getOwner(){return owner;}
//^^^^Will do this in Player class.
public PlanetInfo(String planetName, int planetCost, int boardPosition, int groupColor, int currentOwner, int startRent, int numTown, int numcity)
{
cost = planetCost;
name = planetName;
position = boardPosition;
group = groupColor;
owner = currentOwner;
rent = startRent;
town = numTown;
city = numcity;
sellValue = cost/2;
}
}
finally..
import java.util.Scanner;
import java.util.Random;
public class Planet
{
private static Player[] arr;
private static PlanetInfo[] planetArray;
private String name;
private int cost;
private int playerPosition;
public void Planet()
{
//cost,boardposition,color,currentowner,startingRent,#towns,#city
Planet testPlanet = new Planet();
PlayerArray myArray = new PlayerArray();
PlanetInfo[] planetArray;
myArray.getPlayerArray();
arr = myArray.getPlayerArray();
planetArray = new PlanetInfo[40];
planetArray[1] = new PlanetInfo("Tatooine Mos Eisley",60,1,1,-1,2,0,0);
planetArray[3] = new PlanetInfo("Tatooine Mos Espa",60,3,1,0,-1,0,0);
planetArray[6] = new PlanetInfo("Dagobah",100,6,2,-1,6,0,0);
//MORE OF THIS NOT IMPORTANT SO REMOVED
planetArray[34] = new PlanetInfo("Alderaan",320,34,7,-1,28,0,0);
planetArray[37] = new PlanetInfo("Coruscant Jedi Temple",350,37,8,-1,35,0,0);
planetArray[39] = new PlanetInfo("Coruscant Senate",400,39,8,-1,50,0,0);
public int testCost()
{
return cost;
}
}
public PlanetInfo[] getPlanetArray()
{
return planetArray;
}
public String testName()
{
return name;
}
public int testCost()
{
return cost;
}
public int returnCost() //returns int of cost
{
return planetArray[arr[0].viewPosition()].testCost();
}
}
You never show what the PlanetArray class looks like. Most likely you are not instantiating the Player[] array that gets returned in the getPlanetArray() method.

I need something like a multi dimensional array but using a for loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
String[] item ={"[1]hotdog", "[2]eggpie","[3]menudo","[4]pizza","[5]lumpia"};
int[] cost = {5, 10, 15, 20, 25};
int[] selling = {10,15,20,25,30,};
int[] qty = {2,4,6,8,10};
for(int b = 0; b<5;b++) {
for(int c = 0; c<=1;c++) {
for(int d = 0; d<=1;d++) {
for(int e = 0; e<=1;e++) {
System.out.println(" " + item[b] + "\t" +
cost[c] + "\t\t" + selling[d] + "\t\t" + qty[e]);
}
}
}
}
It doesn't run how I want it to run; I want it to run like a table but using a for loop only not using an array[][].
Just use a regular for loop to iterate over all arrays at once:
String[] item ={"[1]hotdog", "[2]eggpie","[3]menudo","[4]pizza","[5]lumpia"};
int[] cost = {5, 10, 15, 20, 25};
int[] selling = {10,15,20,25,30,};
int[] qty = {2,4,6,8,10};
for (int i = 0; i < item.length; i++)
{
System.out.println(" " +item[i]+"\t"+cost[i]+"\t\t"+selling[i]+"\t\t"+qty[i]);
}
I would recommend putting all of these fields in an object, and then you can iterate over an array of that object.
Take a look at the Guava libraries Table collection.
public class Item {
private int position;
private String name;
private int selling;
private int quantity;
private int cost;
public Item()
{
position = 0;
name="";
selling = 0;
quantity =0;
cost = 0;
}
public String GetState()
{
return String.format("{0} {0} {0} {0} {0} {0}", position,name,selling,cost,quantity);
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSelling() {
return selling;
}
public void setSelling(int selling) {
this.selling = selling;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getCost() {
return cost;
}
public void setCost(int cost) {
this.cost = cost;
}
}
package test;
import java.util.ArrayList;
import java.util.List;
public class ItemTest {
public static void main(String[] args) {
Item i = new Item();
List<Item> items = new ArrayList<Item>();
items.add(i);
items.add(i);
for (Item item : items) {
System.out.println(item.GetState());
}
}
}
console out : [0] 0 0 0
[0] 0 0 0

Categories