Geometry Area Calculator - java

I am trying to make an area calculator in Java that will calculate the area of a triangle based on given dimensions by the user. I can get the user to select the triangle option from a menu and enter their dimensions but when I try to use a method to calculate the area, it only prints out 0.0.
{
Scanner tbaseChoice = new Scanner(System.in);
System.out.println("What is the base?");
double selectionb = tbaseChoice.nextDouble();
tbaseChoice.equals(Tbase);
Scanner theightChoice = new Scanner(System.in);
System.out.println("What is the height?");
double selectionh = theightChoice.nextDouble();
theightChoice.equals(Theight);
System.out.println("BASE:" + selectionb + " " + "HEIGHT:" + selectionh);
//tbaseChoice.equals(Tbase);
//theightChoice.equals(Theight);
}
public static void calculateArea() {
double triangleArea = Theight * Tbase;
System.out.print("Area=" + triangleArea);
}

The problem is that you shouldn't be using the equals method of the Scannerclass to assign values to the Theight and Tbase variables. You should instead be using the = assignment operator to do so instead. So replace theightChoice.equals(Theight); with
Theight = selectionh;
and tbaseChoice.equals(Tbase); with
Tbase = selectionb;
Why your code wasn't working before can be seen from this link, https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)
The equals method in the Scanner class is inherited from Java's Object class, which simply just returns a boolean. In your code before, you were checking to see if a Scanner object was equal to another object, but nothing was being done with the boolean value returned. Therefore, your Tbase and Theight variables weren't changing.

You can try with these code. Maybe this will help you
public class AreaCalculator {
static double base=0.0;
static double height=0.0;
public static void main(String args[]){
//Scanner object for input
Scanner scanner=new Scanner(System.in);
System.out.println("What is the base?");
base=scanner.nextDouble();
System.out.println("What is the height?");
height=scanner.nextDouble();
System.out.println("BASE:" + base + " " + "HEIGHT:" + height);
System.out.println("Area is: "+triangleArea());
}
public static double triangleArea(){
return (.5*base*height);
}
}

Related

Problems with scanning in java

I got a task, where I have to calculate the perimeter and area of a given object, that's determined by the user, with accompanying data - side length, radius, etc. To do this I have to do a "GUI" as my teacher said, and to do that, I have to use the Scanner.
Everytime I try to do the second scan, after the user has choosen what object we are dealing with, when it gets to the part, where the user's supposed to input their data about their object, it always crashes, with a java.util.NoSuchElementException error, according to NetBeans. I looked through it, and even copied in the working scanner, but to no avail.
Here's the full code:
package Methods2;
import java.util.Scanner;
public class Methods2 {
public static void main(String[] args) {
//initialization
int decider;
Scanner input1;
//defining
input1 = new Scanner(System.in);
System.out.println("Choose from these options to find the perimeter and area of any of these:\n1. Circle\n2. Square\n3. Rectangle");
decider = input1.nextInt();
input1.close();
//decision
if (decider == 1) {
circle();
} else if (decider == 2) {
square();
} else if (decider == 3) {
rectangle();
} else {
System.out.println("There aren't any other options, other than these three.");
}
}
public static void circle() {
//method specific initialization
int radius;
double pi;
double perimeter;
double area;
Scanner input2;
//define
pi = 3.14;
input2 = new Scanner(System.in);
System.out.println("Please type in the radius of the circle!");
radius = input2.nextInt(); //these are where my problem's lie
input2.close();
//calculate
perimeter = 2 * radius * pi;
area = radius * radius * pi;
//print
System.out.println("The perimeter of this circle is: " + perimeter);
System.out.println("The area of this circle is: " + area);
}
public static void square() {
//method specific initialization
int a;
int perimeter;
int area;
Scanner input3;
//define
input3 = new Scanner(System.in);
System.out.println("Please type in one side's length of the square!");
a = input3.nextInt(); //these are where my problem's lie
input3.close();
//calculate
perimeter = 4 * a;
area = a * a;
//print
System.out.println("The perimeter of this circle is: " + perimeter);
System.out.println("The area of this circle is: " + area);
}
public static void rectangle() {
//method specific initialization
int a;
int b;
int perimeter;
int area;
Scanner input4;
//define
input4 = new Scanner(System.in);
System.out.println("Please type in one of the sides' length of the rectangle!");
a = input4.nextInt(); //these are where my problem's lie
System.out.println("Now type the other, non-equal side, compared to the previous one!");
b = input4.nextInt(); //these are where my problem's lie
input4.close();
//calculate
perimeter = 2 * (a + b);
area = a * b;
//print
System.out.println("The perimeter of this circle is: " + perimeter);
System.out.println("The area of this circle is: " + area);
}
}
I have thought about it being multiple Scanner's, but after I realized, that variables don't carry over between methods, unless they're defined within the class, that was swiftly thrown out as a theory. Also, NetBeans didn't mark any problems with that line, so it made even less sense to me.
The reason why your code is "stopping" the scanner, is because you added input1.close();. What .close() does, is that it closes the scanner. Once a scanner is closed, you won't be able to open it again. According to your code, you use the Scanner.. even after it was closed. So to fix your problem, removed the line:
input1.close();
Here is a close up of where you should remove the line:
//initialization
int decider;
Scanner input1;
//defining
input1 = new Scanner(System.in);
System.out.println("Choose from these options to find the perimeter and area of any of these:\n1. Circle\n2. Square\n3. Rectangle");
decider = input1.nextInt();
//input1.close(); REMOVE THIS LINE

How to print a static method in java that takes an int as parameter and returns a double

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));
}

How do I use the return value from a method in another method different from the calling method?

I'm kinda new to to java and stumbled on a problem that needs me to do currency conversion declaring different methods for:
getting amount, getting conversion rate, doing the actual conversion and printing the outcome of the conversion
import java.util.*;
public class Conver {
public static void main(String[] args){
amountToConvert();
exchangeRate();
convert();
}
public static double amountToConvert() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount you wish to convert...");
double amount = input.nextDouble();
return amount;
}
public static double exchangeRate(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the currency you wish to convert from... ");
String initialCurrency = input.next();
System.out.println("Enter the currency you wish to convert from... ");
String finalCurrency = input.next();
System.out.println("How many " + initialCurrency + " makes one " + finalCurrency + "?");
double rate = input.nextDouble();
return rate;
}
public static double convert(){
int x = amount*rate;
return x;
}
public void printResult(){
System.out.println(x);
}
}
Learn to use parameters in the methods. Change the convert() method so that it looks like this:
public static double convert(double amount, double rate){
int x = amount*rate;
return x;
}
In the method above, double amount and double rate are the parameters. Use variables to help pass in parameters to convert() in the main method:
public static void main(String[] args){
double amount1 = amountToConvert();
double rate1 = exchangeRate();
double result = convert(amount1, rate1);
printResult(result);
}
Hope this helps!
Pass returned values to the method convert:
import java.util.*;
public class Conver {
public static void main(String[] args){
double amount = amountToConvert();
double rate = exchangeRate();
double result = convert(amount, rate);
printResult(result);
}
public static double amountToConvert() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount you wish to convert...");
double amount = input.nextDouble();
return amount;
}
public static double exchangeRate(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the currency you wish to convert from... ");
String initialCurrency = input.next();
System.out.println("Enter the currency you wish to convert from... ");
String finalCurrency = input.next();
System.out.println("How many " + initialCurrency + " makes one " + finalCurrency + "?");
double rate = input.nextDouble();
return rate;
}
public static double convert(double amount, double rate){
double x = amount * rate;
return x;
}
public void printResult(double x){
System.out.println(x);
}
}
Also, don't use double for money!
First off, you need to change the "receiving method" so that it takes an argument. A method like:
public static double convert() {}
that needs to take in a value for amount and rate, needs to have those added to the method signature:
public static double convert (double amount, double rate) {}
Putting the two comma separated values inside of the parens means that this method takes two values, doubles, as arguments. This makes those values available to use inside of that method.
Now that you have a method that can take the required arguments, you need to actually use that method in your code. When calling this method, you start out the same as with others:
convert(
but then you need to add in the arguments you are using:
double amount = amountToConvert();
double rate = exchangeRate();
convert(rate, amount);
If you want to avoid creating those two additional variables in main(), you can actually call those methods inside of your new method:
convert(amountToConvert(), exchangeRate());

My variables are not initializing properly

In my code below double getAirSpeed double calcPatternwidth and double calcPatternLength are not being initialized properly, why?
/**
* holding patterns
* assignment 1
* question 2
**/
import java.util.Scanner;
public class StockiColeA1Q2 {
public static void main(String []args) {
Scanner keyboard = new Scanner(System.in);
double getAirSpeed ;
double calcPatternWidth;
double calcPatternLength;
System.out.println("That speed is " + getAirSpeed +
"\nHolding pattern width: " + calcPatternWidth +
"kms\nHolding pattern length: " + calcPatternLength + "kms");
}//main
public static double getAirSpeed() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the speed in Knots: ");
double knots = keyboard.nextDouble(); //knots given by user
return knots*1.852;
}//get air speed
public static double calcPatternWidth(double knots) {
return (knots/60*Math.PI)*2;
}//patern width
public static double calcPatternLength(double knots) {
return knots/60 + (knots/60*Math.PI)*2;
}//pattern width
}//class
You aren't properly initializing the variables in main. You show call the functions and assign them up front and then display them. I think what you were looking for was a main that looked liked this:
public static void main(String[] args) {
double getAirSpeed = getAirSpeed();
double calcPatternWidth = calcPatternWidth(getAirSpeed);
double calcPatternLength = calcPatternLength(getAirSpeed);
System.out.println("That speed is " + getAirSpeed + "\nHolding pattern width: " + calcPatternWidth
+ "kms\nHolding pattern length: " + calcPatternLength + "kms");
}// main
The code above uses the getAirSpeed as a parameter to calcPatternWidth and calcPatternLength. I am guessing that was what you intended to accomplish.
You really should close the Scanner object when finished so I'd amend getAirSpeed() to call keyboard.close() before returning.
public static double getAirSpeed() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the speed in Knots: ");
double knots = keyboard.nextDouble(); // knots given by user
keyboard.close();
return knots * 1.852;
}// get air speed
Here I am not able to see where you are initializing the given variables. As all three vairables are local to main method so compiler will not assign the default value to them. just creating getter of those variable will not assign the value. If you create the variable out side the main method in class the compiler will assign the defaut value but you have to make them static as main method is static and you cannot use non-static variable inside the static block.

Getting NaN when using get method

I'm making an BMI calculator for a diet programming I'm making for a piece of coursework. Originally I was making a a couple variables public static to get variables from another class. My BMI calculator worked fine this way.
I then figured out that I could use a get method (for more marks). So I changed by the previous variables to private and used a get method. But when I run this program I get NaN when the program prints out the the variable that holds the BMI, this never happened before!
Can anyone help?
import java.util.Scanner;
public class Weight {
private Scanner input;
private String readInput;
private String userWeightIsPounds;
private String userWeightIsStones;
private Scanner input2;
public static double userWeight;
public Weight(){
userWeightIsPounds = ("Pounds");
userWeightIsStones = ("Stones");
}
public void findOutUserWeightMessage(){
System.out.println("Firstly Do you weigh yourself in pounds or stones?");
}
public void findOutUserWeight(){
input = new Scanner (System.in);
readInput = input.nextLine();
if(readInput.equals(userWeightIsPounds)){
System.out.println("Ok then, enter your weight in pounds please.");
}
if(readInput.equals(userWeightIsStones)){
System.out.println("Ok enter your weight in stones please.");
}
input2 = new Scanner (System.in);
userWeight = input2.nextFloat();
if (userWeight > 20){
System.out.println("You've enetered your weight as " + userWeight + " lbs. I'll save that information for later.");
}else{
userWeight = userWeight * 14;
System.out.println("I've converted your weight into pounds for you. You weigh " + userWeight + " lbs. I'll save that information for later.");
}
}
public double static getUserWeight(){
return userWeight;
}
}
And there is come code the the class that does the calculations. Ignore some of the println's I was trying to find out what was happening with my variables.
public class BMI {
private double userHeightSqaured;
private double bmiMutiplier;
private double weightDivideHeight;
private double userBmi;
private double userWeightBmi;
private double userHeightBmi;
BMI(){
bmiMutiplier = 703;
userWeightBmi = Weight.getUserWeight();
userHeightBmi = Height.getUserHeight();
}
public void startUpBmiMessage(){
System.out.print("Lets start with your BMI then shall we? ");
}
public void calculateUserBmi(){
System.out.println("userWeightBmi is " + userWeightBmi);
System.out.println("userWeightBmi is " + userHeightSqaured);
userHeightSqaured = userHeightBmi * userHeightBmi;
System.out.println("userHeightSqaured is " + userHeightSqaured);
weightDivideHeight = userWeightBmi/userHeightSqaured;
System.out.println("weightDivideHeight is " + weightDivideHeight);
userBmi = weightDivideHeight * bmiMutiplier;
System.out.println("weightDivideHeight is " + weightDivideHeight);
System.out.println("bmiMutiplier is " + bmiMutiplier);
}
public void calculateUserBmiMessage(){
System.out.println("Your bmi is " + userBmi);
}
}
It sounds like you're trying to write a Java program that performs some calculations, and the result of your calculation is NaN - you can refer to the question In Java, what does NaN mean? for some info on NaN.
As for resolving your problem without seeing any code, and assuming your calculation worked fine with the same input before, it sounds like your switch from public static variables to private ones with getters has probably left some of your variables uninitialized, so their value defaults to 0 - Division by 0 is a common cause of NaN.
The reason for the NaN is that this statement:
weightDivideHeight = userWeightBmi/userHeightSqaured;
divided zero by zero. In other words userWeightBmi and userHeightSqaured were both zero at that point.
The root problem seems to be that you haven't got your head around the difference between static and instance variables. And when you should / should not use the two kinds of variable.

Categories