簡體   English   中英

請告訴我我做錯了什么,if 語句和轉換不起作用

[英]Please tell me what I'm doing wrong, the if statements and the conversions are not working

我制作了這個程序來將華氏度轉換為攝氏度。 我收到一個編譯錯誤,因為它繞過了 if 語句並且轉換沒有做任何事情。

     package temp;

        import java.util.Scanner;

這是 TheTemp 類

        public class TheTemp {
            private double tempValue;
            private char tempType;
            private static int obj;

此構造函數設置默認的 0 度和攝氏度

        public TheTemp(){
            tempValue = 0;
            obj = 0;
        }

接下來的 3 個構造函數用於導入值......這個

        public void setTemp(double tempValue){
            this.tempValue=tempValue;
        }

這個

        public void setTemp(char t){
            if(t == 'C'||t == 'c'){
                obj = 0;
                tempType = t;
            }
            if(t == 'F'||t == 'f'){
                obj = 1;
                tempType = t;
            }
            else{
                throw new IllegalArgumentException("Choose ether C or F");
            }

        }

和這個

        public void setTemp(char t, double tempValue){

            this.tempValue=tempValue;

            if(t == 'C'||t == 'c'){
                obj = 0;
                tempType = t;
            }
            if(t == 'F'||t == 'f'){
                obj = 1;
                tempType = t;
            }
            else{
                throw new IllegalArgumentException("Choose ether C or F");
            }

        }

這是第一個 if 語句是攝氏度到華氏度的轉換,第二個 if 語句是華氏度到攝氏度的轉換

        public void convertValue(){
            if(obj == 0){
                tempValue = 9*(tempValue/5) + 32;
            }
            if(obj == 1){
                tempValue = 5*(tempValue - 32) / 9;
            }
            else{
                throw new IllegalArgumentException("Choose ether C or F");

            }
        }

        public double getTempValue(){
            return tempValue;
        }

這是測試課程的程序

            public static void main(String[] args) {
                TheTemp A = new TheTemp();
                Scanner kb = new Scanner(System.in);
                double a;

                A.setTemp(55);
                A.convertValue();
                a=A.getTempValue();
                System.out.println(a);
            }

        }

好的,這段代碼在很多方面都很奇怪。

你能說出編譯錯誤到底是什么嗎?

但作為一個開始

 double tempType = 'c';

在您的構造函數中沒有意義,'c' 不是雙精度數。 並且您已在頂部將 tempType 定義為字符,因此如果有任何內容,您的構造函數應如下所示

    public TheTemp(){
        tempType = 'c';
        tempValue = 0;
        obj = 0;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM