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;
}
Related
I'm having difficulty trying to print the result of the static method calcArea, which takes the int radius as parameter to calculate the area of a circle and returns the area.
Here's the code below 👇 Any help would be appreciated.
public class CircleArea {
public int radius;
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter the radius of the circle: ");
int radius = input.nextInt();
System.out.print("The area of the circle is:" + calcArea()); <-- ERROR HERE
}
public static double calcArea(int radius){
double area = Math.PI * Math.pow(radius, 2);
return area;
}
}
Your call to calcArea needs a parameter passed in. Probably calcArea(radius).
The function calcArea() takes the value of radius and then returns area. To do this, you need to pass an argument to calcArea(). So, your code should be like this:
System.out.print("The area of the circle is:" + calcArea(radius));
The error you're getting clearly points out that you're missing an argument.
call method calcArea, you need give a parameter,Here are the correct example"
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter the radius of the circle: ");
int radius = input.nextInt();
System.out.print("The area of the circle is:" + calcArea(radius));
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
This program counts first 6 months interest for given amount, it doesn't work where is the mistake?
import java.util.Scanner;
public class BalAfter6Months{
public static void main(String []args){
int counter=1;
double interest,SavBal,total,amount;
Scanner sc = new Scanner (System.in);
System.out.print("Enter the monthly saving amount: ");
amount = sc.nextDouble();
SavBal = amount;
while (counter<7) {
interest = amount * 0.00417;
total = interest + SavBal;
amount = amount + SavBal;
counter++;
}
System.out.print(total);
}
}
This avoids unnecessary variables, and IMO is much simpler.
import java.util.Scanner;
public class BalAfter6Months{
public static void main(String []args){
double interest, balance;
Scanner sc = new Scanner (System.in);
System.out.print("Enter the monthly saving amount: ");
balance = sc.nextDouble();
int count = 1
while (counter < 7) {
interest = balance * 0.00417;
balance += interest
counter++;
}
System.out.print(total);
}
}
You have coded it correctly. You just have to initialize the total variable to avoid the compiler error.
/* Initialize Total Variable */
double interest,SavBal,total = 0,amount;
Input:
100
Output:
102.502
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();
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
import java.util.Scanner;
public class Hw4Part4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Ask for the diners’ satisfaction level using these ratings: 1 = Totally
// satisfied, 2 = Satisfied,
// 3 = Dissatisfied.
System.out.println("Satisfacion leve: ");
int satisfactionNumber = sc.nextInt();
// Ask for the bill subtotal (not including the tip)
System.out.println("What is the bill subtotal: ");
double subtotal = sc.nextInt();
// Report the satisfaction level and bill total.
System.out.println("The satisfaction level is: " +
satisfactionLevel(satisfactionNumber));
System.out.println("The bill total is: " +
getBillTotal(tipPercentage, subtotal));
}
public static String satisfactionLevel(int satisfactionNumber) {
String satisfactionL = "";
if (satisfactionNumber == 1) {
satisfactionL = "Totally-satisfied";
}
if (satisfactionNumber == 2) {
satisfactionL = "Satisfied";
}
if (satisfactionNumber == 3) {
satisfactionL = "Dissatisfied";
}
return satisfactionL;
}
// This method takes the satisfaction number and returns the percentage of tip
// to be
// calculated based on the number.
// This method will return a value of 0.20, 0.15, or 0.10
public static double getPercentage(int satisfactionNumber) {
double getPercentage = 0;
if (satisfactionNumber == 1) {
getPercentage = 0.20;
}
if (satisfactionNumber == 2) {
getPercentage = 0.15;
}
if (satisfactionNumber == 3) {
getPercentage = 0.10;
}
return getPercentage;
}
public static double getBillTotal(double tipPercentage, double subtotal) {
double totalWithTip =
(subtotal + (getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
}
Error where it says getPercentage(satisfactionNumber)*subtotal..... says SatisfactionNumber cannot be resolved to a variable
And in the Main method there is a error on
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal)); I believe it is the related to the last error.
In getBillTotal, satisfactionNumber is undefined, it has meaning within the context of the method. In order to use it, you would need to define the variable within the context of the method either as a parameter or as a local variable...
In your main method, You have the same problem with tipPercentage, it's undefined...
Your close. You will need to pass in satisfactionNumber into getBillTotal by adding another parameter. Otherwise it don't know what you are taking about when you say satisfactionNumber. It can't directly see the variables in other functions.
public static double getBillTotal(double tipPercentage, double subtotal, int satisfactionNumber) {
double totalWithTip = (subtotal + (getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
Then in your main method call pass it in.
public static void main(String[] args) {
....
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
}
And actually you don't need tipPercentage, in fact it's not even defined in main. Since it can be found by satisfactionNumber you could do this.
public static void main(String[] args) {
....
System.out.println("The bill total is: " + getBillTotal(subtotal, satisfactionNumber));
}
...
public static double getBillTotal(double subtotal, int satisfactionNumber) {
double totalWithTip = (subtotal + (getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
OR you could pass in the tipPercentage by calculating it first.
public static void main(String[] args) {
....
double tipPercentage = getPercentage(satisfactionNumber);
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal));
}
...
public static double getBillTotal(double tipPercentage, double subtotal) {
double totalWithTip = (subtotal + (tipPercentage * subtotal));
return totalWithTip;
}
Any of these last two would be okay.
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.