package tempconverter;
import java.util.*;
import java.util.Scanner;
public class TempConverter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double tem;
System.out.print("Enter number: ");
double temp = sc.nextDouble();
System.out.println("Convert to Celsius or Fahrenheit (C or F): ");
int input = sc.nextInt();
if (input == 'C'){
System.out.println("Fahrenheit to Celcius is: " + toCelsius(temp));
}else if(input == 'F'){
toFahrenheit(temp);
}
public static double toCelsius(double cels){
double far = 5/9.0*(cels-32);
return far;
}
public static void toFahrenheit(double fahr){
double tem = 9/5.0*fahr+32;
System.out.println("Celsius to Fahrenheit: " + toFahrenheit(tem));
}
}
答案 0 :(得分:0)
主要问题是代码中有一个循环。 toFahrenheit的方法在println中再次调用toFahrenheit。这会导致无限循环,从而在某个时候导致堆栈溢出。将println移到方法的外部(如toCelsius一样)并返回转换后的值。
除此之外,您还遇到了“ C”和“ F”的问题。
答案 1 :(得分:0)
我重构了您的代码。您在其中一个方法中进行了递归调用,而您的方法未返回值。
public static void main(String[] args) {
String name = null;
float temperature;
Scanner in = new Scanner(System.in);
System.out.println("Enter temperature: " );
temperature = in.nextFloat();
System.out.println("Convert to Celsius or Fahrenheit (C or F): ");
name = in.next();
if (name.equals("C")) {
System.out.println("Fahrenheit to Celcius: " + toCelsius(temperature));
}else if (name.equals("F")){
System.out.println("Celsius to Fahrenheit: " + toFahrenheit(temperature));
}
}
public static double toCelsius(double cels){
double far = 5/9.0*(cels-32);
return far;
}
public static double toFahrenheit(double fahr){
double tem = 9/5.0*fahr+32;
return tem;
}