我正在读Java课程,我已经解决了这篇文章,一切正常,但有一件事。我想知道每个间隔中有多少随机数。您可以通过查看下面的代码来查看我的意思,我在其中插入[amount]我想要的随机数。我似乎没有得到正确的逻辑。任何人都可以帮助我吗?
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("How many random numbers from 0 to 999? ");
int amount = in.nextInt();
int[] numbers = new int[amount];
System.out.print("Here is the random numbers: ");
for (int i = 0; i < numbers.length; i++)
{
numbers[i] = (int) Math.floor(Math.random()*1000);
System.out.print(numbers[i] + " ");
}
System.out.println("");
System.out.print("These [amount] numbers are from 0 to 499: ");
for (int i = 0; i < numbers.length; i++)
{
if (numbers[i] <= 499)
{
int[] numbersLow = Arrays.copyOf(numbers, numbers.length);
System.out.print(numbersLow[i] + " ");
}
}
System.out.println("");
System.out.print("These[amount] numbers are from 500 to 999: ");
for (int i = 0; i < numbers.length; i++)
{
if (numbers[i] >= 500)
{
int[] numbersHigh = Arrays.copyOf(numbers, numbers.length);
System.out.print(numbersHigh[i] + " ");
}
}
}
答案 0 :(得分:2)
首先,System.out部分需要在循环之后,你怎么可能知道呢? :)
然后int [] numbersLow对我没有任何意义。如果您只想计算低于500的数字,请执行以下操作:
int counterbelow = 0;
System.out.print("These are the numbers between 0 and 499");
for (int i = 0; i < numbers.length; i++)
{
if (numbers[i] <= 499)
{
counterbelow++;
System.out.print(numbers[i] + " ");
}
}
System.out.print("These are "+counterbelow+" numbers");
答案 1 :(得分:2)
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("How many random numbers from 0 to 999? ");
int amount = in.nextInt();
int lowerCounter=0;
int higherCounter=0;
List<Integer> lowerList = new ArrayList<Integer>();
List<Integer> higherList = new ArrayList<Integer>();
int[] numbers = new int[amount];
System.out.print("Here is the random numbers: ");
for (int i = 0; i < numbers.length; i++)
{
numbers[i] = (int) Math.floor(Math.random()*1000);
System.out.print(numbers[i] + " ");
if (numbers[i] <= 499) {
lowerCounter++;
lowerList.add(numbers[i]);
}
else {
higherCounter++;
higherList.add(numbers[i]);
}
}
System.out.println("");
System.out.print("These ["+lowerCounter+"] numbers are from 0 to 499: ");
for (int i:lowerList)
{
System.out.print(i + " ");
}
System.out.println("");
System.out.print("These ["+higherCounter+"] numbers are from 500 to 999: ");
for (int i:higherList)
{
System.out.print(i + " ");
}
}
答案 2 :(得分:1)
将输出放在循环下方;)
int amount = 0;
int[] numbersLow = new int[numbers.length];
for (int i = 0; i < numbers.length; i++)
{
if (numbers[i] <= 499)
{
numbersLow[amount] = numbers[i];
amount++;
}
}
System.out.println("These " + amount + " numbers are from 0 to 499: ");
for (int n: numbersLow)
System.out.print(n + " ")