我必须创建一个程序,用50个随机值填充数组,介于1和100之间,然后让用户输入1到100之间的数字。程序将输出该数字出现的次数。这是我到目前为止所做的,我不知道接下来要做什么来完成我的计划。
import java.util.*;
public class Occurences {
public static void main(String[] args)
{
//This program will generate an array with 50 random values
//This user will then input a number
//The program will then tell the user how many times their numbers appears
//Create array
int numbers[]= new int[50];
//Create a new scanner object
Scanner sc=new Scanner(System.in);
System.out.println("Please enter a number between 1 and 100");
int Usernum= sc.nextInt();
for (int i=0; i<numbers.length; i++)
{
numbers[i]=(int)(Math.random()*100+1);
}
}
}
答案 0 :(得分:2)
处理此问题的Java 8之前的方法是迭代随机数组并计算输入发生的次数。添加以下代码:
int count = 0;
for (int i=0; i < numbers.length; i++) {
if (numbers[i] == Usernum) {
++count;
}
}
System.out.println("The user input " + Usernum + " occurred " + count + " times.");
在Java 8中,我们可以尝试在随机数组上使用流:
int count = Arrays.stream(numbers).filter(x -> x == Usernum).toArray().length;
答案 1 :(得分:1)
代码:
package com.stackoverflow.json;
import java.util.Arrays;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class Main {
public static void main(String[] args) {
//This program will generate an array with 50 random values
//This user will then input a number
//The program will then tell the user how many times their numbers appears
//Create array
int numbers[]= new int[50];
//Create a new scanner object
Scanner sc=new Scanner(System.in);
System.out.println("Please enter a number between 1 and 100");
int Usernum= sc.nextInt();
for (int i=0; i<numbers.length; i++)
{
numbers[i]=ThreadLocalRandom.current().nextInt(1, 100 + 1);;
}
System.out.println(Arrays.toString(numbers));
int count=0;
for (int i = 0; i < numbers.length; i++) {
if(numbers[i]==Usernum)
count++;
}
System.out.println("count="+count);
}
}
打印:
Please enter a number between 1 and 100
2
[91, 12, 7, 55, 73, 77, 92, 69, 84, 49, 8, 54, 24, 27, 51, 84, 71, 79, 91, 65, 41, 30, 91, 2, 99, 83, 46, 31, 21, 17, 78, 18, 54, 48, 100, 9, 74, 8, 48, 63, 49, 89, 80, 22, 10, 79, 67, 84, 57, 17]
count=1