Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I write following program to invoke the toString method, but it is not working.
import java.util.Scanner;
public class findarea_class {
public static void main(String[] args)
{
findarea_class objtostring = new findarea_class(1.0,1.0);
objtostring.setelements();
}
double width;
double height;
Scanner input = new Scanner(System.in);
findarea_class()
{
}
findarea_class(double width,double height)
{
this.width = width;
this.height = height;
}
public String toString()
{
return "width is: "+this.width+" and height is: "+this.height+"\n"
+"The area is : "+getarea(width,height)+"\n"
+"The perimeter is: "+getperimeter(width,height);
}
double getarea(double width,double length)
{
double area = width * length;
return area;
}
double getperimeter(double width,double length)
{
double perimeter = (2 * length) + (2 * width);
return perimeter;
}
double getwidth()
{
System.out.println("Please the width for calculation:");
double inputwidth = input.nextDouble();
System.out.println("Width is:"+inputwidth);
return inputwidth;
}
double getheight()
{
System.out.println("Please enter the height for calculation:");
double inputheight = input.nextDouble();
System.out.println("Height is:"+inputheight);
return inputheight;
}
void setelements()
{
double newwidth;
double newheight;
newwidth = getwidth();
newheight = getheight();
System.out.println("The new area is : "+getarea(newwidth,newheight));
System.out.println("The new perimeter is `enter code here`: "+getperimeter(newwidth,newheight));
}
}
You're not calling toString(). Pass it to anything that can display it. Use:
System.out.println(objtostring.toString());
Your main method should print the object, or maybe you can put the println call in your constructor (although i'm not a big fan of that).
public static void main(String[] args)
{
findarea_class objtostring = new findarea_class(1.0,1.0);
System.out.println(objtostring);
objtostring.setelements();
}
You are trying to override the toString method of Object class. Try this one.
#Override
public String toString() {
return "width is: "+this.width+" and height is: "+this.height+"\n"
+"The area is : "+getarea(width,height)+"\n"
+"The perimeter is: "+getperimeter(width,height);
}
and call it as objectName.toString();. In this case use something like this.objtostring.toString();
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 months ago.
Improve this question
I got the below question for an assignment in my Java class.
Write a Java method to find & print the area of a circle when user input the radius.
I came up with 2 solutions,
Solution 1: Call a void method where the method does all the inputs and calculations and prints the output.
import java.util.*;
class Example{
public static void area(){
Scanner input = new Scanner (System.in);
double area = 0;
double radius = input.nextInt();
area = 3.14 * radius * radius;
System.out.println("Area is: " + area);
}
public static void main(String args[]){
System.out.println("Input the radius: ");
area();
}
}
Solution 2: Call a parameterized double method. Here the input is fed to the main method and calculation is done in the double method and value is returned back to the main method.
import java.util.*;
class Example{
public static double area(double r){
double area = 0;
area = 3.14 * r * r;
return area;
}
public static void main(String args[]){
System.out.println("Input the radius: ");
Scanner input = new Scanner (System.in);
double radius = input.nextDouble();
System.out.println("Area is: " + area(radius));
}
}
I am wondering what is the best coding practice. Solution 1 or 2 and why is that? Thanks in advance for all the responses.
The second version is better because it separates the concerns of (a) calculating the area from (b) what to do with the results.
You don't need to declare double area = 0 before you assign a value to it. You can simply write:
double area = 3.14 * r * r;
But, in fact, you don't need to declare a variable at all in that method. You can return the value.
public static double area(double r){
return 3.14 * r * r;
}
You can also use the Math constant for PI:
public static double areaOfCircle(double r){
return Math.PI * r * r;
}
I'm not entirely sure if there is an easier answer to this question and I'm thinking to hard about it or what, but I'm currently programming a rectangular block program to practice Java. It's structured to have 4 methods: getInput, volBlock, saBlock, and display, and I want to use only local variables for these methods. Is there a way that I can utilize getInput to accept and return a single double from the user and if so, how can I use that input in my other methods?
I constructed this code, which uses local variables in getInput() and then passes those values to other methods, but I couldn't figure out a display method so I hard coded it into the calculation methods themselves.
Here is that code:
import java.util.*;
public class Block {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String choice = "Y";
while (choice.equals("Y")){
getInput();
System.out.println("Would you like to do another calculation?(Y/N): ");
choice = in.next().toUpperCase();
}
System.out.println("Program now ending...");
}
public static void getInput() {
double l, w, h;
Scanner fin = new Scanner(System.in);
System.out.println("Please enter the length, width, and height in that order: ");
l = fin.nextDouble();
w = fin.nextDouble();
h = fin.nextDouble();
volBlock(l, w, h);
surfaceAreaBlock(l,w,h);
}
public static void volBlock(double length, double width, double height) {
double volume;
volume = length * width * height;
System.out.println("The volume is: " + volume);
}
public static void surfaceAreaBlock (double l, double w, double h) {
double surfaceArea;
surfaceArea = 2 * (l*h+l*w+h*w);
System.out.println("The surface area is: " + surfaceArea);
}
}
I'm sorry if this question is kind of scrambled, I am having a hard time figuring all of this out. I'm quite new to Java.
Any help is appreciated, thank you!
If you're practicing java, you should probably familiarize yourself more with object oriented programming before you go any further, because your code leads me to believe that you're more used to procedural languages (e.g. C, C++, etc). Java doesn't rely on having several static helper methods in its main; the preferred approach is to construct a few classes that perform these calculations for you, and you use the results created by these functions for your basic input/output, which is normally what main is used for.
I implemented a block class to demonstrate what I mean:
public class Block {
private double length;
private double width;
private double height;
public Block(double l, double w, double h) {
length = l;
width = w;
height = h;
}
public double getVolume() {
return length * width * height;
}
public double getSurfaceArea() {
return 2 * length * (height + width) + height * width;
}
/* This is the "display" method that you want */
public String toString() {
return "The volume is: " + getVolume() + "\n"
"The surface area is: " + getSurfaceArea();
}
}
using the Block class, your main becomes much more simple:
public static void main() {
Scanner in = new Scanner(System.in);
char choice = 'y';
do {
System.out.print("Please enter the dimensions of the block: ");
double length = in.nextDouble();
double width = in.nextDouble();
double height = in.nextDouble();
Block block = new Block(length, width, height);
System.out.println(block);
System.out.print("continue (y/n)? ");
choice = in.nextLine.toLowerCase().charAt(0);
} while (choice == 'y');
}
If you return the values from your getInput(), volBlock() and surfaceAreaBlock() methods you might be able to structure the rest as you want to.
For instance surfaceAreaBlock becomes:
public static double surfaceAreaBlock (double l, double w, double h){
double surfaceArea;
surfaceArea = 2 * (l*h+l*w+h*w);
return surfaceArea;
}
and then when you call surfaceAreaBlock you can do this:
public static void main(String[] args) {
...
double surfaceArea = surfaceAreaBlock();
// Do something with the surface area in this method
...
}
I'm trying to create a toString method in a Box class to call in a BoxTest class. I've set up the methods I want to call (getLength, getHeight, getWidth, calculateArea, calculateVolume), which work fine by themselves, but I'm unsure how to use them when calling toString.
Here is a pastebin (http://pastebin.com/Ex520ST6) of my current code.
Box
public class Box
{
private double length = 1.0;
private double width = 1.0;
private double height = 1.0;
public Box(double length, double width, double height) // constructor with thrown exceptions
{
if (length <= 0)
throw new IllegalArgumentException("Values must be higher than 0");
if (width <= 0)
throw new IllegalArgumentException("Values must be higher than 0");
if (height <= 0)
throw new IllegalArgumentException("Values must be higher than 0");
this.length = length;
this.width = width;
this.height = height;
}
public void setLength(double length)
{
if (length <= 0)
throw new IllegalArgumentException("Values must be higher than 0");
this.length = length;
System.out.println("The new length is: " + length);
}
public double getLength()
{
System.out.println("The length is: " + length);
return length;
}
public void setWidth(double width)
{
if (width <= 0)
throw new IllegalArgumentException("Values must be higher than 0");
this.width = width;
System.out.println("The new width is: " + width);
}
public double getWidth()
{
System.out.println("The width is: " + width);
return width;
}
public void setHeight(double height)
{
if (height <= 0)
throw new IllegalArgumentException("Values must be higher than 0");
this.height = height;
System.out.println("The new height is: " + height);
}
public double getHeight()
{
System.out.println("The height is: " + height);
return height;
}
public double calculateArea()
{
double area = (double) (2*length*width + 2*length*height + 2*width*height);
System.out.println("The area is: " + area);
return area;
}
public double calculateVolume()
{
double volume = (double) length*width*height;
System.out.println("The volume is: " + volume);
return volume;
}
public String toString()
{
return String.format("The length is %f, the width is %f, the height is %f, the area is %f, the volume is %f,");
}
}
BoxTest
public class BoxTest
{
public static void main (String[] args)
{
Box[] boxes = new Box[4];
boxes[0] = new Box(1.0,2.0,3.0);
boxes[1] = new Box(4.0,5.0,6.0);
boxes[2] = new Box(1.0,7.0,8.0);
boxes[3] = new Box(1.0,9.0,9.0);
for (Box theBoxes : boxes)
{
System.out.printf(theBoxes.getLength(),theBoxes.getWidth(),theBoxes.getHeight(),theBoxes.calculateArea(),theBoxes.calculateVolume().toString());
}
boxes[3].setLength(11.0); // debug
}
}
Am I on the right track, generally
Should I be using "%s" specifier in the toString heading
Do I still need a format specifier in the printf, and if so, should it be %s or %f, as my methods are type double.
Thank you!
The toString() override should return a String with the values themselves and not rely on external use of System.out.printf() (The method can of course be used within the class, but the class should return a fully formatted String and not one that contains formatters like %s). An example implementation is as follows.
class Animal {
public String name;
public int numlegs;
public double weight;
// ...
#Override
public String toString() {
return String.format("Animal, name: %s, legs: %d, weight: %d", name, numLegs, weight);
}
}
You would then retrieve the full String representation of the object simply by calling the toString() method.
It is encouraged to use printf() rather than large scale String concatenation as it makes for cleaner code (IMO at least).
Side-notes:
Your toString() method calls printf() but doesn't provide the values that should replace the formatters in the format String.
Calls to printf() should have the format String as the first argument and the values as the remaining arguments.
How do i call the length and width variable into the getArea method without creating a private variable in the class, the way I'm doing it is causing the method to run again after its already ran once. I really don't like it this way but thats the way the professor wants it done to simulate the times before "object oriented programming"
/*This program allows the user to enter the length and widtch and receive the area
of the rectangle*/
import java.util.Scanner;
public class theRectangleCompany
{
public static void main(String[] args)
{
System.out.print("This program will find an area of a Rectangle ");
getLength();
getWidth();
getArea();
}
public static double getLength()
{
double length;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter the length ");
length = keyboard.nextDouble();
return length;
}
public static double getWidth()
{
double width;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter the width ");
width = keyboard.nextDouble();
return width;
}
public static void getArea()
{
double length = getLength();
double width = getWidth();
double area = width * length;
System.out.println("The area of the Rectangle is: " +area);
}
}
Why are you calling getLength() and getWidth() from the main method. Just call getArea()
public static void main(String[] args)
{
System.out.print("This program will find an area of a Rectangle ");
getArea();
}
You could make the getArea function take parameters, and use the function calls to the other two functions as the parameters:
getArea(getLength(), getWidth());
public static void getArea(double length, double width) { ... }
changes are here:
/*This program allows the user to enter the length and widtch and receive the area
of the rectangle*/
import java.util.Scanner;
public class theRectangleCompany
{
public static void main(String[] args)
{
System.out.print("This program will find an area of a Rectangle ");
getArea();
}
public static double getLength()
{
double length;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter the length ");
length = keyboard.nextDouble();
return length;
}
public static double getWidth()
{
double width;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter the width ");
width = keyboard.nextDouble();
return width;
}
public static void getArea()
{
double length = getLength();
double width = getWidth();
double area = (width * length);
System.out.println("The area of the Rectangle is: " +area);
}
}
Not sure if this is what you want:
public static void getArea()
{
System.out.println("The area of the Rectangle is: " + (getLength() * getWidth()));
}
You'd also need to change the main method to exclude the getLength() and getWidth():
public static void main(String[] args)
{
System.out.print("This program will find an area of a Rectangle ");
getArea();
}
An variant to the above is something like
public static void main(String[] args)
{
System.out.print("This program will find an area of a Rectangle ");
getArea(getLength(),getWidth());
}
public static void getArea(double length, double width)
{
System.out.println("The area of the Rectangle is: " + (length * width));
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm trying to write a code for where the user inputs two legs of a triangle and the program will calculate the hypotenuse, area, and perimeter. However, all my outputs are 0.
Here is the code:
package practice;
public class RightTri {
double leg1;
double leg2;
double hypotenuse;
double Area;
double Perimeter;
public RightTri() {
leg1=0;
leg2=0;
hypotenuse=0;
}
public double getArea() {
double Area= leg1*leg2*0.5;
return Area;
}
public double getHypotenuse() {
double Hypotenuse=Math.sqrt(Math.pow(leg1, 2.0)+Math.pow(leg2, 2.0));
return Hypotenuse;
}
public double getPerimeter() {
double Perimeter= leg1+leg2+hypotenuse;
return Perimeter;
}
}
package practice;
import javax.swing.JOptionPane;
public class RightTriTest {
public static void main (String args[]) {
RightTri Test=new RightTri();
String a= JOptionPane.showInputDialog ("Leg 1?");
Double leg1=Double.parseDouble(a);
String b= JOptionPane.showInputDialog ("Leg 2?");
Double leg2=Double.parseDouble(b);
System.out.println("The hypotenuse is " +Test.getHypotenuse());
System.out.println("The area is " +Test.getArea());
System.out.println("The perimeter is " +Test.getPerimeter());
}
}
You have defined your triangle's values to be 0:
public RightTri()
{
leg1=0;
leg2=0;
hypotenuse=0;
}
You never change any of them, so when you call getArea()...
public double getArea()
{
double Area= leg1*leg2*0.5;
return Area;
}
...you get 0 because 0 * 0 * 0.5 is zero.
You seem to have confused local variables in the main method with the ones in your triangle object. Try making a more sensible constructor instead:
public RightTri(double leg1, double leg2) {
this.leg1 = leg1;
this.leg2 = leg2;
}
And calling it from main, for example like this:
RightTri a = new RightTri(4, 6);
System.out.println(a.getArea());
Alternatively, since the fields are not private, you could access them directly from main:
Test.leg1 = 4.5;
But this isn't very idiomatic to Java, so I recommend using the constructor.
public RightTri()
{
leg1=0;
leg2=0;
hypotenuse=0;
}
All you values are 0 in your no-arg constructor
You should use a constructor like this
public RightTri(double leg1, double leg2)
{
this.leg1 = leg1;
this.leg2 = leg2;
}
Then in the main do something like this
String a= JOptionPane.showInputDialog ("Leg 1?");
Double leg1=Double.parseDouble(a);
String b= JOptionPane.showInputDialog ("Leg 2?");
Double leg2=Double.parseDouble(b);
RightTri Test = new RightTri(leg1, leg2);
System.out.println("The hypotenuse is " +Test.getHypotenuse());
System.out.println("The area is " +Test.getArea());
System.out.println("The perimeter is " +Test.getPerimeter());
That happens because the values that you obtain for leg1 and leg2 are not being assigned in your "Test" object. I recommend you to create a couple setters in your class RightTri:
public void setLeg1(Double leg1){
this.leg1 = leg1;
}
public void setLeg2(Double leg2){
this.leg2 = leg2;
}
And then assign the values from RightTriTest:
public static void main (String args[]) {
RightTri Test=new RightTri();
String a= JOptionPane.showInputDialog ("Leg 1?");
Double leg1=Double.parseDouble(a);
Test.setLeg1(leg1);
String b= JOptionPane.showInputDialog ("Leg 2?");
Double leg2=Double.parseDouble(b);
Test.setLeg2(leg2);
System.out.println("The hypotenuse is " +Test.getHypotenuse());
System.out.println("The area is " +Test.getArea());
System.out.println("The perimeter is " +Test.getPerimeter());
}
You've said it yourself: constructing a zero triangle is meaningless. Why not drop your default (i.e. no argument) constructor altogether?
Supply this instead:
public RightTri(double leg1, double leg2)
{
this.leg1 = leg1;
this.leg2 = leg2;
this.hypotenuse = Math.sqrt(leg1 * leg1 + leg2 * leg2);
}
Notice that I've bought the hypotenuse calculation inside the constructor. You might even want to bring the setting of Area and Perimeter inside it too: then you can guarantee that the object is in a well-formed state on construction at the expense of virtually negligible overhead. Of course, you'll need to adjust your various get... functions.
I've also dropped the pow functions. The way you have them with 2.0 as the argument will invoke a slow computation: it's much quicker for powers of 2 to multiply the numbers yourself.