为什么我不能使用这个方法的变量?

huangapple go评论76阅读模式
英文:

Why can't I use this method's variable?

问题

我刚开始学习Java,遇到了一些问题:

  • 我正在尝试制作一个将摄氏度转换为华氏度的程序。
  • 我无法在第二个类中使用第一个对象的变量 c。为什么?
  • 我想知道如何使用 BufferedReader 对象和 try-catch 语句询问用户是否想要转换为摄氏度还是华氏度。
class Temperatura {
    private double tempF, tempC;
    
    public void setFarenheit(double f) {
        tempF = f;
    }
    
    public void setCelsius(double c) {
        tempC = c;
    }
    
    // Convierte de grados C a grados F
    public double celsiusToFarenheit() {
        return (1.8 * tempC) + 32;
    }
    
    // Convierte de grados F a grados C
    public double farenheitToCelsius() {
        return (tempF - 32) / 1.8;
    }
}

class TemperaturaPrueba {
    public static void main(String[] args) {
        Temperatura convTemp;
        convTemp = new Temperatura();

        convTemp.setCelsius(100);
        convTemp.setFarenheit(212);

        System.out.println(c + " grados Celsius son " +
            convTemp.celsiusToFarenheit() + " grados Farenheit");

        System.out.println(f + " grados Farenheit son " +
            convTemp.farenheitToCelsius() + " grados Celsius");
    }
}

注意:在提供的代码中,缺少变量 cf 的定义,这可能会导致编译错误。

英文:

I'm just starting on Java and I came across some problems:

  • I'm trying to make a program to convert Celsius to Farenheit

  • I can't use the variable c from the first object on my second class. Why?

  • I would like to know how can I ask the user to input wether they would like to convert it to Celsius or Farenheit, using a BufferedReader object and a try-catch statement.

    Class temperatura {
         private double tempF, tempC;
         public void setFarenheit(double f) {
         tempF = f;
         }
         public void setCelsius(double c) {
         tempC = c;
         }
         // Convierte de grados C a grados F
         public double celsiusToFarenheit() {
         return (1.8*tempC)+32;
         }
         // Convierte de grados F a grados C
         public double farenheitToCelsius() {
         return (tempF-32)/1.8;
         }
         }
    
    class TemperaturaPrueba {
         public static void main(String[] args) {
    
         Temperatura convTemp;
         convTemp = new Temperatura();
    
         convTemp.setCelsius(100);
         convTemp.setFarenheit(212);
    
         System.out.println(c + " grados Celsius son " +
         convTemp.celsiusToFarenheit() + " grados Farenheit");
    
         System.out.println(f + " grados Farenheit son " +
         convTemp.farenheitToCelsius() + " grados Celsius");
         }
         }
    

答案1

得分: 3

Sure, here's the translated content:

[![在这里输入图片描述][1]][1]

> 我不能在第一个对象中使用变量 c 在我的第二个类中。为什么?

是的,这与变量作用域有关。你所指的 tempC 变量在你的主方法中是不存在的(见图片)。但是你的主方法有对堆中的 `Temperatura` 对象的引用。所以,你可以在 Temperature 类中添加一个 getter 方法,就像这样:

```java
public double getCelsius(){
     return tempC;
}

然后在你的主方法中获取值并使用它:

convTemp.getCelsius();

> 我想知道如何让用户输入是否要将温度转换为摄氏度还是华氏度,使用 BufferedReader 对象和 try-catch 语句。

对于这个问题,一个简单的谷歌搜索会帮助你。一些链接:https://www.tutorialspoint.com/how-to-read-integers-from-a-file-using-bufferedreader-in-java

示例:

boolean isValidInput = false;
do {
   try{
      BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
      System.out.println("输入摄氏度:");
      int celsius = Integer.parseInt(reader.readLine());
      isValidInput = true;
   } catch(Exception e){
       System.out.println("无效的输入,请重试");
   }
} while(!isValidInput);

<details>
<summary>英文:</summary>

[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/xto3k.png

&gt; I can&#39;t use the variable c from the first object on my second class. Why?

Yes, it has to do with the variable scopes. The tempC variable you are referring to is not present in your main method (see the image). But your main method has the reference to `Temperatura` object in the heap. So, you could add a getter method 

like

public double getCelsius(){
return tempC;
}

to the Temperature class and get the value in your main method and use it.

convTemp.getCelsius();


&gt; I would like to know how can I ask the user to input wether they would like to convert it to Celsius or Farenheit, using a BufferedReader object and a try-catch statement.

And for this question, a simple google search will help you. Some links: https://www.tutorialspoint.com/how-to-read-integers-from-a-file-using-bufferedreader-in-java

sample:

boolean isValidInput = false;
do {
try{
BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter celsius: ");
int celsius = Integer.parseInt(reader.readLine());
isValidInput = true;
} catch(Exception e){
System.out.println("Invalid input, please try again");
}
} while(!isValidInput);


</details>



# 答案2
**得分**: 1

```java
You have to either make tempC and tempF a public field or you have to write getter methods.

    Class temperatura {
         public double tempF, tempC;  /* I have made these fields public */
    
         public void setFarenheit(double f) {
           tempF = f;
         }
         public void setCelsius(double c) {
           tempC = c;
         }
    
         // Convierte de grados C a grados F
         public double celsiusToFarenheit() {
            return (1.8*tempC)+32;
         }
    
         // Convierte de grados F a grados C
         public double farenheitToCelsius() {
            return (tempF-32)/1.8;
         }
    }
    
    
    class TemperaturaPrueba {
    
           public static void main(String[] args) {
    
           Temperatura convTemp;
           convTemp = new Temperatura();
    
           convTemp.setCelsius(100);
           convTemp.setFarenheit(212);
    
           //Note that I have changed the c and f references to actual field names
    
           System.out.println(convTemp.tempC + " grados Celsius son " +
           convTemp.celsiusToFarenheit() + " grados Farenheit");
    
           System.out.println(convTemp.tempF + " grados Farenheit son " +
           convTemp.farenheitToCelsius() + " grados Celsius");
         }
      }
英文:

You have to either make tempC and tempF a public field or you have to write getter methods.

Class temperatura {
     public double tempF, tempC;  /* I have made these fields public */

     public void setFarenheit(double f) {
       tempF = f;
     }
     public void setCelsius(double c) {
       tempC = c;
     }

     // Convierte de grados C a grados F
     public double celsiusToFarenheit() {
        return (1.8*tempC)+32;
     }

     // Convierte de grados F a grados C
     public double farenheitToCelsius() {
        return (tempF-32)/1.8;
     }
}


class TemperaturaPrueba {

       public static void main(String[] args) {

       Temperatura convTemp;
       convTemp = new Temperatura();

       convTemp.setCelsius(100);
       convTemp.setFarenheit(212);

       //Note that I have changed the c and f references to actual field names

       System.out.println(convTemp.tempC + &quot; grados Celsius son &quot; +
       convTemp.celsiusToFarenheit() + &quot; grados Farenheit&quot;);

       System.out.println(convTemp.tempF + &quot; grados Farenheit son &quot; +
       convTemp.farenheitToCelsius() + &quot; grados Celsius&quot;);
     }
  }

答案3

得分: 1

从您的代码中,变量'c'和'f'在温度类中被用作局部变量,因此作为参数使用,它们的访问范围仅限于函数内部。与此相反,您可以使用带有温度类对象的变量tempF和tempC。

另外,关于您的第二个问题,您想要获取用户的选择,您可以使用Scanner或其他输入方法,在接收用户选择后,您可以使用switch语句来调用您的函数。以下是您可以实现的代码示例:

import java.util.Scanner;
public class HelloWorld {

    public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);  // 创建一个Scanner对象
       System.out.println("Enter Your Choice");
       System.out.println("1.F to c \n2.c to f");
       String choice = sc.nextLine(); // 读取用户输入
    
       switch(choice) {
           case "1":
             // 代码块
             break;
           case "2":
             // 代码块
             break;
           default:
             // 代码块
       }
    }
}

这不是实际的代码,但这是您需要运行项目的格式。

英文:

From Your code the variable 'c' & 'f' you are using in class temperatura are local so variables which are used as parameters so their access scope is limited within the function.
Instead of that you can use the variables tempF, tempC with object of class temperatura

also for your second question you want to get user's choice you can use Scanner or other input method after taking user choice you can use switch statement to call your functions
here the code how you can do it

import java.util.Scanner;
public class HelloWorld{

public static void main(String []args){
   Scanner sc = new Scanner(System.in);  // Create a Scanner object
   System.out.println(&quot;Enter Your Choice&quot;);
   System.out.println(&quot;1.F to c \n2.c to f&quot;);
   String choice = sc.nextLine();//Read User Input

switch(choice) {
   case x:
     // code block
     break;
   case y:
     // code block
     break;
   default:
    // code block
  }

 }
}

This is not actual code but this is the format you needed to run your project

huangapple
  • 本文由 发表于 2020年9月10日 00:34:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/63815897.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定