Java输入随机数并为每个数字保留一个计数器

时间:2015-02-26 02:43:05

标签: java

所以我试图创建一个接受数字“0 - 10”的循环。如果它小于“0”而不是循环退出并且程序打印出所有数字和输入的次数。因此,假设您输入1 2 3 4 5 1之类的值,它会打印出Number:1 Times Entered:2之类的内容,然后下一行将打印出Number:2 Times Entered:1。如果它高于10我会给他们一个输入错误。如果有人可以帮我创建正确的变量和格式,我想我可以从那里开始。这就是我到目前为止......我知道这不正确,但这是我想要的想法。

import java.io.*;

public class test {
    public static void main(String[] args) throws IOException{

      InputStreamReader reader = new InputStreamReader(System.in);
      BufferedReader input = new BufferedReader(reader);
      String str;
      Integer[] numbers = new Integer[1000]
      int count = 0;

      str = input.readLine();
      while(str != null){
         numbers[count] = Integer.parseInt(str);

         // Here I will create some [if else] statements like
         if(numbers < 0)
            break;
         else if(numbers >= 0 || numbers <= 50)
            numbers[count]++;
         else
            System.out.print("You must enter a value less than 51");
      } // Close while loop here

      System.out.println("Number:" + number + " Times Entered:" + count);
   } 

}

1 个答案:

答案 0 :(得分:0)

import java.io.*;

public class Demo {
public static void main(String[] args) throws IOException{

  InputStreamReader reader = new InputStreamReader(System.in);
  BufferedReader input = new BufferedReader(reader);
  String str;
  int i,number;
  Integer[] numbers = new Integer[10];
  int count = 0;
  for(i=0;i<10;i++)
    numbers[i]=0;
  str = input.readLine();
  while(str != null){
     number = Integer.parseInt(str);

     // Here I will create some [if else] statements like
     if(number == 0)
        break;
     else if(number >= 0 && number <= 10)
        numbers[number-1]++;
     else
        System.out.print("You must enter a value less than 11");
str = input.readLine();
  } // Close while loop here
  for(i=0;i<10;i++)
     System.out.println("Number:" + (i+1) + " Times Entered:" + numbers[i]);
   } 

}

这应该有效。并且付出一些努力,以便你可以学习