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;
}
I have two classes called Pokemon.java and Move.java which contain methods for creating and modifying Pokemon and their moves. I've created all of the required methods, but I'm having trouble with the attack method, which is supposed to subtract an opponent's health when it's attacked.
Here is the code for the Pokemon.java class:
import java.util.ArrayList;
public class Pokemon
{
// Copy over your code for the Pokemon class here
// Private constants
private static final int MAX_HEALTH = 100;
private static final int MAX_MOVES = 4;
private String name;
private int health;
private int opponentHealth;
public static int numMovesForPokemon = Move.getNumOfMoves();
private Move move;
private static ArrayList<Move> moveListForPokemon = new ArrayList<Move>();
private String pokemonImage;
// Write your Pokemon class here
public Pokemon(String theName, int theHealth)
{
name = theName;
if(theHealth <= MAX_HEALTH)
{
health = theHealth;
}
}
public Pokemon(String name, String image)
{
this.name = name;
health = 100;
pokemonImage = image;
}
public Pokemon(String theName)
{
name = theName;
}
public void setImage(String image)
{
pokemonImage = image;
}
public String getImage()
{
return pokemonImage;
}
public String getName()
{
return name;
}
public int getHealth()
{
return health;
}
public boolean hasFainted()
{
if(health <= 0)
{
return true;
}
else
{
return false;
}
}
public boolean canLearnMoreMoves()
{
if(numMovesForPokemon < 4)
{
return true;
}
else
{
return false;
}
}
public boolean learnMove(Move other)
{
if(canLearnMoreMoves())
{
moveListForPokemon = Move.getList();
moveListForPokemon.add(other);
numMovesForPokemon++;
return true;
}
else
{
return false;
}
}
public void forgetMove(Move other)
{
moveListForPokemon.remove(other);
}
public static ArrayList<Move> displayList()
{
return moveListForPokemon;
}
public boolean knowsMove(Move move)
{
if(moveListForPokemon.contains(move))
{
return true;
}
else
{
return false;
}
}
public boolean knowsMove(String moveName)
{
if(moveListForPokemon.contains(move.getName()))
{
return true;
}
else
{
return false;
}
}
public boolean attack(Pokemon opponent, Move move)
{
if(knowsMove(move))
{
opponentHealth = opponent.getHealth();
opponentHealth -= move.getDamage();
return true;
}
else
{
return false;
}
}
public boolean attack(Pokemon opponent, String moveName)
{
if(knowsMove(moveName))
{
opponentHealth = opponent.getHealth();
opponentHealth -= move.getDamage();
return true;
}
else
{
return false;
}
}
public String toString()
{
return pokemonImage + "\n" + name + " (Health: " + health + " / " + MAX_HEALTH + ")";
}
// Add the methods specified in the exercise description
}
Here is the code for the Move.java class:
import java.util.ArrayList;
public class Move
{
// Copy over your code for the Move class here
private static final int MAX_DAMAGE = 25;
private String name;
private int damage;
public static int numMoves;
private static ArrayList<Move> moveList = new ArrayList<Move>();
public Move(String theName, int theDamage)
{
name = theName;
if(theDamage <= MAX_DAMAGE)
{
damage = theDamage;
}
}
public String getName()
{
return name;
}
public int getDamage()
{
return damage;
}
public static int getNumOfMoves()
{
return numMoves;
}
public static ArrayList<Move> getList()
{
return moveList;
}
public String toString()
{
return name + " (" + damage + " damage)";
}
// Add an equals method so we can compare Moves against each other
public boolean equals(Move other)
{
if(name.equals(other.getName()))
{
return true;
}
else
{
return false;
}
}
}
Finally, here is the code for PokemonTester.java where I test out the methods:
public class PokemonTester extends ConsoleProgram
{
private PokemonImages images = new PokemonImages();
public void run()
{
// Test out your Pokemon class here!
Pokemon p1 = new Pokemon("Charrizard", 100);
Pokemon p2 = new Pokemon("Pikachu", 100);
Move m1 = new Move("Flamethrower", 20);
Move m2 = new Move("Fire Breath", 15);
p1.learnMove(m1);
System.out.println(p1.knowsMove(m1));
System.out.println(p1.knowsMove("Flamethrower"));
System.out.println(p1.attack(p2, m1));
System.out.println(p2.getHealth());
}
}
I suppose your problem is this:
opponentHealth = opponent.getHealth();
opponentHealth -= move.getDamage();
This code has several problems:
I'd suggest using a local variable for opponentHealth instead of a class level field
The opponent doesn't gets to know that it's health was subtracted. You have to share this knowledge with him, e.g. by introducing a setter for health and then calling opponent.setHealth(opponentHealth)
You are first assigning the value of Oponent.getHealth() to the int variable oponentHealth which you then modify, however this modification does not affect the health of Opponent but instead just the oponentHealth variable, you either have to directly access and modify the health field of Opponent or implement some kind of setHealth(int health) method in the class Pokemon
My question is if it possible to use a void method in a setText for a Label? I'm working at the moment on school homework on Netbeans and I want to use the 'public void printTable()' in a Label but the programm always say that it is impossible to use a void here and I know that normally I should use a return statement but in the instruction is written that I should use a 'void'.
Here you can see my Java Class
public class AffineFunction
{
private int a;
private int b;
public int getA()
{
return a;
}
public int getB()
{
return b;
}
public void setA(int newA)
{
a = newA;
}
public void setB(int newB)
{
b = newB;
}
public AffineFunction(int pA, int pB)
{
a = pA;
b = pB;
}
public int solve(int x)
{
return (a*x)+b;
}
public void printTable()
{
for(int i =-10; i<=10; i++)
{
System.out.println("F(" + i + ") = " + solve(i));
}
}
public void printTable(double step)
{
for(double i = - 10 ; i<= 10; i = i + step)
{
System.out.println( "F(" + i + ") = " + solve((int)i));
}
}
}
Here is a part of my JFrame :
//E
int a = Integer.valueOf(aTextField.getText());
int b = Integer.valueOf(bTextField.getText());
int x = Integer.valueOf(xTextField.getText());
//T
AffineFunction affineFunction = new AffineFunction(a, b);
//S
FLabel.setText(String.valueOf(affineFunction.solve(x)));
printTableLabel.setText(String.valueOf(affineFunction.printTable()));
I want to compare two objects of a class that implements Comparable, I need to compare the objects using two java.sql.Time Objects ASC and DESC, I sort them in mysql like this:
...order by startTime ASC, endTime DESC
and I need to sort them in java in the same way, but im using just:
#Override
public int compareTo(Cita o) {
return (getHoraInicio().compareTo(o.getHoraInicio()));
}
but I dont know how to sort them with two fields like mysql, ASC and DESC.
this is the full implementation of the class I want to sort.
import java.text.SimpleDateFormat;
import java.sql.Time;
public class Cita implements Comparable<Cita> {
public Time horaInicio;
public Time horaTermino;
public Paciente paciente;
public String actividad;
public String observacion;
public String recordar;
public String ciudad;
public String TipoCita;
public String fecha;
public int idPaciente;
public int idCita;
public Cita() {
}
public Cita(String fecha, Time horaInicio, Time horaTermino, int idPaciente, String actividad,
String observacion, String recordar, String ciudad, String tipoCita) {
this.fecha = fecha;
this.horaInicio = horaInicio;
this.horaTermino = horaTermino;
this.idPaciente = idPaciente;
this.actividad = actividad;
this.observacion = observacion;
this.recordar = recordar;
this.ciudad = ciudad;
this.TipoCita = tipoCita;
}
public Cita(int idCita, String fecha, Time horaInicio, Time horaTermino, Paciente paciente, String actividad,
String observacion, String recordar, String ciudad, String tipoCita) {
this.idCita = idCita;
this.fecha = fecha;
this.horaInicio = horaInicio;
this.horaTermino = horaTermino;
this.paciente = paciente;
this.actividad = actividad;
this.observacion = observacion;
this.recordar = recordar;
this.ciudad = ciudad;
this.TipoCita = tipoCita;
}
#Override
public int compareTo(Cita o) {
return (getHoraInicio().compareTo(o.getHoraInicio()));
}
public int getIdCita() {
return idCita;
}
public void setIdCita(int idCita) {
this.idCita = idCita;
}
public Time getHoraInicio() {
return horaInicio;
}
public void setHoraInicio(Time horaInicio) {
this.horaInicio = horaInicio;
}
public Time getHoraTermino() {
return horaTermino;
}
public void setHoraTermino(Time horaTermino) {
this.horaTermino = horaTermino;
}
public Paciente getPaciente() {
return paciente;
}
public void setPaciente(Paciente paciente) {
this.paciente = paciente;
}
public String getActividad() {
return actividad;
}
public void setActividad(String actividad) {
this.actividad = actividad;
}
public String getObservacion() {
return observacion;
}
public void setObservacion(String observacion) {
this.observacion = observacion;
}
public String getRecordar() {
return recordar;
}
public void setRecordar(String recordar) {
this.recordar = recordar;
}
public String getCiudad() {
return ciudad;
}
public void setCiudad(String ciudad) {
this.ciudad = ciudad;
}
public String getTipoCita() {
return TipoCita;
}
public void setTipoCita(String TipoCita) {
this.TipoCita = TipoCita;
}
public int getIdPaciente() {
return idPaciente;
}
public void setIdPaciente(int idPaciente) {
this.idPaciente = idPaciente;
}
#Override
public int hashCode() {
int hash = 3;
hash = 71 * hash + this.idCita;
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Cita other = (Cita) obj;
if (this.idCita != other.idCita) {
return false;
}
return true;
}
public String getFecha() {
return fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
#Override
public String toString() {
SimpleDateFormat formatohora = new SimpleDateFormat("h:mm");
return formatohora.format(horaInicio) + " - " + formatohora.format(horaTermino) + ", " + paciente.getNombre();
}
}
On tie do the compare using the "other" object as a your left-hand-side operand (effectively reversing the order). You could also do a normal compare on end times and negate the answer.
#Override
public int compareTo(Cita o) {
int asc = getHoraInicio().compareTo(o.getHoraInicio());
if (asc != 0) { return asc; }
return o.getHoraTermino.compareTo(getHoraTermino())
}
Note, I am assuming HoraTermino maps to endTime.
I've seen to hit a bump with this. I can't seem to get the array of the map from text file. I mean, I can get everything else BUT the map's array tiles.
This is the text file:
{
'name': 'map_one.txt',
'title': 'xxx One',
'currentMap': 4,
'rightMap': 3,
'lefttMap': 5,
'downMap': 1,
'upMap': 2,
'items': [
{ name: 'Pickaxe', x: 5, y: 1 },
{ name: 'Battleaxe', x: 2, y: 3 }
],
'map': [ [ 1,3,1,1,1,24,1,1,1,1,1,1,1 ],
[ 1,3,1,1,1,24,1,1,1,1,1,1,1 ],
[ 1,7,1,1,1,24,1,1,24,1,1,1,1 ],
[ 1,7,1,1,7,1,1,1,24,1,1,1,1 ],
[ 1,7,7,7,1,24,24,24,24,1,1,1,1 ],
[ 1,1,7,1,1,24,1,24,1,1,1,1,1 ],
[ 1,1,1,1,1,24,1,1,1,1,1,1,1 ],
[ 1,1,3,1,1,24,1,1,1,1,1,1,1 ],
[ 1,3,3,1,1,24,1,1,1,1,1,1,1 ]]
};
and when I run it, I get this:
==========================
JSON MAP LOAD...
==========================
Name of map: xxx One
File of map: map_one.txt
ID of map: 4
==========================
ITEMS IN MAP
==========================
# OF ITEMS: 2
>> Name: Pickaxe (5, 1)
>> Name: Battleaxe (2, 3)
==========================
TILES OF MAP
==========================
null
Press any key to continue . . .
See the null? It's *suppose to be numbers of arrays.
I'm doing it wrong, probably, I know. Here's what I have so far:
import java.util.*;
import java.io.*;
import com.google.gson.*;
public class readGoogle {
public static String MapTitle;
public static Data data;
public static Item item;
public static String dan;
public static FileReader fr;
public static int number;
public static int currentMap;
public static int tile;
public static String[] wepN;
public static void main(String[] args) {
try {
fr = new FileReader("map1.txt");
}catch(FileNotFoundException fne) {
fne.printStackTrace();
}
StringBuffer sb = new StringBuffer();
char[] b = new char[1000];
int n = 0;
try {
while ((n = fr.read(b)) > 0) {
sb.append(b, 0, n);
}
}catch(IOException rex) {
rex.printStackTrace();
}
String fileString = sb.toString();
try {
data = new Gson().fromJson(fileString, Data.class);
}catch (Exception er) {
er.printStackTrace();
}
System.out.println("==========================\n JSON MAP LOAD...\n==========================\n");
System.out.println("Name of map: " + data.getTitle());
System.out.println("File of map: " + data.getName());
System.out.println("ID of map: " + data.getCurrentMap());
String[] wepN = new String[100];
String[] wepX = new String[100];
String[] wepY = new String[100];
int[] tile = new int[256];
int wepQty = 0;
try {
for (int i=0; i < wepN.length; i++) {
if (data.getItems().get(i).getName() == null || "".equals(data.getItems().get(i).getName())) {
System.out.println(data.getItems().get(i).getName() + " -NO MOARE");
break;
}
wepN[i] = data.getItems().get(i).getName();
wepX[i] = Integer.toString(data.getItems().get(i).getX());
wepY[i] = Integer.toString(data.getItems().get(i).getY());
wepQty++;
}
}catch(Exception xe) { }
System.out.println("\n==========================\n ITEMS IN MAP\n==========================\n");
System.out.println("# OF ITEMS: " + wepQty + "\n");
for (int i=0; i < wepQty; i++) {
System.out.println(">> Name: " + wepN[i] + " (" + wepX[i] + ", " + wepY[i] + ")");
}
System.out.println("\n==========================\n TILES OF MAP\n==========================\n");
System.out.println(data.getMap());
}
public static class Item {
public String name;
public int x;
public int y;
public int tile;
public String getName() { return name; }
public int getX() { return x; }
public int getY() { return y; }
public void setName(String name) { this.name = name; }
public void setX(int x) { this.x = x; }
public void setY(int y) { this.y = y; }
}
public static class Data {
private String name;
private String title;
private int currentMap;
private List<Item> items;
private int[][] tile;
public String getName() { return name; }
public int getCurrentMap() { return currentMap; }
public String getTitle() { return title; }
public List<Item> getItems() { return items; }
public int[][] getMap() { return tile; }
public void setName(String name) { this.name = name; }
public void setTitle(String title) { this.title = title; }
public void setItems(List<Item> items) { this.items = items; }
public void setMap(int[][] tile) { this.tile = tile; }
}
}
My thought is that the Data class has a tiles field for holding the map but in the JSON it is named map.
try:
public static class Data {
private String name;
private String title;
private int currentMap;
private List<Item> items;
private int[][] map;
public String getName() { return name; }
public int getCurrentMap() { return currentMap; }
public String getTitle() { return title; }
public List<Item> getItems() { return items; }
public int[][] getMap() { return map; }
public void setName(String name) { this.name = name; }
public void setTitle(String title) { this.title = title; }
public void setItems(List<Item> items) { this.items = items; }
public void setMap(int[][] map) { this.map= map; }
}