Altering Variables in a void method?

a 夏天 提交于 2019-12-11 09:14:03

问题


I need to set the temperature class, and need to alter the degrees in a void method.

How do I access these variables in a void method, and ensure that the void method alters the parameters into the variables that I need?

I need the degrees to be converted, and I don't know how to access the degree variable not in the set class?

Temperature (double enteredtemp,char scale ){
   degrees=Temperature.set();    
}

public void set (double enteredtemp, char scale){
       if (scale=='r'||scale=='R'){ degrees=(enteredtemp/(9/5));}
       else if (scale=='c'|| scale=='C') {degrees=enteredtemp+273.15;}
       else if (scale=='F'||scale=='f'){degrees=((enteredtemp+459.67)*9/5);}

回答1:


The good practice is - do NOT use static methods or static variables unless it is necessary or you are sure it is good way how to do it.

In your case, you can do someting like this:

public class Temperature{
   private double temperature;

   public Temperature(double temperature){
      this.temperature = temperature;
   }

   public void addOneDegree(){
     temperature = temperature+1;
   }

   public double getTemperature(){
     return temperature;
   }
}

public class MyGreatProgramForTemperature{
    public static void main(String [] args){
      double testingTemp;
      Temperature temperature = new Temperature(50);
      testingTemp = temperature.getTemperature();
      System.out.println(testingTemp); //it prints 50
      temperature.addOneDegree();
      testingTemp = temperature.getTemperature();
      System.out.println(testingTemp); //it prints 51
    }
}

Also note, that you should have each class in different file.




回答2:


I suppose the snippet you posted is inside a class, that has a "degrees" member. In that case you're on the right track.

For example :

public class Temperature {
    private double degrees;
    public Temperature (double enteredtemp,char scale ) {
        degrees=Temperature.set(enteredtemp, scale);
    }

    public void set (double enteredtemp, char scale) {
        if (scale=='r'||scale=='R'){ degrees=(enteredtemp/(9/5));}
        else if (scale=='c'|| scale=='C') {degrees=enteredtemp+273.15;}
        else if (scale=='F'||scale=='f'){degrees=((enteredtemp+459.67)*9/5);
    }

    public double getDegrees() {
        return degrees;
    }   
}

This is a functioning class, apart for conversions that i didn't check and some coding conventions about method names that we can debate about :)

Just to make sure you understand how to USE this class, for example inside a main method :

Temperature t = new Temperature(25,'c');
System.out.println("Temperature F " + t.getDegrees());
t.set(30,'c');
System.out.println("Temperature F " + t.getDegrees());



回答3:


Within methods, variables in Java are block-scoped meaning you either need to pass an object's reference to your set method (and alter the object's value in your method), either need it to return something (which doesn't seem to be what you want since you specified you want it void).

Please explain why exactly you want your set method to return void. It seems you do some computations in it, I think it would me much more appropriate as a compute or a calculate method since set methods (also known as setters) have very specific meanings in Java as well as in lots of other programming languages (specifically OOP ones).

Could it be something like :

public double computeDegrees(double enteredtemp, char scale) {
        double degrees = 0;
        if (scale=='r'||scale=='R'){ degrees=(enteredtemp/(9/5));}
        else if (scale=='c'|| scale=='C') {degrees=enteredtemp+273.15;}
        else if (scale=='F'||scale=='f'){degrees=((enteredtemp+459.67)*9/5);
        return degrees;
    }

Found your code on another thread, here's the fixed version. Please try to understand it and ask questions in comments if you have any. I think the biggest mistake you've made was trying to instantiate a Temperature object inside the constructor of your Temperature class (ultimately creating a stack overflow ^^). When you are inside a method (arguably a constructor is a method), use the keyword this to refer the object invoking the method (inside a constructor this refers to the object being instantiated).

public class Temperature {

    public double degrees;

    public static void main(String[] args) {
        // This is an example
        Temperature myTemperature = new Temperature(28, 'C');
        System.out.println("My temperature is " + myTemperature.get());
        Temperature myOhterTemperature = new Temperature(25, 'C');
        boolean greaterThan = myTemperature.isGreaterThan(myOhterTemperature);
        System.out.println(greaterThan); // should be true since 28 > 25
    }


    Temperature () {
        degrees=0;
    }

    Temperature (double enteredtemp) {
        degrees = enteredtemp;
    }

    Temperature (double enteredtemp,char scale ) {
        set(enteredtemp,scale);
    }

    public void set (double enteredtemp, char scale){
        if (scale == 'r'|| scale == 'R'){ degrees = (enteredtemp/(9/5));}
        else if (scale == 'c'|| scale == 'C') {degrees = enteredtemp+273.15;}
        else if (scale =='F'|| scale == 'f'){degrees = ((enteredtemp+459.67)*9/5);}
    }

    public double get() {
        return degrees;
    }

    public double get(char scale) {
        if (scale == 'c'|| scale == 'C'){degrees = (degrees-273.15);}
        else if (scale == 'r'||scale == 'R'){degrees = (degrees*(9/5));}
        else if (scale == 'f'|| scale == 'F'){degrees = (degrees*(9/5)-459.67);}
        return degrees;
    }


    public boolean isLessThan(Temperature t) {
        if (this.get() < t.get()) {
            return true;
        } else {
            return false;
        }
    }

    public boolean isGreaterThan(Temperature t) {
        if (this.get() > t.get()) {
            return true;
        } else {
            return false;
        }
    }
    public boolean isEqual(Temperature t){
        if ((Math.abs(this.get() - t.get())) <= 10E-12) {
            return true;
        } else {
            return false;
        }
    }

    public boolean isGreaterThanOrEqual(Temperature t){
        if (this.get() >= t.get()){
            return true;
        } else {
            return false;
        }
    }

    public boolean isLessThanorEqual(Temperature t){
        if (this.get() <= t.get()) {
            return true;
        } else {
            return false;
        }
    }
}


EDIT : Just noticed your double get(char scale) method actually modifies the degrees property of the Temperature instance whose invoked that method. This is really BAD choice of wording, please re-read my above lines about mutators (getters and setters). A getter should almost never modify any value and especially not any property of the class calling the getter ! If I were to use such a Temperature class, I certainly would expect the returned value to be a copy of the degrees value hold by my Temperature instance converted to the given scale.

Also noticed in this comment that your professor hates switch, break, and won't let you use case. If this same prof gave you this code base as it is, please change school.




回答4:


You are implementing a setter, whose responsibility will be to change the value of degrees. Setters typically have a void return value - this means they don't return anything at all.

This code you posted looks like an 'ok' setter:

public void set (double enteredtemp, char scale){
       if (scale=='r'||scale=='R'){ degrees=(enteredtemp/(9/5));}
       else if (scale=='c'|| scale=='C') {degrees=enteredtemp+273.15;}
       else if (scale=='F'||scale=='f'){degrees=((enteredtemp+459.67)*9/5);}

However, the way you are calling it in your constructor is completely wrong. This line does not make any sense:

degrees=Temperature.set();

Remember your set function returns void, so attempting to assign that value to degrees isn't going to work. Moreover it completely misses the point of calling the setter (which is to have the set function assign the value to degrees). Another issue is that you are calling set() as if its a static method - its not (and if it was, it would again miss the point of using a setter).

The correct way to call your set function from your constructor is:

Temperature (double enteredtemp,char scale )
{
    set(enteredtemp, scale)
}

Another example...

Temperature temp = new Temperature(98.6, 'F');   // normal temp
temp.set(102, 'F');                              // now we've got a fever


来源:https://stackoverflow.com/questions/25703477/altering-variables-in-a-void-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!