Java循环由于某种原因运行了4次

时间:2019-12-05 09:48:34

标签: java arrays for-loop

所以我有这个作业,需要循环用户输入6次。循环完成后,再次循环3次。我之前没有添加for lop,所以我不知道如何处理。

这是该方法的代码:

public static int[] getPlayerNumbers(int[] playNums) {
    Scanner input = new Scanner(System.in);

    for (int i = 0; i < playNums.length; i++) {
        System.out.println("Please enter numbers from 1-9: " + i);
        playNums[i] = input.nextInt();

        while (playNums[i] < 1 || playNums[i] > 9) {
            System.out.println("Invlaid input. Please only enter 1-9. ");
            playNums[i] = input.nextInt();
        }
    }

    return playNums;
}

我放置了i来查看索引,索引从05,然后返回到0。我没办法了,请帮忙。

3 个答案:

答案 0 :(得分:0)

您的playNums似乎已超过6个。尝试

public static int[] getPlayerNumbers(int[] playNums) {
Scanner input = new Scanner(System.in);

for (int i = 0; i < 6; i++) {
    System.out.println("Please enter numbers from 1-9: " + i);
    playNums[i] = input.nextInt();

    while (playNums[i] < 1 || playNums[i] > 9) {
        System.out.println("Invlaid input. Please only enter 1-9. ");
        playNums[i] = input.nextInt();
    }
}

return playNums;}

答案 1 :(得分:0)

我已经测试了您的代码,它似乎对我有用。 playsNums肯定包含超过6个值。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int[] playNums ={1, 2, 3, 4, 5, 6};
        getPlayerNumbers(playNums);
        for (int playNum: playNums) {
            System.out.println(playNum);
        }
    }

    public static int[] getPlayerNumbers(int[] playNums)
    {
        Scanner input = new Scanner(System.in);

        for (int i = 0; i < playNums.length; i++) {
            System.out.println("Please enter numbers from 1-9: " + i);
            playNums[i] = input.nextInt();
            while (playNums[i] < 1 || playNums[i] > 9) {
                System.out.println("Invalid input. Please only enter 1-9. ");
                playNums[i] = input.nextInt();
            }
        }
        return playNums;
    }
}

答案 2 :(得分:0)

尝试一下

public static int[] getPlayerNumbers(int[] playNums)
{
    Scanner input = new Scanner(System.in);

    for (int i = 0; i < 6; i++)
    {
        playNums[i] = input.nextInt();
        if(playNums[i] < 1 || playNums[i] > 9){
           System.out.println("Invlaid input. Please only enter 1-9. ");
           getPlayerNumbers(playNums);
        } else{

        System.out.println("Please enter numbers from 1-9: " + i);
            playNums[i] = input.nextInt();
        }

    }
    return playNums;