java - 如何将用户输入的整数插入到数组中?

标签 java arrays

我昨天刚刚在 AP 计算机科学课上上了关于数组的课,现在正在做一项与接收整数并将它们放入数组有关的作业。我还没有学会如何制作表格,也没有学会如何制作 2d 和 3d 数组(如果我知道它们是什么的话)。不管怎样,我正在做的项目在这里:

“设计并实现一个应用程序,该应用程序读取 0 到 50 范围内的任意数量的整数,并计算每个输入出现的次数。处理完所有输入后,打印所有值(使用输入一次或多次的出现次数)。”

我已经在 Stack Overflow 上找到了可能的解决方案 here:

但我还没有学习 hashmap 或 map,而且他们的解决方案的输出不是我应该得到的输出。

我对我的问题所知道的是如何打印数组的第一行,它看起来像这样但没有表格:

Array

我不知道如何添加另一行以及如何计算用户输入了多少个整数以及相同数字的次数。

这是我的代码:

import java.util.Scanner;
public class Si
{
public static void main (String[] args)
{
    Scanner scan = new Scanner (System.in);
    final int LIMIT = 50;
    int[] numbers = new int[LIMIT];




    System.out.println("Enter an integer (-1 to quit");
    int integer = scan.nextInt();

    while (integer != -1)
    {
        System.out.println("Enter " + integer + " integers between 0 and 50");
        int number = scan.nextInt();
        if (integer >=0 && integer <= 50){
            for (int num = 0; num <= LIMIT; num++){//to make a row from 0 to 50
                number[scan.nextInt()]++;//count the integer the user inputs
                System.out.println (numbers[num] + "  ");//not sure how to continue, I am not sure exactly if i understand the few codes that I typed above

                System.out.println();
            }
        }
    }
}
}

我认为 for 循环下面的代码不正确,但我不确定我能做什么来让它工作。可能的输出如下:

1  2  3  4  5  6  7  8  9... 48  49  50     //Row from 1 to 50
3  1  0  2  0  0  0  3  1     0  0   0      //user typed "1" 3 times, typed "2" 1 time...

最佳答案

有几件事。

使用 while 循环是一个很好的第一步!我认为你出错的地方是

for (int num = 0; num <= LIMIT; num++){//to make a row from 0 to 50

您不需要每次在 while 循环中都执行此操作。从用户那里获取所有信息(直到用户输入-1),然后打印所有内容。

考虑存储出现次数的一个好方法是创建一个长度为 50 的数组(就像您所做的那样)并递增与用户输入的数字相对应的索引(请记住数组是从 0 索引的) 。然后,您可以只打印 2 行,其中一行是数字 1 到 50,另一行是使用简单的 for 循环和 print 语句打印的。

这旨在帮助您,而无需为您找出解决方案,特别是因为这似乎是一个家庭作业问题,并且尝试自己弄清楚这些概念非常重要!如果您有更多问题,请随时提问!

关于java - 如何将用户输入的整数插入到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40880307/

相关文章:

PHP数组匹配MYSQL字符串

arrays - Delphi 10. TCustomWinSocket 数组使用时访问冲突

javascript - JSON数组迭代: How to apply a function on each element of a json array in javascript?

java - 在 wicket 1.5.8 中强制页面过期

Java简单的递归算法,使其并行化

python - 是否可以在 Django 模型中存储数组?

c - 无法将一维数组转换为二维数组

java - 如何在 Java 中使用 C API?杰尼?

java - 尝试使用 fileProvider 从 Assets 文件夹中打开 PDF 文件,但出现 FileNotFoundException : No such file or directory

java - jsp如何将选定的值传递给servlet?