簡體   English   中英

帶有switch語句的效率,Java

[英]Efficieny with switch Statements, Java

最近,我開發了一個程序,要求用戶輸入年齡(年,月和日)。

收到輸入后,它必須進行計算和打印

a)以秒為單位的年齡(totalAgeInSecs)和

b)剩余的秒數。 b將基於以秒為單位的平均壽命(avgLifeSpan = 250000000000l. So secondsLeft = avgLifeSpan - totalAgeInSecs)

無論如何,為了簡單起見,我能夠使程序能夠使用(switch)語句來工作,而不必編寫一堆if / else語句,但是我覺得這樣做的結果是,我最終寫了重復的行, d不必重復計算或打印語句。

我知道有些類和數組可以與循環結合使用,但是為了簡單起見和邏輯理解,我沒有用它們來理解“英語”這個項目的無骨骨骼和邏輯。 哈哈。

無論如何,請查看下面的代碼,讓我知道您對如何簡化重復性代碼或實現此目的的更好方法的想法。 謝謝。

import java.util.*;

public class AgeInSeconds {

    static Scanner kbd = new Scanner(System.in);
    public static void main(String[] args) {

        int totalNumDays, daysInMonth, daysToHours;
        int yrsToDays,minsInHr, secsInMin;

        long timeRemaining, avgLifeSecs;

        System.out.println("Enter your age in years months and days: ");

        System.out.print("Years: ");
        int years = kbd.nextInt();

        System.out.print("Months: ");
        int months = kbd.nextInt();

        System.out.print("Days: ");
        int days = kbd.nextInt();

        yrsToDays = years * 365;
        avgLifeSecs = 2500000000l;

        switch (months){
        case 1: 
            daysInMonth = 31;
            totalNumDays = yrsToDays + daysInMonth + days;
            daysToHours = totalNumDays * 24;
            minsInHr = daysToHours * 60;
            secsInMin = minsInHr * 60;

            timeRemaining = avgLifeSecs - secsInMin;

            System.out.printf("You have been alive for %,d seconds.\n", secsInMin);
            System.out.printf("The average human life is  %,d seconds.\n", avgLifeSecs);
            System.out.printf("You have  %,d seconds.\n", timeRemaining);           
            break;
        case 2: 
            daysInMonth = 59;
            totalNumDays = yrsToDays + daysInMonth + days;
            daysToHours = totalNumDays * 24;
            minsInHr = daysToHours * 60;
            secsInMin = minsInHr * 60;

            timeRemaining = avgLifeSecs - secsInMin;    

            System.out.printf("You have been alive for %,d seconds.\n", secsInMin);
            System.out.printf("The average human life is  %,d seconds.\n", avgLifeSecs);
            System.out.printf("You have  %,d seconds.\n", timeRemaining);
            break;      
        case 3: 
            daysInMonth = 90;
            totalNumDays = yrsToDays + daysInMonth + days;
            daysToHours = totalNumDays * 24;
            minsInHr = daysToHours * 60;
            secsInMin = minsInHr * 60;

            timeRemaining = avgLifeSecs - secsInMin;

            System.out.printf("You have been alive for %,d seconds.\n", secsInMin);
            System.out.printf("The average human life is  %,d seconds.\n", avgLifeSecs);
            System.out.printf("You have  %,d seconds.\n", timeRemaining);
            break;      
        case 4: 
            daysInMonth = 120;
            totalNumDays = yrsToDays + daysInMonth + days;
            daysToHours = totalNumDays * 24;
            minsInHr = daysToHours * 60;
            secsInMin = minsInHr * 60;

            timeRemaining = avgLifeSecs - secsInMin;

            System.out.printf("You have been alive for %,d seconds.\n", secsInMin);
            System.out.printf("The average human life is  %,d seconds.\n", avgLifeSecs);
            System.out.printf("You have  %,d seconds.\n", timeRemaining);
            break;      
        case 5:
            daysInMonth = 151;
            totalNumDays = yrsToDays + daysInMonth + days;
            daysToHours = totalNumDays * 24;
            minsInHr = daysToHours * 60;
            secsInMin = minsInHr * 60;

            timeRemaining = avgLifeSecs - secsInMin;

            System.out.printf("You have been alive for %,d seconds.\n", secsInMin);
            System.out.printf("The average human life is  %,d seconds.\n", avgLifeSecs);
            System.out.printf("You have  %,d seconds.\n", timeRemaining);
            break;      
        case 6: 
            daysInMonth = 181;
            totalNumDays = yrsToDays + daysInMonth + days;
            daysToHours = totalNumDays * 24;
            minsInHr = daysToHours * 60;
            secsInMin = minsInHr * 60;

            timeRemaining = avgLifeSecs - secsInMin;
            System.out.printf("You have been alive for %,d seconds.\n", secsInMin);
            System.out.printf("The average human life is  %,d seconds.\n", avgLifeSecs);
            System.out.printf("You have  %,d seconds.\n", timeRemaining);           
            break;      
        case 7: 
            daysInMonth = 212;
            totalNumDays = yrsToDays + daysInMonth + days;
            daysToHours = totalNumDays * 24;
            minsInHr = daysToHours * 60;
            secsInMin = minsInHr * 60;

            timeRemaining = avgLifeSecs - secsInMin;
            System.out.printf("You have been alive for %,d seconds.\n", secsInMin);
            System.out.printf("The average human life is  %,d seconds.\n", avgLifeSecs);
            System.out.printf("You have  %,d seconds.\n", timeRemaining);       
            break;      
        case 8: 
            daysInMonth = 243;
            totalNumDays = yrsToDays + daysInMonth + days;
            daysToHours = totalNumDays * 24;
            minsInHr = daysToHours * 60;
            secsInMin = minsInHr * 60;

            timeRemaining = avgLifeSecs - secsInMin;
            System.out.printf("You have been alive for %,d seconds.\n", secsInMin);
            System.out.printf("The average human life is  %,d seconds.\n", avgLifeSecs);
            System.out.printf("You have  %,d seconds.\n", timeRemaining);

            break;

        case 9: 
            daysInMonth = 273;
            totalNumDays = yrsToDays + daysInMonth + days;
            daysToHours = totalNumDays * 24;
            minsInHr = daysToHours * 60;
            secsInMin = minsInHr * 60;

            timeRemaining = avgLifeSecs - secsInMin;
            System.out.printf("You have been alive for %,d seconds.\n", secsInMin);
            System.out.printf("The average human life is  %,d seconds.\n", avgLifeSecs);
            System.out.printf("You have  %,d seconds.\n", timeRemaining);           
            break;      
        case 10: 
            daysInMonth = 304;
            totalNumDays = yrsToDays + daysInMonth + days;
            daysToHours = totalNumDays * 24;
            minsInHr = daysToHours * 60;
            secsInMin = minsInHr * 60;

            timeRemaining = avgLifeSecs - secsInMin;
            System.out.printf("You have been alive for %,d seconds.\n", secsInMin);
            System.out.printf("The average human life is  %,d seconds.\n", avgLifeSecs);
            System.out.printf("You have  %,d seconds.\n", timeRemaining);           
            break;          
        case 11: 
            daysInMonth = 334;
            totalNumDays = yrsToDays + daysInMonth + days;
            daysToHours = totalNumDays * 24;
            minsInHr = daysToHours * 60;
            secsInMin = minsInHr * 60;
            timeRemaining = avgLifeSecs - secsInMin;

            System.out.printf("You have been alive for %,d seconds.\n", secsInMin);
            System.out.printf("The average human life is  %,d seconds.\n", avgLifeSecs);
            System.out.printf("You have  %,d seconds.\n", timeRemaining);
            break;      
        case 12:
            daysInMonth = 365;
            totalNumDays = yrsToDays + daysInMonth + days;
            daysToHours = totalNumDays * 24;
            minsInHr = daysToHours * 60;
            secsInMin = minsInHr * 60;

            timeRemaining = avgLifeSecs - secsInMin;

            System.out.printf("You have been alive for %,d seconds.\n", secsInMin);
            System.out.printf("The average human life is  %,d seconds.\n", avgLifeSecs);
            System.out.printf("You have  %,d seconds.\n", timeRemaining);

        default:

        }

        kbd.close();    

    }


}

在以下情況下為輸出:年= 24,月= 5,天= 8。

Enter your age in years months and days: 
Years: 24
Months: 5
Days: 8
You have been alive for 770,601,600 seconds.
The average human life is  2,500,000,000 seconds.
You have  1,729,398,400 seconds.

要正確計算用戶的存活天數,您應該首先根據提供的數據和今天的日期計算其生日。 例如:

  • 用戶的年齡為1個月,當前日期為2015年9月28日,因此該用戶出生於2015年8月28日,年齡為31天。
  • 用戶的年齡為1個月,當前日期為2015年3月2日,因此該用戶出生於2015年2月2日,年齡為28天。

之后,您可以計算秒數差異。 Java API中有准備好的類和方法來執行這些步驟。 最簡單的是使用Java 8 Time API:

import java.time.LocalDateTime;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.util.Scanner;

public class AgeInSeconds {

    public static void main(String[] args) {
        try (Scanner kbd = new Scanner(System.in)) {

            System.out.println("Enter your age in years months and days: ");

            System.out.print("Years: ");
            int years = kbd.nextInt();

            System.out.print("Months: ");
            int months = kbd.nextInt();

            System.out.print("Days: ");
            int days = kbd.nextInt();

            Period period = Period.of(years, months, days);
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime birthDate = now.minus(period);
            long seconds = birthDate.until(now, ChronoUnit.SECONDS);
            long avgLifeSecs = 2500000000l;
            long timeRemaining = avgLifeSecs - seconds;

            System.out.printf("You have been alive for %,d seconds.\n", seconds);
            System.out.printf("The average human life is  %,d seconds.\n", avgLifeSecs);
            System.out.printf("You have  %,d seconds.\n", timeRemaining);
        }
    }
}

我在這里不解決統計問題。 要計算估計的剩余壽命(假設我是普通人),您應該平均比我死的人的壽命。

您的整數daysInMonth將轉移通過switch語句。 因此,您只需在switch語句之后使用重復代碼即可。

經驗法則:當重復代碼時,將其放在自己的方法中,或者合並代碼,以便只需要在一個位置調用它。

import java.util.*;

public class AgeInSeconds {

static Scanner kbd = new Scanner(System.in);
public static void main(String[] args) {

    int totalNumDays, daysInMonth, daysToHours;
    int yrsToDays,minsInHr, secsInMin;

    long timeRemaining, avgLifeSecs;

    System.out.println("Enter your age in years months and days: ");

    System.out.print("Years: ");
    int years = kbd.nextInt();

    System.out.print("Months: ");
    int months = kbd.nextInt();

    System.out.print("Days: ");
    int days = kbd.nextInt();

    yrsToDays = years * 365;
    avgLifeSecs = 2500000000l;

    switch (months){
    case 1: 
        daysInMonth = 31;
        break;
    case 2: 
        daysInMonth = 59;
        break;      
    case 3: 
        daysInMonth = 90;
        break;      
    case 4: 
        daysInMonth = 120;
        break;      
    case 5:
        daysInMonth = 151;
        break;      
    case 6: 
        daysInMonth = 181;
        break;      
    case 7: 
        daysInMonth = 212;
        break;      
    case 8: 
        daysInMonth = 243;
        break;

    case 9: 
        daysInMonth = 273;
        break;      
    case 10: 
        daysInMonth = 304;
        break;          
    case 11: 
        daysInMonth = 334;
        break;      
    case 12:
        daysInMonth = 365;
        break;
    default:
        daysInMonth = 0;
    }
    totalNumDays = yrsToDays + daysInMonth + days;
    daysToHours = totalNumDays * 24;
    minsInHr = daysToHours * 60;
    secsInMin = minsInHr * 60;

    timeRemaining = avgLifeSecs - secsInMin;

    System.out.printf("You have been alive for %,d seconds.\n", secsInMin);
    System.out.printf("The average human life is  %,d seconds.\n", avgLifeSecs);
    System.out.printf("You have  %,d seconds.\n", timeRemaining);           

    kbd.close();    

}


}

上面是代碼的“快速而骯臟的”解決方案,因此您可以看到如何通過switch語句傳遞變量。

更好的做法是使用模運算符檢查它是奇數還是偶數,如果不是第二個月,則給出正確的值。

import java.util.*;

public class AgeInSeconds {

static Scanner kbd = new Scanner(System.in);
public static void main(String[] args) {

    int totalNumDays, daysInMonth, daysToHours;
    int yrsToDays,minsInHr, secsInMin;

    long timeRemaining, avgLifeSecs;

    System.out.println("Enter your age in years months and days: ");

    System.out.print("Years: ");
    int years = kbd.nextInt();

    System.out.print("Months: ");
    int months = kbd.nextInt();

    System.out.print("Days: ");
    int days = kbd.nextInt();

    yrsToDays = years * 365;
    avgLifeSecs = 2500000000l;
    /** predifine with 0 so we always have a value **/
    daysInMonth = 0;
    /** Our months here. Please consider using calendar **/
    int[] legaldays =  {31,28,31,30,31,30,31,31,30,31,30,31};
    /** Looping through all months **/
    for(i=0;i<legaldays.length;i++) { 
       /** check if we didn't pass our max limit **/
       if(i+1 > daysInMonth) {
          break;
       }
       /** add the days to our tally **/
       daysInMonth += legaldays[i];
    }
    totalNumDays = yrsToDays + daysInMonth + days;
    daysToHours = totalNumDays * 24;
    minsInHr = daysToHours * 60;
    secsInMin = minsInHr * 60;

    timeRemaining = avgLifeSecs - secsInMin;

    System.out.printf("You have been alive for %,d seconds.\n", secsInMin);
    System.out.printf("The average human life is  %,d seconds.\n", avgLifeSecs);
    System.out.printf("You have  %,d seconds.\n", timeRemaining);           

    kbd.close();    

   }    
}

查看評論以了解我如何進行改進。 通過循環,您不必為硬編碼幾個月內的值而煩惱,它為您提供了一定的靈活性。 為了獲得更可靠的天數而不是硬編碼,我建議您查看特定年份一個月中的天數,以便靈活使用leap年。

只要有可能,就不要對無形或動態數據值進行硬編碼,而是嘗試准確地推導它們。 眾所周知,日期很難保持秩序。

暫無
暫無

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

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