使用switch语句的效率,Java

使用switch语句的效率,Java,java,switch-statement,Java,Switch Statement,我最近开发了一个程序,询问用户的年龄:年、月、日 在收到输入后,它必须计算并打印 a) 年龄(秒)(总年龄)和 b) 剩余的生存时间。b将以秒为单位的平均寿命(avgLifeSpan=25000000000l.So secondsLeft=avgLifeSpan-totalageInsenses) 无论如何,为了简单起见,我能够利用(switch)语句使程序工作,而不必编写一堆if/else语句,但我觉得这样做,我最终会编写重复的行,并且我希望能够不必重复计算或打印语句 我知道有一些类和数组可以

我最近开发了一个程序,询问用户的年龄:年、月、日

在收到输入后,它必须计算并打印

a) 年龄(秒)(总年龄)和

b) 剩余的生存时间。b将以秒为单位的平均寿命
(avgLifeSpan=25000000000l.So secondsLeft=avgLifeSpan-totalageInsenses)

无论如何,为了简单起见,我能够利用(switch)语句使程序工作,而不必编写一堆if/else语句,但我觉得这样做,我最终会编写重复的行,并且我希望能够不必重复计算或打印语句

我知道有一些类和数组可以与循环结合,但是为了简单和逻辑理解,我没有用它们来理解这个项目在“英语”中的基本内容和逻辑。哈哈

无论如何,请查看下面的代码,并让我知道您对如何简化重复行或更好地实现这一点的想法。谢谢

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.

您的整数
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();    

   }    
}
import java.util.*;
公共阶级不安全{
静态扫描仪kbd=新扫描仪(System.in);
公共静态void main(字符串[]args){
整数总计numdays、daysInMonth、daystoh;
年内、年内、年内、年内;
剩余时间长,avgLifeSecs;
System.out.println(“以年、月、日为单位输入您的年龄:”;
系统输出打印(“年:”);
int years=kbd.nextInt();
系统输出打印(“月:”);
int months=kbd.nextInt();
系统输出打印(“天:”);
int days=kbd.nextInt();
yrsToDays=年*365;
avgLifeSecs=2500000000l;
/**用0进行预测,所以我们总是有一个值**/
daysInMonth=0;
我们的月份在这里。请考虑使用日历**/
int[]法定日期={31,28,31,30,31,30,31,30,31,31};
/**贯穿所有月份**/

对于(i=0;i要正确计算用户活着的天数,应首先根据提供的数据和今天的日期计算其出生日期。例如:

  • 用户1个月大,当前日期为2015年9月28日,因此用户出生于2015年8月28日,年龄为31天
  • 用户1个月大,当前日期为2015年3月2日,因此用户出生于2015年2月2日,年龄为28天
之后,您可以以秒为单位计算差异。Java API中有现成的类和方法来执行这些步骤。最简单的方法是使用Java 8时间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);
        }
    }
}

这里我不是在讨论统计问题。计算剩余寿命(假设我是一个普通人)你应该计算死亡年龄比我大的人的平均寿命。

在这种情况下,你应该调用一个方法并将整个代码放入其中。闰年呢?顺便说一句,从统计角度来看,程序的结果是不正确的。如果我100岁了呢?我的秒数是负数?这没有意义。这是ind我们需要重复很多代码。还有一个叫做闰年的东西。实际上整个方法是不正确的。如果我1个月大,并不意味着我31天大。根据当前日期,可能是28到31天之间的任意天数。你的代码中有一个大错误。首先,没有人知道他们的年龄,以年、月、日为单位。但是如果ey do:x年和y月是什么意思?如果某人出生在4月或6月,则第二个月没有28天…是否使用数组存储基于1..12(或0..11)的值我考虑过,但是输入无效的例子是什么?加上我还在编辑一些最好的练习。也考虑到OP提出的方法是没有意义的。如果我是X年和5个月的今天,第二个月肯定没有28天。这是半正确答案-在低问题水平。+ 1来自我。坏的问题,答案不能是SP。lendid.BTW变量
daysInMonth
在说谎。理论上,这个问题的目标有很多实现,比如
final int ml[]=…}
if
if在2月份等等……是的,我对这个问题也不满意,但我感觉OP想学习如何编码。看着这些重复的代码,我有点想把我的答案塑造成他的水平,这样他就能理解。显然OP还是个新手,需要一种与有经验的程序员不同的方法.我想你可能对OP有点过分了。我想他在《学会编码》的第一章或第二章;-)回答得不错,+1