在 void 方法中更改变量? [英] Altering Variables in a void method?

查看:38
本文介绍了在 void 方法中更改变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要设置温度等级,并且需要在 void 方法中更改度数.

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

如何在 void 方法中访问这些变量,并确保 void 方法将参数更改为我需要的变量?

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

推荐答案

您正在实现一个 setter,其职责是更改度的值.Setter 通常有一个 void 返回值 - 这意味着它们根本不返回任何内容.

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.

您发布的此代码看起来像一个确定"的 setter:

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

请记住,您的 set 函数返回 void,因此尝试将该值分配给度数是行不通的.此外,它完全忽略了调用 setter 的要点(即让 set 函数将值分配给度数).另一个问题是您调用 set() 就好像它是一个静态方法 - 它不是(如果是,它会再次错过使用 setter 的意义).

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).

从构造函数调用 set 函数的正确方法是:

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

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

另一个例子...

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

这篇关于在 void 方法中更改变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆