在简单循环中打印数组时,输出与预期不同

时间:2016-11-26 13:19:31

标签: java

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]);
        }
    }
}

在我的代码中,我从控制台读取了四个整数,并为每个整数添加了2。 如果我输入数字1四次,则System.out.print应输出3四次。

但是,我得到以下输出:

Console output

2 个答案:

答案 0 :(得分:0)

如果在检索输入后调用System.out.print(value);,则在输入后将直接打印该值(最后一个字符是换行符,因此在下一行中)。只需将它放在第一个循环后的单独循环中,如下所示:

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);
    }

}

然后,在您输入后,它将在单独的行中打印3333。如果要在单独的行中打印每个数字,请改用System.out.println(value);

答案 1 :(得分:0)

这是我目前的解决方案。希望评论能帮到你一点,否则我可以随意问我一些问题。 :)

问候Kyon

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