Convert Height to Inches (Java) - java

I am having issues with the output of my code. Seems I am missing something in my method that I created... I had instructions to return the total number of inches. I places totInches after return and get an error stating that totInches is not a variable. Not certain what is missing here as I am only supposed to be creating a method. Most of this code was written and the only portion I was supposed to created was the second convertToInches method.. Any advice?
import java.util.Scanner;
public class FunctionOverloadToInches {
public static double convertToInches(double numFeet) {
return numFeet * 12.0;
}
public static double convertToInches(double numFeet, double numInches) {
return totInches * 12.0;
}
public static void main (String [] args) {
double totInches = 0.0;
totInches = convertToInches(4.0, 6.0);
System.out.println("4.0, 6.0 yields " + totInches);
totInches = convertToInches(5.9);
System.out.println("5.9 yields " + totInches);
return;
}
}

The variable totInches is not defined in the scope of your function:
public static double convertToInches(double numFeet, double numInches) {
return totInches * 12.0;
}
The only variables you can use in this function are the ones you create and the ones defined as formal parameters: numFeet and numInches. So you have to come up with an equation that takes numFeet and converts it to inches, taking into account the additional inches provided in numInches.

You declared the double variable "totInches" inside of your main method, but you are trying to access it inside of your "convertToInches" method. When declaring a variable in a particular method, that variable is ONLY accessible by that method. Your "convertToInches" knows of only two variables: numFeet and numInches, which you passed to it in the parameter. It then looks at your return statement, sees "totInches" and has no idea what it is.
I also don't understand what this is trying to do...
public static double convertToInches(double numFeet, double numInches) {
return totInches * 12.0;
}
Why are you passing it the double variables numFeet and numInches? The function isn't using them. I also don't understand why you need both the number of feet AND the number of inches if the method, by its name, is trying to convert something into inches.

public static double convertToInches(double numFeet, double numInches) {
return (numFeet * 12) + numInches;
This takes into account any variable amount entered by user for height of 5 feet 7 inches or 6 feet even

Related

Can someone correct my code over here? Also, can someone tell me the proper way to define a function in Java?

This code does not run when I try to compile it, I am sure it is because I
defined my function/method incorrectly, so it would be much appreciated if
someone can correct my code and also tell me what is wrong with it.
I know C++ so I tried to define the function like how I would define it
normally in Cpp but with a few tweaks. I really don't know what I am doing
right now.
class Calculator {
public static void main(String[] arguments) {
float Celcius;
float Farenheit = 32;
final float k = 5 / 9;
System.out.println("This is the temperature in degrees celsius: " +
Converter(Farenheit));
public float Converter(float Farenheit) {
return 5 / 9 * (Farenheit - 32);
}
}
}
So the comments noted the key issues. The method cannot be within main. 5/9=0 in Java. Here is a little program I just checked on jdoodle.com. It does what you said in what might be typical Java style (though for sure there are possible improvements and things with which to quibble). For learning Java (which is not the same as for experienced users for development), bluej is an interesting IDE with which to start (specifically because it doesn't do all the work for you). But StackOverflow does not want judgment questions like that, so ignore if you wish.
public class Calculator {
public double converter(double Farenheit) {// convention converter lower case because not a class name
return 5.0 / 9 * (Farenheit - 32); //note 5.0 ensures real number arithmetic, not integer
}
public static void main(String[] arguments) {
Calculator calculator = new Calculator();// make a calculator object, alternative would be to declare converter static
double Farenheit = 32;
System.out.println("This is the temperature in degrees celsius: " +
calculator.converter(Farenheit));
}
}
Your method public float Converter(float Farenheit) is written inside main method . This is not allowed in JAVA . You can however write a anonymous class inside a method and calls its methods .
The correct code is :
class Calculator {
private static final float k = 5.0f / 9;
public static void main(String[] arguments) {
float Celcius;
float Farenheit = 32;
System.out.println("This is the temperature in degrees celsius: " +
Converter(Farenheit));
}
public static float Converter(float Farenheit) {
return k * (Farenheit - 32);
}
}
Please note I have modified Converter method to a static one . We cannot call non static methods from static context in JAVA(as main is static here) . If Converter would have been non static then we would have to create an object of the Calculator class.
Calculator c = new Calculator();
c.Converter(Fahrenheit);
You can declare k as class level variable if it is to be used across multiple methods and has a constant value .
private static final float k = 5.0f / 9;

How to make calculation inside class field in Java?

So I created Saving class, created also setters and getters. Now I need u method, which will calculate the total amount of deposits.
public class Saving {
private double deposits;
private double totalAmountOfDeposits;
public double getDeposits()
{
return deposits;
}
public void setDeposits(double deposits)
{
this.deposits = deposits + deposits;
}
public double getTotalAmountOfDeposits()
{
double total = 0;
return total = total + deposits;
}
}
When I use this class in the program I got a wrong calculation. The program just add first value of deposit to the first value.
import java.util.Scanner;
public class SavingDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Saving save = new Saving();
System.out.println("Deposit amount");
double depositeAmount = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("Deposit amount");
double depositeAmount2 = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("Deposit amount");
double depositeAmount3 = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("The total amount has been deposited is " + save.getTotalAmountOfDeposits());
}
}
And here is the output:
Deposit amount
12
Deposit amount
34
Deposit amount
56
The total amount has been deposited is 24.0
As you can see its just added 12 to 12. Just want to mention that I'm totally new in programming. Les than a month.
I see two problems in your code. Take a look at the commented line. The reason you are seeing 12 + 12 is because that is exactly what you are instructing the JVM to do.
System.out.println("Deposit amount");
double depositeAmount = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("Deposit amount");
double depositeAmount2 = input.nextDouble();
save.setDeposits(depositeAmount); // <= adds the wrong variable
System.out.println("Deposit amount");
double depositeAmount3 = input.nextDouble();
save.setDeposits(depositeAmount); // <= adds the wrong variable
System.out.println("The total amount has been deposited is " + save.getTotalAmountOfDeposits());
Secondly, it looks like you may have a design flaw in your implementation of the Saving class.
You'll want to brush up on variable scope
If you take a look at your implementation on your total:
public double getTotalAmountOfDeposits()
{
double total = 0;
return total = total + deposits;
}
You have the total starting at 0 every time this method getTotalAmountOfDeposits() is called. the total variable in this method is local to it's method. So what you currently have is a method variable
You'll want to do some research into class variable. This will maintain that the instance of the object will have this variable assigned through the life cycle of the instantiated object.
When you have variables of the same name, you can get the instance variable with this keyword.
So when dealing with your setter
public void setSomething(double something) {
this.something // class variable
something // method variable
}
If you want your object to maintain state, you can set it on your object itself, and have your set deposit modify that state. Some pseudo code to get you moving forward.
public class Saving {
private double totalAmountOfDeposits; // you can modify this value with public methods
public void setDeposit(_) {
// Setter implementation
// increment totalAmountOfDeposits;
public double getTotalAmountOfDeposits(_)
// return totalAmountOfDeposits;
}
You should write a method
public void addDeposits(double deposits)
{
this.deposits = this.deposits + deposits;
}
and change setDeposits to
public void setDeposits(double deposits)
{
this.deposits = deposits;
}
after this call addDeposits to add deposits
To eliminate confusion within the Saving Class change the argument name for the setDeposits() method to double newDeposit instead of double deposits which is also a class field name. Although the construct is legal it does make it a wee bit confusing. Inside the setDeposits() method use:
this.deposit+= newDeposit;
As a matter of fact, you can get rid of the deposits field altogether since you also have the field named totalAmountOfDeposits. Use that instead:
this.totalAmountOfDeposits+= newDeposit;
You might also want a clearDeposits() method in your Saving Class:
public void clearDeposits() {
this.totalAmountOfDeposits = 0.0;
}
Your getTotalAmountOfDeposits() method within the Saving Class doesn't really make any sense either. Since you are always summing deposits anyways you can just return what is held within the totalAmountOfDeposits field:
public double getTotalAmountOfDeposits() {
return totalAmountOfDeposits;
}
The above method is would now of course be very mush the same as the getDeposits() method which could be changed to getTotalDeposits(). You can then change the getTotalAmountOfDeposits() method name to getTotalNumberOfDeposits() and add a additional class field named numberOfDeposits:
private double totalAmountOfDeposits;
private int numberOfDeposits = 0;
public double getTotalDeposits() {
return totalAmountOfDeposits;
}
public int getTotalNumberOfDeposits() {
return numberOfDeposits;
}
and in your setDeposits() method add the code line:
numberOfDeposits++;
So that it would look something like:
public void setDeposits(double newDeposit) {
totalAmountOfDeposits+= newDeposit;
numberOfDeposits++;
}
If you do add a clearDeposits() method to your Saving Class then don't forget to add the code line: numberOfDeposits = 0; into that method as well. It might now look something like:
public void clearDeposits() {
totalAmountOfDeposits = 0.0;
numberOfDeposits = 0;
}
You also have some issues within your main() method of your SavingDemo Class. Take a real close look at each call you make to the setDeposits() method for each value the User supplies. Each User supplied value goes into a specific double type variable name. Is that what you are passing to the setDeposits() method? ;)
Once you've got all that taken care of you can display to console:
System.out.println("The total amount has been deposited is " +
save.getTotalDeposits() + " by making " +
save.getTotalNumberOfDeposits() + " deposits.");

Methods not working with tester in java

I'm a newbie coder here currently taking a computer science class based on java. I'm having issues with a program I'm supposed to be writing and I can't seem to figure it out regardless of what I look up, so I'm asking on here.
The instructions say: Create a class. Create a method within the class called printDimensions() that displays the dimensions of a letter-size(8.5x11 inches) sheet of paper in millimeters. There are 25.4 millimeters per inch (constant value). Use constants and comments in the method. It also says (make use of printf to limit the number of decimal places in your method.
As of right now I am stuck in the middle of using the print statement and the return value for the method. I also have a tester that I am using to test the code, but I'm getting BOTH the print statement AND the return value, which I don't believe is correct.
public class Task01
{
// final dimensions of the paper
private double dimensions;
// width of the paper which is 8.5
private double paperWidth;
// length of the paper which is 11
private double paperLength;
public Task01(){
dimensions = 0;
paperLength = 0;
paperWidth = 0;
}
public double printDimensions()
{
final double LENGTH = 11; // inches
final double WIDTH = 8.5; // inches
final double MM_PER_INCH = 25.4; // millimeters per inch
paperLength = LENGTH * MM_PER_INCH;
paperWidth = WIDTH * MM_PER_INCH;
System.out.printf("The dimension are: " + paperLength + " x " + paperWidth);
return dimensions;
}
}
For the tester, I have a seperate class that I use to call the methods I create by creating a new object for that task.
public class Tester
{
public static void main(String[] arg)
{
System.out.println("The task begins now: ");
// creating a new object for the task
Task01 task01 = new Task01();
System.out.println(task01.printDimensions());
}
}
Change this line:
public double printDimensions()
To this
public void printDimensions()
then remove the return statement at the end of that method
You have two options. You can remove the line System.out.printf("The dimension are: " + paperLength + " x " + paperWidth); from the printDimensions methods. Then your tester class just create an instance of Task01 and call the method in a print statement which would look something like this:
public static void main(String[] args) {
Task01 t = new Task01();
System.out.println(t.printDimensions);
}
The other option as already stated is to change the method type to void rather than double and remove the return statement. Then call it like this:
public static void main(String[] args) {
Task01 t = new Task01();
t.printDimensions();
}

Method (correctly) declares variables as 0 but I don't understand why?

I have some code to look at for a class and I understand most of it, but am confused about this method. With the given code, wouldn't the return change always result in 0 since the last thing put in was that the totalOfItems and the totalGiven are 0.0. I was told that when running it that won't happen but I'd like to understand why. Can anyone help me?
public SelfCheckout () {
this.totalOfItems = 0.0;
this.totalGiven = 0.0;
}
/**
* This method will scan the item.
* #param amount The amount the items cost.
*/
public void scanItem (double amount){
this.totalOfItems = this.totalOfItems + amount;
}
/** The method will add the items scanned and return the total due.
*
* #return getTotalDue The getTotalDue is the total amount of items scanned.
*/
public double getTotalDue(){
return this.totalOfItems;
}
/** The method will show the amount that is received from the consumer.
*
*/
public void receivePayment(double amount){
this.totalGiven = this.totalGiven + amount;
}
/**The method will calculate the amount of change due.
*
*/
public double produceChange(){
double change = this.totalGiven - this.totalOfItems;
this.totalGiven = 0.0;
this.totalOfItems = 0.0;
return change;
Statements execute in order. Changes to totalGiven and totalOfItems won't change change after it has been computed.
For this:
double change = this.totalGiven - this.totalOfItems;
this.totalGiven = 0.0;
this.totalOfItems = 0.0;
return change;
first you assign a (non-zero) value to change, then you reset the original variables, and only then return the value of change. The variable values are copied to another variable and then reset.
The assumption I think is that at some point receivePayment and scanItem have already been called so they reassign the field variables to a number that is not zero. Then change is given. The transaction is closed after you have already computed change you reset the variables for the next transaction.

the left hand side of the assignment is not a variable?

I am trying to set this up so my tests will work but I keep getting an error about the left-hand side of the assignment is not a variable on the line starting with 'flunking.gpa...'. Any suggestions as to what i am doing wrong?
/**
* After we have added hours and quality points, we need to
* check that the gpa is (quality points) / hours
*/
#Test
public void gpa() {
flunking.gpa() = flunking.qualityPoints() / (double)flunking.hours();
assertEquals(flunking.gpa(), 0.0, DELTA);
}
You're attempting to assign a value to a method
flunking.gpa() = flunking.qualityPoints() / (double)flunking.hours();
As both qualityPoints and hours contain values within the flunking classs, there's should be no need for any assignment here, i.e. just have gpa return the calculated value in that class as required, e.g.
public double getGPA() {
return qualityPoints / (double)hours;
}
Perhaps there is a flunking.setGpa(newValue) or flunking.gpa(newValue) method to change the value? .gpa() just returns the value and it doesn't make sense to assign to it, technically speaking.

Categories

Resources