display the weight of balls in ascending order - java

Now the information is displayed in order (by ball number) How can I display the weight of the balls in ascending order?
public class WorkWithBall {
public static double WeightBall(){
Random random = new Random();
return random.nextInt(10)/2.5+1;
}
public class WorkWithBasket {
public static Basket fillBasket(Basket basket){
for(int i =0; i < basket.getVolume(); i++){
Ball temp = new Ball(Color.getRandomColor(),WorkWithBall.WeightBall());
basket.addBall(temp);
}
return basket;
}
public static void InfoOut (Basket basket){
for (int i = 0; i < basket.getBasket().length; i++){
System.out.println("Ball #" + (i+1) + " with color - " + basket.getBasket()[i].getColor()+
" weight - " + basket.getBasket()[i].getWeight());
}
}

Using Java 8, get a stream from the balls array. Sort by weight, as follows:
Stream.of(basket.getBasket()).sorted(Comparator.comparing(Ball::getWeight)).forEach(ball -> {
System.out.println(ball.getColor() + " " + ball.getWeight());
});

You should use Stream and sorted() like
public static void InfoOut (Basket basket){
Arrays.stream(basket.getBasket()).sorted(Comparator.comparing(Ball::getWeight)).forEach((Ball ball) -> {
System.out.println("Ball #" + (i+1) + " with color - " + basket.getBasket()[i].getColor()+ " weight - " + basket.getBasket()[i].getWeight());
})
}
Also please note that your print should be placed in toString method of Ball overriden from Object class.
And you might simplify the stream like
Arrays.stream(basket.getBasket()).sorted(Comparator.comparing(Ball::getWeight)).forEach(System.out::println);

Related

How to double a value of private int type field?

This is the code of method takeDamage in the class Enemy which is a superclass of class Vampire.
public void takeDamage(int damage) {
int remainingHitPoints = hitPoints - damage;
if (remainingHitPoints > 0) {
setHitPoints(remainingHitPoints);
System.out.println(name + " took " + damage + " damage and have " + remainingHitPoints + " HitPoint left" + "\n------------------------------------" );
} else {
this.lives = this.lives - 1;
System.out.println(name + " took " + damage + " damage" + "\n------------------------------------" + "\n" + name +" lost a life" + "\n------------------------------------");
if (lives > 0) {
System.out.println(name + " revived" + "\n------------------------------------");
setHitPoints(remainingHitPoints + damage);
} else {
System.out.println(name + " is dead now RIP" + "\n------------------------------------");
setHitPoints(0);
}
}
}
In the class Vampire I override the method takeDamge:
public void takeDamage(int damage) {
int inflictedDamage = damage/2;
int doubleHitPoints = getHitPoints()*2;
int remainingHitPoints = getHitPoints() - inflictedDamage;
int remainingLives = getLives() - 1;
if (remainingHitPoints > 0) {
setHitPoints(remainingHitPoints);
System.out.println(getName() + " took " + inflictedDamage + " damage(Vampire takes inflicted damage) and has " + remainingHitPoints + " HitPoint left" + "\n------------------------------------" );
} else {
setLives(remainingLives);
System.out.println(getName() + " took " + inflictedDamage + " damage(Vampire takes inflicted damage)" + "\n------------------------------------" + "\n" + getName() +" lost a life" + "\n------------------------------------");
if (remainingLives > 0) {
System.out.println(getName() + " revived and even got stronger!" + "\n------------------------------------");
setHitPoints(doubleHitPoints);
} else {
System.out.println(getName() + " is dead now RIP" + "\n------------------------------------");
setHitPoints(0);
}
}
}
What I intend to do is double the object's hitPoints which is originally set by the constructor.
When a Vampire object takes enough damage to die (in other words, when it loses its life), this method successfully doubles the object's hitPoints.
The problem happens (if I diagnosed right) when the Vampire object takes not enough damage to die.
setHitPoints(remainingHitpoints); gets executed and when the Vampire object takes enough damage to die, it doubles the object's remainingHitPoints not an original hitPoints.
I would like to fix this issue.
The hitPoints field has been declared as private inside the Enemy class so if I understood well the only way to modify the value of this field is by using getHitPoint method (getter) inside the Enemy class.
You need some place where the original hit points are stored.
If your Enemy class doesn't provide this information and you only need it in the Vampire class you could change the Vampire class along these lines:
public class Vampire extends Enemy {
private int originalHitPoints;
public Vampire() {
// ...
originalHitPoints = getHitPoints();
}
public void takeDamage(int damage) {
// ...
if (remainingLives > 0) {
System.out.println(getName() + " revived and even got stronger!" + "\n------------------------------------");
setHitPoints(originalHitPoints * 2);
}
// ...
}
}
If you want to double the hit points every time the Vampire dies you could change the code of takeDamage() like this:
public void takeDamage(int damage) {
// ...
if (remainingLives > 0) {
System.out.println(getName() + " revived and even got stronger!" + "\n------------------------------------");
originalHitPointes *= 2; // double the hit points
setHitPoints(originalHitPoints);
}
// ...
}

How to declare two variables and run each separately through a method? (java)

So for an assignment I have to create an application whose main() method holds two variables. After declaring the variables and assigning an integer to each of them, I have to run both through the same 3 methods. I was thinking that I have to create a class for the variables, but honestly have no idea where to begin. So far, I have figured out how to run one of the integers through the methods, but I can't get both to pass through the same methods.
Here is my work so far:
public class ArithmeticMethods{
public class integer
{
int firstInteger = 10;
int secondInteger = 20;
}
public static void main(String[] args) {
displayNumberPlus10();
displayNumberPlus100();
displayNumberPlus1000();
System.out.println(firstInteger + " +" + " 10" + " is " + displayNumberPlus10());
System.out.println(firstInteger + " +" + " 100" + " is " + displayNumberPlus100());
System.out.println(firstInteger + " +" + " 1000" + " is " + displayNumberPlus1000());
}
public static int displayNumberPlus10() {
int numberPlus10;
numberPlus10 = (firstInteger + 10);
return numberPlus10;
}
public static int displayNumberPlus100() {
int numberPlus100;
numberPlus100 = (firstInteger + 100);
return numberPlus100;
}
public static int displayNumberPlus1000() {
int numberPlus1000;
numberPlus1000 = (firstInteger + 1000);
return numberPlus1000;
}
}
Right now the methods are set to only run the first variable and with my ATTEMPT at creating a class, the program doesn't work at all. Any advice would be greatly appreciated.
Also I apologize if the code looks ugly. I am very new to this.
You need to add parameters to your methods. The result should look something like this:
public static int displayNumberPlus10(int input) {
return (input + 10);
}
...
And can be called like this:
int first = 10;
int second = 20;
displayNumberPlus10(first);
displayNumberPlus10(second);

Accessing variables of an instance stored in an Object

I can't seem to access any get/set methods or the variables directly from an object. I'm attempting to get the level of my enemy which is stored in a variable as below. The last line, I 'want' to do "World[i][j].enemy.getLevel()" but apparently that is an illegal move? At the moment it just prints the objects id reference.
Is there a conversion back to an object i'm missing?
The Monster class extends Player.
Creation:
World[i][j].enemy = spawnEnemy(World[i][j].mapLevel); //Spawn a monster.
Other code:
public static Object spawnEnemy(int level) {
//Spawns a monster and returns the Object.
Monster enemy = new Monster();
enemy.setLevel(level);
enemy.setMaxHealth(level * 5);
enemy.setHealth(enemy.getMaxHealth());
enemy.setDamage(enemy.getLevel() * 3);
return enemy;
}
public static void enemiesAlive() {
for (int i = 0; i < mapSizeX; i++)
{
for (int j = 0; j < mapSizeY; j++)
{
if (World[i][j].enemyAlive)
{
System.out.print(i + "-" + j + " with a level of " + World[i][j].enemy + ", ");
}
}
}
}
The last line, I 'want' to do "World[i][j].enemy.getLevel()"
The problem is that you forgot the call to getLevel() and simply print the object reference.
Change
System.out.print(i + "-" + j + " with a level of " + World[i][j].enemy + ", ");
for
System.out.print(i + "-" + j + " with a level of " + ((Player)World[i][j].enemy).getLevel() + ", ");

Methods and arrays

Here is my code:
import java.util.*;
import java.text.*;
public class zadanko4
{
int ile;
public static final int vat8 = 8;
public static final int vat23 = 23;
public static final int vat5 = 5;
//deklaracje zmiennych tablicowych
static double[] price;
static String[] name;
static int[] quantity;
static int[] vat;
//tworzenie tablic
price = new double[ile];
name = new String[ile];
quantity = new int[ile];
vat = new int[ile];
public static void printSellerData(String tekst)
{
System.out.print(tekst);
}
public static void printBuyerData(String company, String taxNo, String phone, String email)
{
System.out.print(company + taxNo + phone + email);
}
public static void printInvoiceDate(Date data)
{
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.print(dateFormat.format(data));
}
public static void printInvoiceHeader(String naglowek)
{
System.out.print(naglowek);
}
public static void printInvoiceProduct(String name, int quantity, double price, int vat)
{
System.out.printf(name + quantity + price + vat);
}
public static void readProductsData()
{
//uzytkownik wprowadza liczbe produktow
System.out.println("podaj liczbe produktow");
Scanner scanner = new Scanner(System. in );
ile = scanner.nextInt();
}
public static void main(String[] args)
{
int i;
String line;
for (i = 0; i < ile; i++)
{
System.out.print("Podaj cene produktu nr " + (i + 1) + ": ");
price[i] = scanner.nextDouble();
System.out.print("Podaj nazwe produktu nr " + (i + 1) + ": ");
name[i] = scanner.next();
System.out.print("Podaj ilosc produktu nr " + (i + 1) + ": ");
quantity[i] = scanner.nextInt();
System.out.print("Podaj vat produktu nr " + (i + 1) + ": ");
vat[i] = scanner.nextInt();
System.out.printf("Dane sprzedajacego\n");
printSellerData("Company: MaxDom Ltd, Kochanowskiego 17, 31-782 Krakow, Poland\n");
printSellerData("Tax no: 677-000-21-39\n");
printSellerData("Phone: +48123454943\n");
printSellerData("Email: office#maxdom.pl\n\n");
System.out.printf("Dane kupujacego\n");
printBuyerData("Softpol Ltd, Mickiewicza 5, 31-009 Krakow, Poland\n", "342-909-33-12\n", "+48505392100\n", "office#softpol.eu\n");
// printInvoiceNumber(+numer+);
Date data = new Date();
printInvoiceDate(data);
printInvoiceHeader("|No.|Product desciptrion |Quantity |Unit price |Total |VAT rate |VAT |Gross|");
printInvoiceHeader("|______________________________________________________________________________________________________|");
//printInvoiceProduct("name[i]", ilosc[prod], cena[prod], vat[prod]");
printInvoiceProduct("|" + (i + 1) + " |" + name[i] + " |" + quantity[i] + " |" + price[i] + " |" + (quantity[i] * price[i]) + " |" + (vat[i] / 100.0) + " |" + (quantity[i] * price[i] * (vat[i] / 100.0)) + " |" + (quantity[i] * price[i]) * (1 + (vat[i] / 100.0)));
}
}
}
and my problems:
I have 4 errors like: error: <identifier> expected. It is connected
with arrays but i have no idea what is wrong.
By the last line: printInvoiceProduct.... I want to display 1 product which user entered, but nothing displays.
Why is that?
Create new memory addresses for arrays as you refer them. Like;
static double[] price = new double[ile];
This is also not enough because these static arrays trying to make a static reference to a non-static variable, "ile". So if you want your arrays to be static, just make "ile" static also.
printInvoiceProduct method is declared to pass 4 arguments to it but you've called it by only one String object.
Even if you solve compilation errors you will face again problems.
For example you are creating an array with size zero This will fail. So instead of creating your array objects above; create in the main function after knowing size of array.
So get rid of ile variable. Take input in the main and then instantiate all the array.
Even I don't see a need of class level arrays all can be method local.
On top of that I don't think this is correct platform to solve such problem. Consider putting your problem on
https://codereview.stackexchange.com/

Obtaining Value from a Method (java)

I have gotten this code to work out so far, but I am trying to learn how to complete this method so that it will compile the total amount of sides used and print that value on in the last print line. The problem method is getTotalSides, I currently have it set to return 0, but I want it to return the total sides instead, meaning: mp1.getSides() + mp2.getSides() + mp3.getSides() + mp4.getSides().
public class TestParts {
public static void main(String[] args) {
MyPolygon mp1 = new MyPolygon();
MyPolygon mp2 = new MyPolygon(4);
MyPolygon mp3 = new MyPolygon(5);
MyPolygon mp4 = new MyPolygon(6);
System.out.println("Polygon 1 has " + mp1.getSides()
+ " sides, angles total " + mp1.getSumOfAngles());
System.out.println("Polygon 2 has " + mp2.getSides()
+ " sides, angles total " + mp2.getSumOfAngles());
System.out.println("Polygon 3 has " + mp3.getSides()
+ " sides, angles total " + mp3.getSumOfAngles());
System.out.println("Polygon 4 has " + mp4.getSides()
+ " sides, angles total " + mp4.getSumOfAngles());
System.out.println("There are " + MyPolygon.getTotalSides()
+ " total sides");
}
}
class MyPolygon {
double getSides;
MyPolygon() {
getSides = 3;
}
static double getTotalSides() {
return 0;
}
double getSides() {
// TODO Auto-generated method stub
return getSides;
}
MyPolygon(double newGetSides) {
getSides = newGetSides;
}
double getSumOfAngles() {
return ((getSides - 2) * 180);
}
void setGetSides(double newGetSides) {
getSides = newGetSides;
}
If you really need a method, you can use varargs (variable arity arguments) for this purpose:
static double getTotalSides(MyPolygon... polygons) {
double x = 0;
for (MyPolygon p: polygons)
{
x+= p.getSides();
}
return x;
}
Then call like this:
System.out.println("There are " + MyPolygon.getTotalSides(mp1,mp2,mp3,mp4)
+ " total sides");
or make an array
MyPolygon myPolygons = new MyPolygon [4];
myPolygons [0] = mp1;
myPolygons [1] = mp2;
myPolygons [2] = mp3;
myPolygons [3] = mp4;
System.out.println("There are " + MyPolygon.getTotalSides(myPolygons)
+ " total sides");
However, the better solution is to store your Polygons in an array/List from the beginning then pass that whole array/List them off to the method, do the loop, and return the result. Be aware though, that Lists and arrays are different, and so, you will neeed to modify the method signature accordingly.
Why don't you just put the expression that you wrote out in:
System.out.println("There are " + (mp1.getSides() + mp2.getSides() + mp3.getSides() + mp4.getSides()) + " total sides");
Since you are trying to write getTotalSides as part of the class, there is not a simple way to check for all other instantiated objects and call their method getSides to add up all the total sides. You could define a function that takes all the polygon objects and adds up the sides, but it can't be under the class definition.
You need look at the scope of your objects, maybe you could use some sort of Collection
public class TestParts {
public static void main(String[] args) {
final MyPolygon mp1 = MyPolygon.newInstance(3);
final MyPolygon mp2 = MyPolygon.newInstance(4);
final MyPolygon mp3 = MyPolygon.newInstance(5);
final MyPolygon mp4 = MyPolygon.newInstance(6);
System.out.println("Polygon 1 has " + mp1.getSides()
+ " sides, angles total " + mp1.getSumOfAngles());
System.out.println("Polygon 2 has " + mp2.getSides()
+ " sides, angles total " + mp2.getSumOfAngles());
System.out.println("Polygon 3 has " + mp3.getSides()
+ " sides, angles total " + mp3.getSumOfAngles());
System.out.println("Polygon 4 has " + mp4.getSides()
+ " sides, angles total " + mp4.getSumOfAngles());
System.out.println("There are " + MyPolygon.getTotalSides()
+ " total sides");
}
}
class MyPolygon {
private static final Collection<MyPolygon> POLYGONS = new LinkedList<MyPolygon>();
private final double sides;
private MyPolygon(final double sides) {
this.sides = sides;
}
public static MyPolygon newInstance(final double sides) {
final MyPolygon polygon = new MyPolygon(sides);
POLYGONS.add(polygon);
return polygon;
}
public static double getTotalSides() {
double sides = 0d;
for (final MyPolygon polygon : POLYGONS) {
sides += polygon.getSides();
}
return sides;
}
public double getSides() {
return sides;
}
public double getSumOfAngles() {
return ((sides - 2) * 180);
}
}
I have tidied your code so it conforms to naming conventions (no getSides variable).
If you want global information on the number of all sides ever created, try a static variable:
class MyPolygon {
private static int totalSides;
private int sides;
MyPolygon() {
this(3); // constructor chaining: really useful
}
MyPolygon(int numSides) {
this.sides = numSides;
MyPolygon.totalSides += numSides;
}
// ... the rest, incl. getter for sides and static getter for totalSides
}
However, when it may happen that you do not need one polygon anymore, you have to decrease the number explicitly again somehow...

Categories

Resources