reciving memory location instead of string output - java

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.

Related

Java class/objects output double with (,) and change decimal places

How do I input doubles such as 4,10, in the main class?
If not, how do I print the result as 4,10, after inputting 4.10?
Also, the trailing zero after the decimal is lost, after printing the result, how do I fix that?
public static void main(String[] args){
Pizza Rentals = new Pizza("Rentals",4.10);
Pizza Strength = new Pizza("Strength ", 3.10);
Pizza Molissimo = new Pizza("Molissimo", 4.20);
System.out.println(Rentals.getName() + " (" + Rentals.getPrice() + " euros)" );
System.out.println(Strength.getName() + " (" + Strength.getPrice() + " euros)" );
System.out.println(Molissimo.getName() + " (" + Molissimo.getPrice() + " euros)" );
}
Class
class Pizza{
String name;
double price ;
Pizza(String name, double price){
this.name = name;
this.price = price;
}
public String getName(){
return name;
}
public double getPrice() {
return price;
}
public String toString() {
return super.toString() ;
}
}
Desire outcome;
Rentals (4,10 euros)
Strength (3,10 euros)
Molissimo (4,20 euros)
For your given input one of the solutions can be to implement DecimalFormat as below:
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("#.00");
DecimalFormatSymbols sym = DecimalFormatSymbols.getInstance();
sym.setDecimalSeparator(',');
df.setDecimalFormatSymbols(sym);
Pizza Rentals = new Pizza("Rentals", 4.10);
Pizza Strength = new Pizza("Strength ", 3.10);
Pizza Molissimo = new Pizza("Molissimo", 4.20);
System.out.println(Rentals.getName() + " (" + df.format(Rentals.getPrice()) + " euros)");
System.out.println(Strength.getName() + " (" + df.format(Strength.getPrice()) + " euros)");
System.out.println(Molissimo.getName() + " (" + df.format(Molissimo.getPrice()) + " euros)");
}
use java.text.MessageFormat with correct java.util.Locale
Example as JUnit-Test:
import java.text.MessageFormat;
import java.util.Locale;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* #author jk
*/
public class MessageFormatTest {
#Test
public void hello() {
MessageFormat fmt_EN = new MessageFormat("{0,number,#0.00}", Locale.ENGLISH);
assertEquals("4.10", fmt_EN.format(new Object[] {4.10}));
MessageFormat fmt_DE = new MessageFormat("{0,number,#0.00}", Locale.GERMAN);
assertEquals("4,10", fmt_DE.format(new Object[] {4.10}));
}
}

Java Equals Method

I'm coding a program to sell and buy games. I have 3 classes: Main, Person and Game. What I want it to do: Check if the (Game g) is already in the (ArrayList games), basically check for the same values. If yes, then it should return true. If false, it should return false. How can I achieve this?
My problem: For the p1.koop(g3) it still says it succeeded. However, the g2 and g3 are the same. Therefor it should not succeed.
My main:
package week3.practicum;
import java.time.LocalDate;
public class Practicum2 {
public static void main(String[] args) {
int releaseJaar1 = LocalDate.now().getYear() - 1; // 1 jaar geleden
int releaseJaar2 = LocalDate.now().getYear() - 2; // 2 jaar geleden
Game g1 = new Game("Just Cause 3", releaseJaar1, 49.98);
Game g2 = new Game("Need for Speed: Rivals", releaseJaar2, 45.99);
Game g3 = new Game("Need for Speed: Rivals", releaseJaar2, 45.99);
Persoon p1 = new Persoon("Eric", 200.0);
Persoon p2 = new Persoon("Hans", 55.0);
Persoon p3 = new Persoon("Arno", 185.0);
System.out.println("p1 koopt g1:" + (p1.koop(g1) ? "" : " niet") + " gelukt");
System.out.println("p1 koopt g2:" + (p1.koop(g2) ? "" : " niet") + " gelukt");
System.out.println("p1 koopt g3:" + (p1.koop(g3) ? "" : " niet") + " gelukt");
System.out.println("p2 koopt g2:" + (p2.koop(g2) ? "" : " niet") + " gelukt");
System.out.println("p2 koopt g1:" + (p2.koop(g1) ? "" : " niet") + " gelukt");
System.out.println("p3 koopt g3:" + (p3.koop(g3) ? "" : " niet") + " gelukt");
System.out.println("\np1: " +p1+ "\n\np2: " +p2+ "\n\np3: " +p3+ "\n");
System.out.println("p1 verkoopt g1 aan p3:"+(p1.verkoop(g1, p3) ? "" : " niet")+" gelukt");
System.out.println("p2 verkoopt g2 aan p3:"+(p2.verkoop(g2, p3) ? "" : " niet")+" gelukt");
System.out.println("p2 verkoopt g1 aan p1:"+(p2.verkoop(g1, p1) ? "" : " niet")+" gelukt");
System.out.println("\np1: " +p1+ "\n\np2: " +p2+ "\n\np3: " +p3+ "\n"); } }
This is my Person class:
package week3.practicum;
import java.util.ArrayList;
public class Persoon {
private String naam;
private Double budget;
private ArrayList<Game> games;
private Game gameObj;
public Persoon(String nm, Double bud){
naam = nm;
budget = bud;
games = new ArrayList<Game>();
}
public boolean koop(Game g){
Double huidW = g.huidigeWaarde();
if (budget > huidW && games.equals(g) == false){
games.add(g);
budget = budget - huidW;
return true;
}
else{return false;}
}
public boolean verkoop(Game g, Persoon koper){
Double huidW = g.huidigeWaarde();
if (koper.budget > huidW){
koper.budget = koper.budget = huidW;
budget = budget + huidW;
koper.games.add(g);
games.remove(g);
return true;
}
else{
return false;
}
}
public String toString(){
String s = naam + " heeft een budget van " + budget + " en bezit de volgende games:\n";
for (Game gam: games){
s += gam;
}
return s;
}
}
Here's my equals method in the Game class.
package week3.practicum;
public class Game {
private String naam;
private Integer releaseJaar;
private Double nieuwprijs;
public Game(String nm, Integer rJ, Double nwpr){
naam = nm;
releaseJaar = rJ;
nieuwprijs = nwpr;
}
public String getNaam(){
return naam;
}
public Double huidigeWaarde(){
Double huidigeprijs = 0.0;
if (releaseJaar == 2016){
huidigeprijs = nieuwprijs * 0.7;
}
else if (releaseJaar == 2015){
huidigeprijs = nieuwprijs * 0.7 * 0.7;
}
else{
huidigeprijs = nieuwprijs;
}
return huidigeprijs;
}
public boolean equals(Object andereObject) {
boolean gelijkeObjecten = false; // blijft false tenzij:
if (andereObject instanceof Game) {
Game andereGame = (Game) andereObject;
if (this.naam.equals(andereGame.naam)){
gelijkeObjecten = true;
}
}
return gelijkeObjecten; }
public String toString(){
String s = naam + ", uitgegeven in " + releaseJaar + "; nieuwprijs: " + nieuwprijs + " nu voor: " + huidigeWaarde() + "\n";
return s;
}
}
games.equals(g) == false
Aside from the fact that you don't need to compare a boolean to a boolean to convert the boolean into a boolean, you're comparing a List to a Game, which can never be true.
you are not invoking the equals Method in any way.
To address ur initial need:
1- Create a private method that will take 2 parameters: 1- the games ArrayList , and 2 the game you want to check.
LAter for loop and check if the game exist return false.
private boolean doesGameExist(ArrayList gameList, Game gameToAdd){
for (int i=0; i<gameList.size(); i++){
if (gameList.get(i).equals(gameToAdd)){
return true; //the game already exists
}
}
return false; ///the game does not exist
}
than call this function prior to adding a new game to the array list.

Cannot understand the reason for IllegalArgumentException

Below is my code,
// Testing class circle
import java.text.DecimalFormat ;
import javax.swing.JOptionPane ;
public class CircleTest {
public static void main( String args[] )
{
// instantiate Circle object
Circle circle = new Circle( ) ;
Point3 point = new Point3( 40, 50 ) ;
// get circle's initial x - y coordinate and radius
String output = "\nX coordinate is " + circle.getX( ) +
"\nY coordinate is " + circle.getY( ) +
"\nRadius is " + circle.getRadius() ;
circle.setX( 35 ); // set new x - coordinate
circle.setY( 20 ); // set new y - coordinate
circle.setRadius( 4.25 ); // set new radius
// get String representation of new circle value
output += "\n\nThe new location and radius of circle are\n" +
circle.toString() ;
// format floating - point values with 2 digits of precision
DecimalFormat twoDigits = new DecimalFormat ( " 0.00 ") ;
// get Circle's diameter, Circumference and area respectively
output += "\nDiameter is " + twoDigits.format( circle.getDiameter() ) +
"\nCircumference is " + twoDigits.format( circle.getCircumference() ) +
"\nArea is " + twoDigits.format( circle.getArea( ) +
" Test sum is: " + twoDigits.format( point.sum( ) ) ) ;
JOptionPane.showMessageDialog( null, output ) ;
System.exit( 0 );
} // end method main
} // end class CircleTest
I am getting an error as
Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Number
at java.text.DecimalFormat.format(DecimalFormat.java:507)
at java.text.Format.format(Format.java:157)
at CircleTest.main(CircleTest.java:35)
However I am not getting the above error if I append the output separately with
output += " Test sum is: " + twoDigits.format( point.sum() ) ;
Why is it so? What is the problem ?
You are applying format at the whole string message, not just the area: a ) is missing, there.
You are mistakenly put the bracket.
Here is the fixed one
output += "\nDiameter is " + twoDigits.format(circle.getDiameter()) +
"\nCircumference is " + twoDigits.format(circle.getCircumference()) +
"\nArea is " + twoDigits.format(circle.getArea()) +
" Test sum is: " + twoDigits.format(point.sum()) ;

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