如何从另一个

时间:2017-05-15 23:05:51

标签: java

我正在尝试进行温度转换,我知道我需要在main中调用convertTemp,但我只是不知道我在做什么。有人可以看看这个并帮助我吗?

import java.util.Scanner;

public class TemperatureConverter {

  public static void convertTemp() {
       Scanner keyboard = new Scanner(System.in);
       double temperature;
       String temperatureScale = " ";

     if (temperatureScale.equals("f"))
     {    
     // code that converts from Fahrenheit to Celsius 
        temperature = (5/9)*(keyboard.nextDouble() - 32);   
     // and prints the result to the screen  
        System.out.println("The temperature is " + temperature + "degrees celsius");
     }
        //
     else if (temperatureScale.equals("c")) 
     {       
     // code that converts from Celsius to Fahrenheit    
        temperature = 32.0 +(keyboard.nextDouble() * 1.8);
        System.out.println("The temperature is " + temperature + "degrees fahrenheit");
     // and prints the result to the screen 
     } 
     else 
     {    
     // code that outputs a message indicating that an incorrect 
        System.out.println("Error! A valid temperature was not chosen!");   
     // option was selected 
     } 
    }

  public static void main(String[] args) {
     Scanner keyboard = new Scanner(System.in);
     System.out.println("What temeprature number are you trying to find out?"); 
     double keyboardInput = keyboard.nextDouble();


     System.out.println("Type f for Fahrenheit or c for Celsius.");
     String keyboardTempLetter = keyboard.next(); 

   }

  }
 //}

2 个答案:

答案 0 :(得分:0)

您需要将用户输入发送到convertTemp方法,以便方法检查它然后返回结果或打印它就像您一样。

问题是您通过添加

在方法中初始化 temperatureScale 温度
 double temperature;
`String temperatureScale = " "; `

因此该方法使用它们而不是用户插入的内容。

第二个问题convertTemp方法没有收到userinput

convertTemp(没有在这里收到)。

你甚至没有从主

发送输入的第三个问题

首先你的方法应该有:

convertTemp(String  temperatureScale,double temperature) 

然后删除temperatureScale和温度的初始化,如上所述也删除

`   Scanner keyboard = new Scanner(System.in);` 

从convertTemp开始,你在main

中初始化了它

最后以这种方式在main方法中调用方法: -

convertTemp(keyboardInputkeyboardInput,keyboardTempLetter);

答案 1 :(得分:0)

我建议不要在convertTemp方法中调用scanner,将字符或字符串和数字作为参数传递。那么你只需要像这样调用你主体中的函数:

    convertTemp(double keyboardInput, String keyboardTempLetter);