java接受用户输入为5个整数

时间:2012-11-08 06:48:49

标签: java algorithm

您好如何在java中限制某些用户输入的整数?下面是我接受用户输入的代码,我如何确保只接受来自用户的5个整数?感谢

public static void main(String args[]) 
    {
        int a;
         Scanner in = new Scanner(System.in);

      System.out.println("Enter a string");
      a = in.nextInt();
      System.out.println("You entered integer "+a);

    }

3 个答案:

答案 0 :(得分:1)

public static void main(String args[]) 
{
  int a[] = new int[5];
  int i = 0; 
  Scanner in = new Scanner(System.in);
  while(i<5)
  {
  System.out.println("Enter an integer");
  a[i] = in.nextInt();
  i++;
  System.out.println("You entered integer "+a[i-1]);
  }

}

a [i]介于1和100之间

public static void main(String args[]) 
    {
      int a[] = new int[5];
      int i = 0; 
      Scanner in = new Scanner(System.in);
      while(i<5)
      {
      System.out.println("Enter an integer between 1 and 100");
      a[i] = in.nextInt();
      if(a[i]>=1 && a[i]<=100) 
      {
        i++;
        System.out.println("You entered integer "+a[i-1]);
      }
      }

    }

答案 1 :(得分:0)

使用仅迭代5次的for循环并在for循环内取输入。

答案 2 :(得分:0)

将静态字段声明为count = 0,

检查a> 0 如果是,则递增计数1

当count已经是5时,不要让用户输入任何内容