简体   繁体   English

带有switch语句的效率,Java

[英]Efficieny with switch Statements, Java

I recently worked on a program that asked the user for his age in: years, months, and days. 最近,我开发了一个程序,要求用户输入年龄(年,月和日)。

After receiving that input, it had to calculate and print 收到输入后,它必须进行计算和打印

a) Age in Seconds (totalAgeInSecs) and a)以秒为单位的年龄(totalAgeInSecs)和

b) the Amount of Seconds left to live. b)剩余的秒数。 b is going to be based on the average lifespan in seconds (avgLifeSpan = 250000000000l. So secondsLeft = avgLifeSpan - totalAgeInSecs) . b将基于以秒为单位的平均寿命(avgLifeSpan = 250000000000l. So secondsLeft = avgLifeSpan - totalAgeInSecs)

Anyway,I was able to get the program to work utilizing (switch) statements for simplicity purposes and not having to write a bunch of if/else statements, but I feel that in doing that, I ended up writing repetitive lines, and I'd like to be able to not have to repeat the calculation or the print statements. 无论如何,为了简单起见,我能够使程序能够使用(switch)语句来工作,而不必编写一堆if / else语句,但是我觉得这样做的结果是,我最终写了重复的行, d不必重复计算或打印语句。

I know there are classes and arrays I can combine with loops, but for the sake of simplicity and logic understanding I didn't use them to understand the bareback bones and logic of this project in "English." 我知道有些类和数组可以与循环结合使用,但是为了简单起见和逻辑理解,我没有用它们来理解“英语”这个项目的无骨骨骼和逻辑。 haha. 哈哈。

Anyway, check the code out below and let me know your thoughts on how to simplify the repetitive lines or better ways of approaching this. 无论如何,请查看下面的代码,让我知道您对如何简化重复性代码或实现此目的的更好方法的想法。 Thanks. 谢谢。

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();    

    }


}

This is the output when: years = 24, months = 5, days = 8. 在以下情况下为输出:年= 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.

To correctly calculate how many days the user is alive, you should first calculate his birthdate based on the supplied data and today's date. 要正确计算用户的存活天数,您应该首先根据提供的数据和今天的日期计算其生日。 For example: 例如:

  • User is 1 month old, current date is Sept 28th 2015, thus user was born at Aug 28th 2015 and he is 31 days old. 用户的年龄为1个月,当前日期为2015年9月28日,因此该用户出生于2015年8月28日,年龄为31天。
  • User is 1 month old, current date is March 2nd 2015, thus user was born at Feb 2nd 2015 and he is 28 days old. 用户的年龄为1个月,当前日期为2015年3月2日,因此该用户出生于2015年2月2日,年龄为28天。

After that you can calculate the difference in seconds. 之后,您可以计算秒数差异。 There are ready classes and methods in Java API to do these steps. Java API中有准备好的类和方法来执行这些步骤。 The easiest is to use Java 8 Time 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);
        }
    }
}

I'm not addressing the statistical problem here. 我在这里不解决统计问题。 To calculate estimate remaining lifespan (provided I'm an average person) you should average the lifespan of the people who died older than me. 要计算估计的剩余寿命(假设我是普通人),您应该平均比我死的人的寿命。

Your integer daysInMonth will transfer past the switch statement. 您的整数daysInMonth将转移通过switch语句。 So you can just utilise the repetitive code after the switch statement. 因此,您只需在switch语句之后使用重复代码即可。

As a rule of thumb: When you have repeating code put it in it's own method, or cosolidate the code so you only need to call it at one spot. 经验法则:当重复代码时,将其放在自己的方法中,或者合并代码,以便只需要在一个位置调用它。

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();    

}


}

The above is a "quick and dirty" solution to your code so you can see how you can transfer variables past an switch statement. 上面是代码的“快速而肮脏的”解决方案,因此您可以看到如何通过switch语句传递变量。

Better practise it would be to use an modulus operator to check if it's odd or even and if it's not month two, give the correct value. 更好的做法是使用模运算符检查它是奇数还是偶数,如果不是第二个月,则给出正确的值。

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();    

   }    
}

See the comments to know how I improved it. 查看评论以了解我如何进行改进。 By looping you take yourself off the headache of having to hardcode the values of the months days and it gives you an amount of flexibility. 通过循环,您不必为硬编码几个月内的值而烦恼,它为您提供了一定的灵活性。 For a more reliable day count instead of hardcode I suggest you look at Number of days in a month of a particular year so you can be flexible with leap years and such. 为了获得更可靠的天数而不是硬编码,我建议您查看特定年份一个月中的天数,以便灵活使用leap年。

When ever possible try to not hardcode intangible or dynamic data values, but try to deduct them accurately. 只要有可能,就不要对无形或动态数据值进行硬编码,而是尝试准确地推导它们。 Dates are notoriously hard to keep in order. 众所周知,日期很难保持秩序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM