Creating a static average price method - java

Good afternoon, I can't write a static method to calculate the average price
Implement a static method to calculate the average price of goods in all baskets. It should calculate and return the ratio of the total cost of all baskets to the total number of all items.
Implement the static method for calculating the average cost of a basket (the ratio of the total cost of all baskets to the number of baskets).
I still have not been able to create static method data
public class Basket {
private static int count = 0;
private String items = "";
private int totalPrice = 0;
private double totalWeight = 0;
private int limit;
public static int allprice = 0;
public static int allcount = 0;
public static int averagebasket = 0;
public Basket() {
increaseCount(1);
items = "Список товаров:";
this.limit = 1000000;
}
public Basket(int limit) {
this();
this.limit = limit;
}
public Basket(String items, int totalPrice) {
this();
this.items = this.items + items;
this.totalPrice = totalPrice;
}
public static int getCount() {
return count;
}
public static int getAllTovar() {
return allcount;
}
public static int getAllPrice() {
return allprice;
}
public static int getAverageBasket() {
return averagebasket;
}
public double getTotalWeight(){
return totalWeight;
}
public static void increaseCount(int count) {
Basket.count = Basket.count + count;
}
public static void increaseTovar(int count) {
Basket.allcount = Basket.allcount + count;
}
public static void increasePrice(int totalPrice) {
Basket.allprice = Basket.allprice + totalPrice;
}
public static void average() {
Basket.averagebasket = allprice / allcount;
}
public void add(String name, int price, double weight) {
add(name, price, 1, weight);
}
public void add(String name, int price, int count, double weight) {
boolean error = false;
if (contains(name)) {
error = true;
}
if (totalPrice + count * price >= limit) {
error = true;
}
if (error) {
System.out.println("Error occured :(");
return;
}
increaseTovar(1);
items = items + "\n" + name + " - " +
count + " шт. - " + price + " Вес - " + totalWeight;
totalPrice = totalPrice + count * price;
totalWeight = totalWeight + weight;
Basket.allprice += price * count;
}
public void clear() {
items = "";
totalPrice = 0;
}
public int getTotalPrice() {
return totalPrice;
}
public boolean contains(String name) {
return items.contains(name);
}
public void print(String title) {
System.out.println(title);
if (items.isEmpty()) {
System.out.println("Корзина пуста");
} else {
System.out.println(items);
}
}
}
`
`public class Main {
public static void main(String[] args) {
Basket basket = new Basket();
basket.add("Milk", 40, 305.4);
basket.print("Milk");
//System.out.println(Basket.getCount());
Basket vasya = new Basket();
basket.add("bread", 60, 555);
System.out.println(Basket.getAllTovar());
System.out.println((Basket.getAllPrice()));
System.out.println(Basket.getAverageBasket());
}
}

Something like this?
public static double getAveragePrice() {
return (double) allPrice / allCount;
}
public static double getAverageBasket() {
return (double) allPrice / basketCount;
}

Related

Sort Rows by number

there is a class hierarchy, a Table class and a Rows class, the table consists of rows, I would like to sort the rows in the array I selected by the row number, please tell me how to do this. In the handler class, I can create a table and rows, and the row has fields: row number and row content, the table has a field: table number
public class Rows {
private int number;
private String data;
private int numT;
public void setNumber(int number) { this.number = number;}
public void setData(String data) { this.data = data; }
public int getNumber() { return number; }
public String getData() { return data; }
public Rows() {
number = 0;
data = "Some input text";
}
public Rows(int number, String data, #NotNull Table table) {
this.number = number;
this.data = data;
this.numT = table.getNum();
}
public void printRows() { System.out.print(number + ": " + data + "\n"); }
#Override
public String toString() { return number + ": " + data + "\n"; }}
public class Table {
private int num;
protected ArrayList<Rows> rowsArrayList = new ArrayList<>();
public Table() { num = 0; }
public Table(int num) { this.num = num; }
public void setNum(int num) { this.num = num;}
public int getNum() { return num; }
public void printTables() {
System.out.print("Name: " + num);
}
#Override
public String toString() { return String.valueOf(num);}}
public class Handler {
ArrayList<Table> listT = new ArrayList<>();
ArrayList<Rows> listR = new ArrayList<>();
Scanner console = new Scanner(System.in);
Rows rows;
Table table;
public void printT() {
for (Table table: listT) {
System.out.print(table.toString());
System.out.print(table.rowsArrayList.toString());
}
}
public void createTable() {
int numT;
if (console.hasNextInt()) {
System.out.println("Write the number of the Table");
numT = console.nextInt();
table = new Table(numT);
listT.add(listT.size(), table);
}
else System.out.print("Please input integer value!\n");
}
public void createRows() {
int numR, numT;
String data;
System.out.println("Write the number of the rows");
if (console.hasNextInt()) {
numR = console.nextInt();
System.out.println("enter any data");
data = console.next();
System.out.println("Chose Table: ");
printT();
if (console.hasNextInt()) {
numT = console.nextInt();
rows = new Rows(numR, data, listT.get(numT - 1));
listT.get(numT - 1).rowsArrayList.add(listT.get(numT - 1).rowsArrayList.size(), rows);
}
else System.out.print("Please input integer value (number of table)!\n");
}
else System.out.print("Please input integer value (number of rows)!\n");
}
public void sortRowsByNum() {
// need to sort
}}
One way is to implement the Comparable interface
public class Rows implements Comparable {
#Override
public int compareTo(Rows rows){
return Integer.compare(this.number, rows.getNumber());
// this will give you an ASC order
//If you would like DESC order flip the comparison
}
}
And then in your sortRowsByNum method in the Table class you can do this
public void sortRowsByNum() {
Collections.sort(rowsArrayList);
}

TreeSet wont add edges

i have to code the Dijkstra algorithm. We got a blueprint for this project. Meaning we were told the classes, field variables and methods we have to use.
We have to read the adjacency matrix from a csv file and then use the Dijkstra algorithm.
My problem already begins in in filling the TreeSet edges...
The problem occurs in Graph.class on line 45 when i try to add the Edges.
Example for the csv :
;A;B;C;D;E;F;G;H
A;;1;3;1;;;;
B;1;;;;3;3;;
C;3;;;1;;;1;
D;1;;1;;1;;2;
E;;3;;1;;1;;5
F;;3;;;1;;;1
G;;;1;2;;;;1
H;;;;;5;1;1;
=>
A -> (B,1), (C,3), (D,1)
B -> (A,1), (E,3), (F,3)
C -> (A,3), (D,1), (G,1)
D -> (A,1), (C,1), (E,1), (G,2)
E -> (B,3), (D,1), (F,1), (H,5)
F -> (B,3), (E,1), (H,1)
G -> (C,1), (D,2), (H,1)
H -> (E,5), (F,1), (G,1)
Could somebody look where my problem is ? My indices are correct i checked them with some sout.
Just need help with filling in the TreeSet! I want to try the Dijkstra part myself.
public class Edge implements Comparable<Edge>{
private int distance;
private Node neighbour;
public Edge(int distance, Node neighbour) {
this.distance = distance;
this.neighbour = neighbour;
}
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
public Node getNeighbour() {
return neighbour;
}
public void setNeighbour(Node neighbour) {
this.neighbour = neighbour;
}
#Override
public int compareTo(Edge o) {
if (this.neighbour.getId().equals(o.neighbour.getId())){
return 0;
}else{
return -1;
}
}
}
import java.util.TreeSet;
public class Node {
private String id;
private TreeSet<Edge> edges;
private int distance;
private Node previous;
private boolean isVisited;
public Node(String id) {
this.id = id;
this.edges = new TreeSet<>();
}
public Node(String id, int distance){
this.id = id;
this.distance = distance;
}
#Override
public String toString() {
return "Node{" +
"id='" + id + '\'' +
", edges=" + edges +
", distance=" + distance +
", previous=" + previous +
", isVisited=" + isVisited +
'}';
}
public String getPath(){
return null;
}
public void addEdge(Edge e){
edges.add(e);
}
public void init(){
}
public void setStartNode(Node n){
}
public void visit(Node n){
}
public String getId() {
return id;
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.file.Path;
import java.util.*;
public class Graph {
private PriorityQueue pq;
private ArrayList<Node> nodes;
public Graph(){
this.pq = new PriorityQueue();
this.nodes = new ArrayList();
}
public void readGraphFromAdjacencyMatrixFile(Path file) throws FileNotFoundException {
Scanner sc = new Scanner(new File(String.valueOf(file)));
ArrayList<String> s = new ArrayList<>();
ArrayList<Character> nodesCharacter = new ArrayList<Character>();
while (sc.hasNext()){
s.add(sc.next());
}
sc.close();
for(char ch: s.get(0).toCharArray()){
if (ch != ';' && ch != ',') {
nodes.add(new Node(Character.toString(ch)));
nodesCharacter.add(ch);
}
}
ArrayList<Node> nodes2 = getNodes();
String node = "";
int index = 0;
for (int i = 1; i < s.size(); i++){
int cnt = -2;
char[] chArray = s.get(i).toCharArray();
for (int j = 0; j < chArray.length; j++){
if(j == 0){
node = String.valueOf(chArray[j]);
index = indexOfNode(String.valueOf((chArray[j])));
}
else if (j >= 2){
if (Character.isDigit(chArray[j])){
int neighbourIndex = indexOfNode("" + nodesCharacter.get(cnt));
Edge e = new Edge(Character.getNumericValue(chArray[j]), nodes.get(neighbourIndex));
nodes.get(index).addEdge(e);
cnt--;
}
}
cnt ++;
}
}
}
public String getAllPAths(){
return null;
}
public void calcWithDijkstra(String startNodeId){
}
public ArrayList<Node> getNodes() {
return nodes;
}
public int indexOfNode(String id){
int cnt = 0;
for (int i = 0; i < nodes.size(); i++){
if (id.equals(nodes.get(i).getId())){
return cnt;
}
cnt++;
}
return -1;
}
}

RPG game code error [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I keep getting this error in my code. Can someone fix it and how is the code written? Can it be improved by maybe using setters and getters only?
Exception in thread "main" java.lang.NullPointerException
at Player.attack(Player.java:72)
at Main.main(Main.java:15)
My code:
Player.java
public class Player {
String name;
String race;
int hp;
int power;
int armour;
Weapon weapon;
public Player (String n, String r, int h, int p, int a) {
name = n;
race =r;
hp = h;
power = p;
armour = a;
}
public void setName (String n) {
name = n;
}
public String getName() {
return name;
}
public void setRace (String r) {
race = r;
}
public String getRace() {
return race;
}
public void setHP (int h) {
hp = h;
}
public int getHP() {
return hp;
}
public void setPower (int p) {
power = p;
}
public int getPower() {
return power;
}
public void setArmour (int a) {
armour = a;
}
public int getArmour() {
return armour;
}
public boolean dead() {
return hp <= 0;
}
public boolean equip(Weapon weapon) {
this.weapon = weapon;
return true;
}
public boolean receiveDamage(int i) {
if ((hp - i) > 0) {
hp = hp - i;
return true;
}
hp = 0;
return false;
}
public boolean attack(Player player) {
return player.receiveDamage(weapon.useWeapon());
}
}
Main.java
public class Main {
public static void main(String args[]) {
Player Mensch = new Player("Mensch", "Mensch", 85, 12, 10);
Player Ork = new Player("Shrek", "Ork", 50, 14, 6);
Weapon MenschW = new Weapon("mächtiges Schwert", 15, 100);
Weapon OrkW = new Weapon("große Axt", 7, 100);
Mensch.equip(Mensch.weapon);
Ork.equip(Ork.weapon);
while (!Mensch.dead() && !Ork.dead() ) { //Alternativ: for (player hp >=0)
System.out.println("Mensch gegen Ork " + Mensch.attack(Ork));
if (Mensch.dead() || Ork.dead()) {
break;
}
System.out.println("Mensch gegen Ork " + Ork.attack(Mensch));
}
System.out.println("Ork ist tot: " + Ork.dead());
System.out.println("Mensch ist tot: " + Mensch.dead());
}
}
Weapon.java
import java.util.concurrent.ThreadLocalRandom;
public class Weapon {
String name;
int damage;
int hp;
public Weapon(String string, int d, int hp) {
// TODO Auto-generated constructor stub
}
public void setName (String n) {
name = n;
}
public String getName() {
return name;
}
public void setDamage (int d) {
damage = d;
}
public int getDamage() {
return damage;
}
public void setWHP (int h) {
hp = h;
}
public int getWHP() {
return hp;
}
public int useWeapon() {
if
(broken())
return 0;
hp = hp - 5;
return (damage / 2) + random();
}
private int random() {
return ThreadLocalRandom.current().nextInt(1, damage + 1);
}
private boolean broken() {
return hp <= 0;
}
}
I know its a lot of code but I keep getting the same error, also I'm quite new to java so I would appreciate some tips or suggestions to make my code better or more failsave. The code doesn't do much yet but it will (hopefully) be a simple game soon in which two characters fight eachother with some calculations on damageoutput of each player. In this case a Human and Ork. Feel free to try it out
Change
Mensch.equip(Mensch.weapon); // Mensch.weapon is not initialized in constructor so it is null.
Ork.equip(Ork.weapon); // Ork.weapon is not initialized in constructor so it is null as well.
To
// Use your newly created weapons in the main instead.
Mensch.equip(MenschW );
Ork.equip(OrkW);

wrapping around minutes into hours

I'm doing simple clock which wraps around when reaching 0 (e.g 00:59 -> 01:00, 23:59 -> 00:00). I got stuck at this moment and can't figure it out.
I have to do this in this way, using just methods given in 'BoundedCounter' class.
public class Test3 {
public static void main(String[] args) {
BoundedCounter minutes = new BoundedCounter(59, 0);
BoundedCounter hours = new BoundedCounter(23, 0);
int i = 0;
while (i < 70) { //repeats actual time 70 times - just to check if works fine
//put code here
i++;
}
}
}
.
import java.text.DecimalFormat;
public class BoundedCounter {
private int startValue;
private int upperLimit;
private int value;
public BoundedCounter(int upperLimit, int startValue) {
this.upperLimit = upperLimit;
this.startValue = startValue;
this.value = startValue;
}
public void next() {
value++;
if (value > upperLimit) {
value = 0;
}
}
public String toString() {
DecimalFormat df = new DecimalFormat("#00");
return "" + df.format(value);
}
}
One variant is to use handlers:
import java.text.DecimalFormat;
public class Test3 {
public static void main(String[] args) {
final BoundedCounter minutes = new BoundedCounter(59, 0);
final BoundedCounter hours = new BoundedCounter(23, 0);
minutes.setOverflow(hours::next);
hours.setOverflow(minutes::reset);
for (int i = 0; i < 70; i++) { //repeats actual time 70 times - just to check if works fine
minutes.next();
System.out.println(hours.toString() + ":" + minutes.toString());
}
}
public static class BoundedCounter {
private int startValue;
private int upperLimit;
private int value;
private Runnable c;
public BoundedCounter(int upperLimit, int startValue) {
this.upperLimit = upperLimit;
this.startValue = startValue;
this.value = startValue;
}
public void reset() {
this.value = startValue;
}
public void setOverflow(final Runnable c) {
this.c = c;
}
public void next() {
if (++value > upperLimit) {
value = 0;
c.run();
}
}
public String toString() {
DecimalFormat df = new DecimalFormat("#00");
return "" + df.format(value);
}
}
}
Maybe this will help... To show current time use:
System.out.println(hours.toString() + ":" + minutes.toString());
To increment hours: hours.next()
To increment minutes: minutes.next()

Java LinkedList with Object

Trying to implement a LinkedList that simulates a Portfolio, consisting of Stock objects. I'm struggling to figure out how to properly iterate through the list and check if each stock contains certain parameters. the SHAREPRICE method is the one I'm having trouble with specifically, if someone could help with that, I'd be very grateful. What I have so far:
import java.util.*;
public class Portfolio<AnyType> implements Iterable<AnyType> {
public int balance, shares;
private Stock<AnyType> beginMarker, endMarker, temp;
LinkedList<Stock> Portfolio = new LinkedList<Stock>();
java.util.Iterator<Stock> iter = Portfolio.iterator();
public int CASHIN(int x) {
balance = x;
return balance;
}
public int CASHOUT(int y) {
balance = balance + (-y);
return balance;
}
public int CASHBALANCE() {
return balance;
}
public void BUY(String t, int s, float pp) {
temp = new Stock<AnyType>(t, s, pp, pp, 0, null, null);
Portfolio.add(temp);
shares = shares + s;
}
public void SELL(String t, int s, float pp) {
shares = shares - s;
}
public void SHAREPRICE(String t, float pp)
{
if(Portfolio.contains(Stock.)
{
}
}
public void QUERY(String t) {
}
public int COUNTPORTFOLIO() {
return shares;
}
public void PRINTPORTFOLIO() {
}
public java.util.Iterator<AnyType> iterator() {
return new Iterator();
}
private class Iterator implements java.util.Iterator<AnyType> {
private Stock<AnyType> current = beginMarker.next;
private boolean okToRemove = false;
public boolean hasNext() {
return current != endMarker;
}
public AnyType next() {
if (!hasNext())
throw new java.util.NoSuchElementException();
AnyType nextItem = (AnyType) current.getTicker();
current = current.next;
okToRemove = true;
return nextItem;
}
public void remove() {
if (!okToRemove)
throw new IllegalStateException();
Portfolio.this.remove(current.prev);
okToRemove = false;
}
}
private class Stock<AnyType> implements Comparable<Stock<AnyType>> {
public String getTicker() {
return ticker;
}
public void setTicker(String ticker) {
this.ticker = ticker;
}
public float getPurchasePrice() {
return purchasePrice;
}
public void setPurchasePrice(float purchasePrice) {
this.purchasePrice = purchasePrice;
}
public float getLatestPrice() {
return latestPrice;
}
public void setLatestPrice(float latestPrice) {
this.latestPrice = latestPrice;
}
public float getPctChange() {
return pctChange;
}
String ticker;
int sharesOwned;
float purchasePrice, latestPrice;
float pctChange = (latestPrice - purchasePrice) / purchasePrice;
Stock<AnyType> prev, next;
public Stock(String ticker, int sharesOwned, float purchasePrice,
float latestPrice, float pctChange, Stock<AnyType> prev,
Stock<AnyType> next) {
this.ticker = ticker;
this.sharesOwned = sharesOwned;
this.purchasePrice = purchasePrice;
this.latestPrice = latestPrice;
this.pctChange = pctChange;
this.prev = prev;
this.next = next;
}
public int compareTo(Stock<AnyType> pctChange) {
return ((Comparable) this.pctChange)
.compareTo(Stock.getPctChange());
}
}
}
class TestPortfolio {
public static void main(String[] args) {
}
}
Forward Direction:
while(itr.hasNext())
{
System.out.println(itr.next());
}
Reverse Direction
while(itr.hasPrevious())
System.out.println(itr.previous());
}

Categories