簡體   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