gpt4 book ai didi

java - 如何获取 for 循环迭代内生成的值并在其外部以相同的方法使用它们?

转载 作者:行者123 更新时间:2023-12-01 17:58:42 25 4
gpt4 key购买 nike

我希望能够从 for 循环中取出值,并为 for 循环的单独迭代生成单独的值,以便我可以将它们放入 for 循环下面的比较 if/else 语句中。

public static void calculateBirthdays(Scanner console) {
//Print purpose
System.out.println("This program compares two birthdays");
System.out.println("and displays which one is sooner.");

Calendar cal = Calendar.getInstance();
int todayYear = cal.get(Calendar.YEAR);
int todayMonth = cal.get(Calendar.MONTH)+1;
int todayDay = cal.get(Calendar.DAY_OF_MONTH);

SimpleDateFormat d = new SimpleDateFormat();

int todayDayValue = absDayVal(todayMonth, todayDay, todayYear);

System.out.println("Today is " + d.format(cal.getTime()) + ", day #" + todayDayValue + " of the year.");

for (int i = 1; i <= 2; i++) {
System.out.println("Person " + i + ":\nWhat month, day and year were you born?");

int month = console.nextInt();
int day = console.nextInt();
int year = console.nextInt();

int daysPassed = absDayVal(month, day, year);
int daysInYear = leapYear(todayYear);

int daysUntilBday = daysAway(daysPassed, todayDayValue, daysInYear);

DecimalFormat df = new DecimalFormat("0.##");

System.out.println(month + "/" + day + "/" + todayYear + " falls on day #" + todayDayValue + " of " + daysInYear + ".");

if(todayDayValue == daysPassed){
System.out.println("Happy birthday!");
} else if (todayDayValue != daysPassed){
System.out.println("Your next birthday is in " + daysUntilBday + " day(s).");
System.out.println("That is " + df.format((percentUntil(daysUntilBday, daysInYear)) * 100) + " percent of a year away.");
}
}

if(percent < percent) {
System.out.println("Person 1's birthday is sooner.");
} else if (percent < percent) {
System.out.println("Person 2's birthday is sooner.");
} else if (percent == percent) {
System.out.println("Wow, you share the same birthday!");
}


}

最佳答案

您可以像这样在循环之外简单地声明它们。

int month;
int day;
int year;

for (int i = 1; i <= 2; i++) {
System.out.println("Person " + i + ":\nWhat month, day and year were you born?");

month = console.nextInt();
day = console.nextInt();
year = console.nextInt();
...
}

这个概念称为范围Here is an article这可能会让您更好地理解变量范围。

关于java - 如何获取 for 循环迭代内生成的值并在其外部以相同的方法使用它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60671638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com