gpt4 book ai didi

java - 如何从打印列表中删除不需要的项目?

转载 作者:行者123 更新时间:2023-12-01 19:33:17 27 4
gpt4 key购买 nike

编写一个 Java 函数,接受整数 n 作为输入,并输出从 1n 的整数字符串,其中每个数字4 的倍数替换为“Hello”,每个 5 的倍数替换为“Wonderful”,每个 7 的倍数替换为“World”。

package Multiple;

import java.util.Scanner;

public class MultipleList {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter an integer number: ");
int n = reader.nextInt();
for (int i = 1; i <= n; i++) {
// Checking if the integer is a multiple of 4
if ((i % 4) == 0) {
// print
System.out.println("Hello");
}
// Checking if the integer is a multiple of 5.
if ((i % 5) == 0) {
// print
System.out.println("Wonderful");
}
// Checking if the integer is a multiple of 7.
if ((i % 7) == 0) {
// print
System.out.println("World");
}
System.out.println(i);
}
}
}

当我输入 n = 7 (例如)时,我期望输出“1, 2, 3, Hello, Wonderful, 6, World”,但实际输出是“1, 2, 3、你好、4、精彩、6、世界、7"。

最佳答案

你必须这样做:

if ((i % 4) == 0) {
System.out.println("Hello");
} else if ((i % 5) == 0) {
System.out.println("Wonderful");
} else if ((i % 7) == 0) {
System.out.println("World");
} else {
System.out.println(i);
}

关于java - 如何从打印列表中删除不需要的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58805848/

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