在java中输入数组的范围

时间:2013-04-17 02:05:58

标签: java arrays

我是java编程的新手。我想知道是否有一种方法可以用键盘中的整数填充数组(范围:10到65)。这是我的代码:

public static void main(String[] args)      
{
    //Keyboard Initialization
    Scanner kbin = new Scanner(System.in);

    //a.Declare an array to hold 10 intgers values
    int list[]=new int[10];     
    int i=0;
    //b.Fill the array with intgers from the keyboard(range: 10 to 50).
    System.out.print("\n\tInput numbers from 10 to 50: \n");
    list[i]= kbin.nextInt();
    if(10<=list[i] && list[i] <= 50)
    {
        for(i=1; i<=9;i++)
        {
            list [i] = kbin.nextInt();      
        }
    }
}

请帮忙。谢谢!

4 个答案:

答案 0 :(得分:2)

如果我理解你的意图......

您需要循环,直到有10个有效数字。如果用户输入的数字超出范围,则需要将其丢弃。

import java.util.Scanner;

public class TestStuff {

    public static void main(String[] args) {
        //Keyboard Initialization
        Scanner kbin = new Scanner(System.in);

        //a.Declare an array to hold 10 intgers values
        int list[] = new int[10];
        int i = 0;

        System.out.print("\n\tInput numbers from 10 to 50: \n");
        while (i < 10) {
            //b.Fill the array with intgers from the keyboard(range: 10 to 50).
            int value = kbin.nextInt();
            if (value >= 10 && value <= 50) {
                list[i] = value;
                i++;
            } else {
                System.out.println("!! Bad number !!");
            }
        }
        for (int value : list) {
            System.out.println("..." + value);
        }
    }
}

示例输出......

    Input numbers from 10 to 50: 
1
!! Bad number !!
2
!! Bad number !!
3
!! Bad number !!
4
!! Bad number !!
5
!! Bad number !!
6
!! Bad number !!
7
!! Bad number !!
8
!! Bad number !!
9
!! Bad number !!
10
11
12
13
14
15
16
17
18
19
...10
...11
...12
...13
...14
...15
...16
...17
...18
...19

答案 1 :(得分:1)

这应该解决它......

System.out.print("\n\tInput numbers from 10 to 50: \n");
for(int i=0; i<10;)
{
    int k = kbin.nextInt();      
    if (k >= 10 && k <= 50)
    {
        list[i] = k;
        ++i;
    }
}

答案 2 :(得分:0)

我不确定你要做什么。但是,我猜你正试图取用户输入的前10个数字?

要记住的一件重要事情是java(和其他语言)使用基于0的索引。所以你的for循环,其中i = 1,i <= 9; i ++我认为我应该从0开始,但我不知道你在这里会发生什么。

答案 3 :(得分:0)

尽管此问题已得到回答,但我注意到没有人提供或谈论过.hasNext() regex 方法,因此下面我使用 regex为该问题提供了答案表达式

import java.util.Scanner;

public class Main3 {
    public static void main (String [] args) {
        int list [] = new int [10];
        for (int i = 0; i < 10; i ++) {
            Scanner sc = new Scanner (System.in);
            if (sc.hasNext("([1-4][0-9])?(50)?")) {
                list[i] = sc.nextInt();
            } else {
                System.err.println("Entered value is out of range 10 - 50. Please enter a valid number");
                i --;
            }
        }

        for (int i = 0; i < 9; i ++) {
            System.out.print(list[i] + " ");
        }
        System.out.println(list[9]);
    }
}