Java 在简单循环中打印数组时,输出与预期不同
在我的代码中,我从控制台读取了四个整数,每个整数加2。 如果我键入数字1四次,System.out.print应输出3四次 但是,我得到以下输出: 如果调用System.out.printvalue;检索输入后,值将直接在输入后打印。最后一个字符是换行符,因此在下一行中。只需在第一个循环之后将其放入一个单独的循环中,如下所示:Java 在简单循环中打印数组时,输出与预期不同,java,Java,在我的代码中,我从控制台读取了四个整数,每个整数加2。 如果我键入数字1四次,System.out.print应输出3四次 但是,我得到以下输出: 如果调用System.out.printvalue;检索输入后,值将直接在输入后打印。最后一个字符是换行符,因此在下一行中。只需在第一个循环之后将其放入一个单独的循环中,如下所示: import java.util.*; public class RandomAddArray { public static void main (String
import java.util.*;
public class RandomAddArray {
public static void main (String[] args) {
AddArray ad = new AddArray();
int[] Ar = new int[4];
ad.AddArray(Ar);
}
}
class AddArray {
public void AddArray(int a[]) {
for(int i = 0; i < a.length; i++) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
a[i] = n + 2;
System.out.print(a[i]);
}
}
}
然后,在您输入后,它将在单独的行中打印3333。如果要在单独的行中打印每个数字,请使用System.out.printlnvalue;相反。这是我目前的解决方案。希望这篇评论能对你有所帮助,否则你可以问我更多的问题 你好,Kyon
public void AddArray(int a[]) {
Scanner sc = new Scanner(System.in);
for(int i = 0; i < a.length; i++) {
int n = sc.nextInt();
a[i] = n + 2;
}
for (int value : a) {
System.out.print(value);
}
}
你看到的部分是你的输入。所以最好在读完所有数字后再写下答案。@Henry你是说System.out.print应该在for循环之外吗?我试过了,但如果是这样的话,程序就不能读取[I]或[n],这就是为什么我在for循环中写这个。你有什么好主意或建议来解决这个问题吗?你考虑过第二个循环吗?我以为!我的第二个循环是否应该在forint i=0的内部;你为什么把它放在里面?谢谢!它工作得很好!但我有一个问题要问你。在for int value:a中是什么意思?@javaprogrammer它是for-each循环,表示数组a中的每个值。int值它会随着a中的每个值而变化。哦,你的输出看起来真的很棒。。谢谢你的建议@Kyon您不应该关闭系统流上的扫描仪。为什么?因为这是JVM的责任,JVM创建了它。@我关闭流,因为在这种情况下不再需要它,所以没有必要保持流打开。提到Java文档,这里也关闭了扫描仪。对,但只有字符串上的扫描器关闭,System.in上的扫描器不关闭。您永远不应该关闭资源,因为您没有打开,其中包括System.in。那将是糟糕的编码实践。我自己犯了这个错误,例如Eclipse给了你一个错误的资源泄漏警告。有关更多信息,请查看和。以后使用中的另一个问题是,无法重新打开System.in。
import java.util.*;
public class Main {
public static void main (String[] args) {
// create Array to fill and pass it into our fill function
int[] Ar = new int[4];
AddArray.addToArray(Ar);
System.out.println(Arrays.toString(Ar));
}
private static class AddArray {
// static class, there is no need to instantiate it.
public static void addToArray(int a[]) {
// create on scanner out of the loop
Scanner sc = new Scanner(System.in);
// for each array index let's scan for some new int's
for(int i = 0; i < a.length; i++) {
System.out.printf("Type in your %s of %s integer:%n", i+1, a.length);
int n = sc.nextInt();
a[i] = n + 2;
}
// close scanner afterwards
sc.close();
}
}
}
Type in your 1 of 4 integer:
4
Type in your 2 of 4 integer:
124
Type in your 3 of 4 integer:
12
Type in your 4 of 4 integer:
2
[6, 126, 14, 4]
Process finished with exit code 0