繁体   English   中英

如何获得此阵列的正确输出?

[英]How do I get the right output for this array?

我正在尝试获取数组的特定输出。 将该数组放入while循环中以继续建立新数组,直到到达其计数器为止。 计数器和每个数组中的元素数量对齐,但是一旦我尝试获取输出,它就无法工作。 我应该解决什么才能解决?

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    int i;  int j;  int n;  int u;

    int count = 0;

    n = input.nextInt();

    System.out.println("Times repeated: " + n);


    while(count < n) //counter represents amount of times loop will occur
    {
        i = input.nextInt();
        int[] numbers = new int[i];
        System.out.println("Length of Array: " + i);//represents how many numbers within a line
        count++;

        for(j = 0; j < numbers.length; j++) //numbers within line
        {
            numbers[j] = input.nextInt();}
            for(int p = 0; p < numbers.length - 1; p++) //prints specific values in line

            {


            numbers[p] = numbers[numbers.length - 1 ];
            p = numbers[p];
            System.out.println(p);
            System.out.println(Arrays.toString(numbers)); }

    input.close();}
 }  }

首次用户输入:

3

2

10

1

预期产量:10

相反,我得到1。我想要做的是从数组的其余部分减去数组的最后一个元素,以获得所需的输出。 这也包括最后一个元素。

代码工作正常,只需要同时close scanner outside while. 固定支架。

input.close(); 外循环

public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        int i;
        int j;
        int n;
        int u;

        int count = 0;

        n = input.nextInt();

        System.out.println("Times repeated: " + n);

        while (count < n) // counter represents amount of times loop will occur
        {
            i = input.nextInt();
            int[] numbers = new int[i];
            System.out.println("Length of Array: " + i);// represents how many numbers within a line
            count++;

            for (j = 0 ; j < numbers.length ; j++) // numbers within line
            {
                numbers[j] = input.nextInt();
            }
            for (int p = 0 ; p < numbers.length - 1 ; p++) // prints specific values in line

            {

                numbers[p] = numbers[numbers.length - 1];
                p = numbers[p];
                System.out.println(p);
                System.out.println(Arrays.toString(numbers));
            }

        }

        input.close();
    }

产量

2
Times repeated: 2
2
Length of Array: 2
1
2
2
[2, 2]
2
Length of Array: 2
1
2
2
[2, 2]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM