为Scanner for arrays创建一个循环

时间:2016-11-24 02:17:13

标签: java arrays

我想创建一个循环,要求扫描器在一个数组中输入一个接一个的数字(我想到的是10)。有什么建议吗?

import java.util.Scanner;

public class AssignSeven 
{
    public static void main(String[] args)
    {
        int [] array1 = new int[10];
        System.out.println("Enter 10 numbers");
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();

        for (int i = 0; i < 9; i++)
        {
            array1[i] = a;
        }

    }
}

2 个答案:

答案 0 :(得分:2)

更改为

    for (int i = 0; i < 9; i++)
    {
        int a = sc.nextInt();
        array1[i] = a;
    }

甚至

    for (int i = 0; i < 9; i++)
    {
        array1[i] = sc.nextInt();
    }

答案 1 :(得分:0)

很简单,您只需将扫描仪对象的输入值分配给数组的索引即可:

import java.util.Scanner;

public class AssignSeven 
{
    public static void main(String[] args)
    {
        int [] array1 = new int[10];
        System.out.println("Enter 10 numbers");
        Scanner sc = new Scanner(System.in);

        // Where you had the original input
        // int a = sc.nextInt();

        for (int i = 0; i < 9; i++)
        {
            // Instead of array1[i] = a; you have
            array1[i] = sc.nextInt();
        }

    }
}

希望这有帮助!