如何在 Java 中将多个字符输出为一个单词
How to output multiple characters as one word in Java
下面的代码接受用户输入的整数并将它们转换为 ASCII 符号。
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int charCount = in.nextInt();
for (int i = 0; i < charCount; i++) {
System.out.println((char) in.nextInt());
}
}
}
现在,它在一个新行上打印每个字符:
Input: 097 098 099
Output:
a
b
c
如何将所有字符打印到一行中?
Input: 097 098 099
Output: abc
如果我明白你的意思,只需在解码时打印每个字符(你不需要所有的临时变量),然后在循环后打印一个新行。像,
Scanner in = new Scanner(System.in);
int charCount = in.nextInt();
for (int i = 0; i < charCount; i++) {
System.out.print((char) in.nextInt());
}
System.out.println();
示例输入/输出
7 69 108 108 105 111 116 116
Elliott
您可以使用 System.out.print()
而不是 System.out.println(
) - 它会自动为您的输出附加换行符。另一种方法是创建一个数组或 ArrayList 来存储所有输入,然后简单地打印其内容。
下面的代码接受用户输入的整数并将它们转换为 ASCII 符号。
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int charCount = in.nextInt();
for (int i = 0; i < charCount; i++) {
System.out.println((char) in.nextInt());
}
}
}
现在,它在一个新行上打印每个字符:
Input: 097 098 099
Output:
a
b
c
如何将所有字符打印到一行中?
Input: 097 098 099
Output: abc
如果我明白你的意思,只需在解码时打印每个字符(你不需要所有的临时变量),然后在循环后打印一个新行。像,
Scanner in = new Scanner(System.in);
int charCount = in.nextInt();
for (int i = 0; i < charCount; i++) {
System.out.print((char) in.nextInt());
}
System.out.println();
示例输入/输出
7 69 108 108 105 111 116 116
Elliott
您可以使用 System.out.print()
而不是 System.out.println(
) - 它会自动为您的输出附加换行符。另一种方法是创建一个数组或 ArrayList 来存储所有输入,然后简单地打印其内容。