温度单位转换java程序问题

这个程序部分的运行结果是
Enter a number to choose one of the following options:

1.Convert temperatures one at a time.
2.Convert temperature from a list of values in a .txt file.
3.End the program
1
You select 1
Enter temperature:
f
Please enter a number!
Enter temperature:
c
Please enter a number!
Enter temperature:
20
Enter scale:
f
Enter scale to convert to (F, C, K, R):
c
122.0 is -6.666666666666666c
Would you like to do another conversion? (y/n):

可以看到我输入温度是20,但打印出来是122.0,自动加上了102,还不带单位,有人帮忙看看是为什么吗?

import java.util.Scanner;
import java.io.*;


/**
 * TemperatureConversion provides static methods that allow temperatures to be
 * converted between 4 scales: celsius, fahrenheit, kelvin, rankine.
 * Name: Xiangcheng Ding
 * UniqueID: DINGX11
 * Instructor: Dr. Deepak Dawar
 * Course number and section: CSE271 Lab1
 *
 * @author Jill Courte
 * @modified Laurie Werner
 * @version 1.1
 */
public class TemperatureConversion
{
    public final static char FAHRENHEIT = 'F';
    public final static char CELSIUS = 'C';
    public final static char KELVIN = 'K';
    public final static char RANKINE = 'R';



    /**
     * Given a double value in fahrenheit and a scale, converts the value to that scale.
     * @param value - the fahrenheit value to be converted
     * @param scale - the target scale - one of 'F', 'C', 'K', 'R'
     */
    public double fahrenheitToOther (double value, char scale) {
        double newValue = 0;
        if(scale == FAHRENHEIT || scale== 'f'){
        }else if(scale == CELSIUS || scale == 'c'){
            newValue=(value-32)/1.8;
        } else if (scale == KELVIN || scale == 'k') {
            newValue=(value-32)/1.8+273.15;
        } else if (scale == RANKINE || scale == 'r') {
            newValue=value+459.67;
        }else {
            return 0.0;
        }
        return newValue;
    }


    /**
     * Given a double value in celsius and a scale, converts the value to that scale.
     * @param value - the celsius value to be converted
     * @param scale - the target scale - one of 'F', 'C', 'K', 'R'
     */
    public double celsiusToOther (double value, char scale) {
        double newValue=0;
        if (scale == CELSIUS || scale == 'c') {
        } else if (scale == FAHRENHEIT || scale == 'f') {
            newValue = (value * 1.8) + 32;
        } else if (scale == KELVIN || scale == 'k') {
            newValue = value + 273.15;
        } else if (scale == RANKINE || scale == 'r') {
            newValue = value * 1.8 + 32 + 459.67;
        } else {
            return 0.0;
        }
        return newValue;
    }


    /**
     * Given a double value in kelvin and a scale, converts the value to that scale.
     * @param value - the kelvin value to be converted
     * @param scale - the target scale - one of 'F', 'C', 'K', 'R'
     */
    public double kelvinToOther (double value, char scale) {
        double newValue=0;
        if (scale == KELVIN || scale == 'k') {
        } else if (scale == FAHRENHEIT || scale == 'f') {
            newValue = (value - 273.15) * 1.8 + 32;
        } else if (scale == CELSIUS || scale == 'c') {
            newValue = value - 273.15;
        } else if (scale == RANKINE || scale == 'r') {
            newValue = value * 1.8;
        } else {
            return 0.0;
        }
        return newValue;
    }


    /**
     * Given a double value in rankine and a scale, converts the value to that scale.
     * @param value - the rankine value to be converted
     * @param scale - the target scale - one of 'F', 'C', 'K', 'R'
     */
    public double rankineToOther (double value, char scale) {
        double newValue=0;
        if (scale == RANKINE || scale == 'r') {
        } else if (scale == FAHRENHEIT || scale == 'f') {
            newValue = value-459.76;
        } else if (scale == KELVIN || scale == 'k') {
            newValue = value/1.8;
        } else if (scale == CELSIUS || scale == 'c') {
            newValue = (value-32-459.67)/1.8;
        } else {
            return 0.0;
        }
        return newValue;
    }

    /**
     * Given a double value and its associated scale, and a new scale,
     * converts the given value from the original scale to the new scale.
     * Each scale shoud be one of 'F', 'C', 'K', 'R' (fahranheit, celsius, kelvin, rankine)
     * @param originalValue - the  value to be converted
     * @param originalScale - the scale of the original value
     * @param newScale - the target scale
     */
    public double doConversion (double originalValue, char originalScale, char newScale)
    {
        double newValue = 0.0;
        if (originalScale == CELSIUS || originalScale == 'c') {
                newValue = celsiusToOther(originalValue, newScale);
            } else if (originalScale == KELVIN || originalScale == 'k') {
                newValue = kelvinToOther(originalValue, newScale);
            } else if (originalScale == FAHRENHEIT || originalScale == 'f') {
                newValue = fahrenheitToOther(originalValue, newScale);
            } else if (originalScale == RANKINE || originalScale == 'r') {
                newValue = rankineToOther(originalValue, newScale);
            }
        return newValue;
    }




    public static void main (String [] args)
    {
        boolean repeat, repeat2=true, repeat3=true, repeat4 = true;
        double temp = 0;
        char scale;
        while(repeat2){
            repeat = true;
            int option;
            Scanner in = new Scanner(System.in);
            System.out.println("Enter a number to choose one of the following options:\n" +
                    "\n" +
                    "1.Convert temperatures one at a time.\n" +
                    "2.Convert temperature from a list of values in a .txt file.\n" +
                    "3.End the program");
            while(repeat){
                        if (in.hasNextInt()) {
                            option = in.nextInt();
                            if (option == 1) {
                                    System.out.println("You select 1");
                                    do {
                                        boolean isNotDoble = true;
                                        while (isNotDoble) {
                                            in = new Scanner(System.in);
                                            System.out.println("Enter temperature: ");
                                            if (in.hasNextDouble()) {
                                                temp = in.nextDouble();
                                                isNotDoble = false;
                                            } else {
                                                System.out.println("Please enter a number!");
                                            }
                                        }
                                        in = new Scanner(System.in);
                                        System.out.println("Enter scale: ");
                                        scale = in.next().charAt(0);
                                        in = new Scanner(System.in);
                                        System.out.println("Enter scale to convert to (F, C, K, R): ");
                                        char newScale = in.next().charAt(0);
                                        TemperatureConversion Conversion = new TemperatureConversion();
                                        double newTemp = Conversion.doConversion(temp, scale, newScale);
                                        if (newTemp == 0.0) {
                                            System.out.println("Please enter proper scales!");
                                        } else {
                                            System.out.println(temp + scale + " is " + newTemp + newScale);
                                            repeat3 = false;
                                        }
                                    } while (repeat3);
                                    in = new Scanner(System.in);
                                    System.out.println("Would you like to do another conversion? (y/n): ");
                                    String yes = in.next();
                                    if (yes.equals("y") || yes.equals("Y")) {
                                        break;
                                    } else if (yes.equals("n") || yes.equals("N")) {
                                        repeat = false;
                                    } else {
                                        System.out.println("Please enter 'y' or 'n'.");
                                    }
                            } else if (option == 2) {
                                try {
                                        String fileName;
                                        in = new Scanner(System.in);
                                        System.out.print("Please enter a file name: ");
                                        fileName = in.next();
                                        File inputFile = new File(fileName);
                                        in = new Scanner(inputFile);
                                        double[] temps = new double[0];
                                        char[] scales = new char[0];
                                        char[] newScales = new char[0];
                                        int i = 0, j = 0, k = 0;
                                        while(in.hasNextDouble()){
                                          temps[i] = in.nextDouble();
                                          i++;
                                        }
                                        in.close();
                                        in = new Scanner(inputFile);
                                        while (in.hasNext()){
                                            scales[j]=in.next().charAt(0);
                                            in.next();
                                            j++;
                                        }
                                        in.close();
                                        in = new Scanner(inputFile);
                                        while(in.hasNext()){
                                            in.next();
                                            newScales[k] = in.next().charAt(0);
                                            k++;
                                        }
                                        in.close();
                                        TemperatureConversion conversion = new TemperatureConversion();
                                        double[] newTemps = new double[0];
                                        for(int a = 0; a <= i; a++){
                                          newTemps[a] = conversion.doConversion(temps[a],scales[a],newScales[a]);
                                          if (newTemps[a] == 0){
                                              System.out.println("error invalid original scale specified " + scales[a]);
                                          }else{
                                              System.out.println(temps[a] + scales[a] + " is " + newTemps[a] + newScales[a]);
                                          }
                                        }

                                }catch (IOException exception){
                                    exception.printStackTrace();
                                }
                            } else if (option == 3) {
                                System.out.println("Goodbye");
                                repeat = false;
                                repeat2 = false;
                            } else {
                                System.out.println("Please enter 1, 2, or 3!");
                                System.out.println("");
                                repeat = false;
                            }
                        } else{
                            System.out.println("Please enter 1, 2, or 3!");
                            System.out.println("");
                            repeat = false;
                        }
                    }
                }
            }
        }


问题出在这段代码块中:

while (in.hasNextDouble()){
    temps[i] = in.nextDouble();
    i++;
}

你在使用数组temps之前没有为其分配内存空间,因此会导致数组越界异常。你需要在读取文件之前定义一个足够大的数组,以存储读取的温度值。

同样的问题也存在于scalesnewScales数组的使用中。

解决方法是在读取文件之前,为这些数组分配正确的大小,例如:

double[] temps = new double[10];
char[] scales = new char[10];
char[] newScales = new char[10];

请根据你的需要选择适当的数组大小。在这个例子中,我将数组大小设置为10。你可以根据实际情况进行调整。


如果以上回答对您有所帮助,点击一下采纳该答案~谢谢

  • 问题

    img

  • 解决
System.out.println(temp+"" + scale + " is " + newTemp + newScale);
  • 原理
    在Java中,char类型和double类型是可以自动相加的。当char类型和double类型进行相加运算时,char类型会被隐式地转换为其对应的Unicode编码值,然后与double类型进行相加。这是因为char类型在内部表示为Unicode编码值,而double类型是一种浮点数类型。
    例如,如果有以下代码:
char c = 'A';
double d = 3.14;
System.out.println(c + d);

输出将会是:

68.14
  • 如果解决您的问题,希望采纳一下啦

引用 皆我百晓生 小程序回复内容作答:
你好!根据你提供的代码,问题出现在doConversion方法中。在该方法中,当originalScale'C''c'时,newValue的值没有被赋值,因此默认为0.0。这就导致返回的newValue0.0,而不是正确的转换结果。

为了解决这个问题,你应该修改doConversion方法中每个条件分支的初始化newValue的方式。这样,无论originalScale的值是多少,都可以正确地计算并返回newValue

下面是修改后的doConversion方法的代码:

public double doConversion(double originalValue, char originalScale, char newScale) {
    double newValue = 0.0;
    if (originalScale == CELSIUS || originalScale == 'c') {
        newValue = celsiusToOther(originalValue, newScale);
    } else if (originalScale == KELVIN || originalScale == 'k') {
        newValue = kelvinToOther(originalValue, newScale);
    } else if (originalScale == FAHRENHEIT || originalScale == 'f') {
        newValue = fahrenheitToOther(originalValue, newScale);
    } else if (originalScale == ANKINE || originalScale == 'r') {
        newValue = rankineToOther(originalValue, newScale);
    }
    return newValue;
}

希望这可以解决你的问题!如果还有任何疑问,请随时提问。

【以下回答由 GPT 生成】

问题出在方法fahrenheitToOther的逻辑上,当scale为FAHRENHEIT或者'f'的时候,没有对newValue进行赋值,导致返回值始终为0.0。同时,也没有在每个分支中加入返回值的语句。

以下是修复后的代码:

import java.util.Scanner;
import java.io.*;

/**
 * TemperatureConversion provides static methods that allow temperatures to be
 * converted between 4 scales: celsius, fahrenheit, kelvin, rankine.
 * Name: Xiangcheng Ding
 * UniqueID: DINGX11
 * Instructor: Dr. Deepak Dawar
 * Course number and section: CSE271 Lab1
 *
 * @autho Jill Courte
 * @modified Laurie Werner
 * @version 1.1
 */
public class TemperatureConversion{
    public final static char FAHRENHEIT = 'F';
    public final static char CELSIUS = 'C';
    public final static char KELVIN = 'K';
    public final static char RANKINE = 'R';

    /**
     * Given a double value in fahrenheit and a scale, converts the value to that scale.
     * @param value - the fahrenheit value to be converted
     * @param scale - the target scale - one of 'F', 'C', 'K', 'R'
     * @return the converted value
     */
    public double fahrenheitToOther (double value, char scale) {
        double newValue = 0;
        if(scale==FAHRENHEIT || scale=='f'){
            newValue = value;
        }else if(scale==CELSIUS || scale == 'c'){
            newValue=(value-32)/1.8;
        } else if (scale == KELVIN || scale == 'k') {
            newValue=(value-32)/1.8+273.15;
        } else if (scale == RANKINE || scale == 'r') {
            newValue=value+459.67;
        }else {
            return 0.0;
        }
        return newValue;
    }
}

修复后的代码在每个分支中给newValue赋值,并且在方法的结束处返回newValue的值。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^