gpt4 book ai didi

java - 如何组合 while 循环,以便获得与使用两个 while 循环时相同的输出?

转载 作者:行者123 更新时间:2023-11-29 08:32:42 25 4
gpt4 key购买 nike

我要重新设计一个程序,只用一个循环来判断

every even and odd number between 50 -100.

public class Practice_6_3
{
public static void main(String[] args)
{
int even = 50;
int odd = 51;

System.out.print ("Even numbers between 50 and 100: \t");
while (even <= 100)
{
System.out.print(even + ", ");
even += 2;
}

System.out.print ("\nOdd numbers between 50 and 100: \t");
while (odd <= 100)
{
System.out.print(odd + ", ");
odd += 2;
}
}
}

输出是:50 到 100 之间的偶数:

50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 

50 到 100 之间的奇数:

51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99, 

我不知道如何在保持相同输出格式的同时组合 while 循环。

最佳答案

您需要在循环中构建两个值列表,您可以使用一对 StringJoiner 来完成实例来记录您的 evenodd 值。喜欢,

public static void main(String[] args) {
int even = 50;
StringJoiner evens = new StringJoiner(", ");
StringJoiner odds = new StringJoiner(", ");
while (even <= 100) {
evens.add(String.valueOf(even));
if (even + 1 <= 100) {
odds.add(String.valueOf(even + 1));
}
even += 2;
}

System.out.printf("Even numbers between 50 and 100: \t%s%n", evens);
System.out.printf("Odd numbers between 50 and 100: \t%s%n", odds);
}

哪些输出(按要求)

Even numbers between 50 and 100:    50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100
Odd numbers between 50 and 100: 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99

关于java - 如何组合 while 循环,以便获得与使用两个 while 循环时相同的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46635497/

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