Java新手在这里,
所以我试图编写一个程序,可以设置hello世界的数量,以及跟随它的感叹号的数量,使用命令行参数输入这些值。我以某种方式完成它但输出格式错误。
期望的结果
“Hello World !!!!
“Hello World !!!!”
尝试1
“Hello World!
!
!
!“(这继续下去)
我得到了什么,尝试2
“Hello World !!!! Hello World !!!! Hello World !!!!”
我的尝试代码1
public class NHelloWorldWE {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//
int n = Integer.parseInt(args[0]);
int e = Integer.parseInt(args[1]);
for (int a = 1; a <= n; a = a + 1) {
System.out.print("Hello World");
for (int b = 1; b <= e; b = b + 1) {
System.out.print("!");
System.out.println(" ");
}
}
}
}
我的尝试代码2
public class NHelloWorldWE {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//
int n = Integer.parseInt(args[0]);
int e = Integer.parseInt(args[1]);
for (int a = 1; a <= n; a = a + 1) {
System.out.print("Hello World");
for (int b = 1; b <= e; b = b + 1) {
System.out.print("!");
}
}
}
}
答案 0 :(得分:0)
您需要使用新的行打印:
System.out.println("Hello World");
像这样:
public static void main(String[] args) {
//
int n = Integer.parseInt(args[0]);
int e = Integer.parseInt(args[1]);
for (int a = 1; a <= n; a = a + 1) {
System.out.print("Hello World");
for (int b = 1; b <= e; b = b + 1) {
System.out.print("!");
}
System.out.println();
}
}
这个会给你一个类似的结果,但每次迭代都会少一个感叹号(我相信这就是你想要做的)
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int e = Integer.parseInt(args[1]);
for (int a = 1; a <= n; a++) {
System.out.print("Hello World");
for (int b = 1; b <= e; b++) {
System.out.print("!");
}
e--;
System.out.println();
}
}
答案 1 :(得分:0)
以下是您的解决方案的一个版本:
public class NHelloWorldWE {
public static void main(String... args) {
int n = Integer.parseInt(args[0]);
int e = Integer.parseInt(args[1]);
for (int a = 0; a < n; a++) {
System.out.print("Hello World");
for (int b = 0; b < e; b++) {
System.out.print("!");
}
System.out.println();
}
}
}
这是一个使用流:
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class NHelloWorldWE {
public static void main(String... args) {
int n = Integer.parseInt(args[0]);
int e = Integer.parseInt(args[1]);
final String hello = "Hello World" + Stream.generate(() -> "!")
.limit(e)
.collect(Collectors.joining());
Stream.generate(() -> hello)
.limit(n)
.forEach(System.out::println);
}
}