每个 for 循环都在新行上打印,即使它不应该



我正在尝试为Minecraft制作一个3个字母的名称生成器,我计划与不存在的朋友分享。

package bored;
import java.util.Random;
public class Yay {
public static void main(String[] args) {
String[] arr={"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "_"};
int i;
int f;
for (f=0; f<10; f++) {
for (i=0; i<3; i++) {
Random r=new Random();
int randomNumber=r.nextInt(arr.length);
System.out.print(arr[randomNumber]);
System.out.println("");
}
}
}
}

它应该打印类似"3ab"9dl"的东西 但相反,它打印

3

一个

9

d

l

您当前正在内部 for 循环中调用换行符 print 语句。您可以从中更改代码

for (f=0; f<10; f++) {
for (i=0; i<3; i++) {
Random r=new Random();
int randomNumber=r.nextInt(arr.length);
System.out.print(arr[randomNumber]);
System.out.println("");
}
}

对此

for (f=0; f<10; f++) {
for (i=0; i<3; i++) {
Random r=new Random();
int randomNumber=r.nextInt(arr.length);
System.out.print(arr[randomNumber]);
}
System.out.println();
}

您需要将System.out.println("");移到内部for-loop之外。

此外,我不会在 for 循环之外初始化fi变量,因为您只需要它们:

public static void main(String[] args) {
String[] arr={"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "_"};
for (int f=0; f<10; f++) {
for (int i=0; i<3; i++) {
Random r=new Random();
int randomNumber=r.nextInt(arr.length);
System.out.print(arr[randomNumber]);
}
System.out.println("");
}
}

问题是你在最里面的 for 循环中调用System.out.println("")。根据您的预期输出和缩进,我怀疑您的意思是:

import java.util.Random;
public class Yay {
public static void main(String[] args) {
String[] arr={"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "_"};
for (int f=0; f<10; f++) {
for (int i=0; i<3; i++) {
Random r=new Random();
int randomNumber=r.nextInt(arr.length);
System.out.print(arr[randomNumber]);
}
System.out.println(); // Outside of the for loop
}
}
}

您必须移动 'System.out.println("(;内部 for 循环外。

import java.util.Random;
public class Main {
public static void main(String[] args) {
String[] arr={"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "_"};
int i;
int f;
for (f=0; f<10; f++) {
for (i=0; i<3; i++) {
Random r=new Random();
int randomNumber=r.nextInt(arr.length);
System.out.print(arr[randomNumber]);
}
System.out.println("");
}
}
}

相关内容

最新更新