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...
Related
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);
When I run my program instead of receiving the string from the toString method in my RightTriangle class that I should get normally I instead receive the memory location of the string when I print the object from my driver. How do I fix this problem?
this is the RightTriangleDriver class
import java.util.*;
public class RightTriangleDriver
{
public static void main ( String [] args )
{
Scanner reader = new Scanner ( System.in );
System.out.println ( "Enter the length of the first leg " );
double leg1 = reader.nextDouble ();
System.out.println ( "Enter the length of the second leg " );
double leg2 = reader.nextDouble ();
RightTriangle f1 = new RightTriangle ( leg1, leg2 );
System.out.println ( f1 );
}
}
this is the RightTriangle class.
public class RightTriangle
{
private double leg1;
private double leg2;
private double hyp;
public RightTriangle (double one , double two)
{
leg1 = one;
leg2 = two;
hyp = Math.sqrt ( Math.pow ( leg1 , 2 ) + Math.pow (leg2 , 2 ) );
}
public double perimiter ()
{
double perimiter = 0;
perimiter = leg1 + leg2 + hyp;
return perimiter;
}
public double area ()
{
double area = 0;
area = ( leg1*leg2 )/2;
return area;
}
public String toSting ()
{
String str;
str = "Leg 1 is " + leg1 + " units long. Leg 2 is " + leg2 + " units long." + "\n" + "the Hypotenuse is " + hyp +
" units long." + "\n" + " The perimiter is " + perimiter () + " units and the area is " + area () +
" units squared.";
return str;
}
}
The method name is toString. You have not written correctly.
Whenever you override method of super class use #Override annotation (toString is method of Object class which every class inherit by default). This will help you to know if you are really overriding the method.
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);
Instead of the variables sum, diff prod inside the
System.out.println(" " + **here)**, is there a way I can store it in just one variable?
So if I call it inside a statement (and if i use a variable "answer")it would look something like this and will still give me the same output:
System.out.println("Sum = " + answer);
System.out.println("Difference = " + answer);
System.out.println("Product = " + answer);
I'm really stuck at this part of the program, any kind of help or tips will do, thanks
You can use an array to store the sum, diff, and prod respectively. Or you can great a new class that has those attributes.
For instance (with an array):
int[] answer = {sum, diff, prod};
System.out.println("Sum = " + answer[0]);
System.out.println("Difference = " + answer[1]);
System.out.println("Product = " + answer[2]);
It can't work the way your example is stated, but you could do something like the following:
public class NumberPair {
private final int x;
private final int y;
public NumberPair(int x, int y) {
this.x = x;
this.y = y;
}
public int sum() {
return x+y;
}
public int difference() {
return x-y;
}
public int product() {
return x * y;
}
}
Then you could do the following:
NumberPair answer = new NumberPair(10, 5);
System.out.println("Sum = " + answer.sum());
System.out.println("Difference = " + answer.difference());
System.out.println("Product = " + answer.product());
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/