【问题标题】:How to find the random index in an array?如何在数组中找到随机索引?
【发布时间】:2017-09-13 06:40:13
【问题描述】:
  1. 创建 8 个随机生成的介于 1 到 50 之间的整数值。完成
  2. 在屏幕上显示一系列值。完成
  3. 用户必须输入值。查找索引和显示。
  4. 如果找不到值,则显示 -none。

【问题讨论】:

  • 代码和尝试怎么样?如果谷歌不能帮你解决这个问题,你应该尝试提高你的谷歌技能
  • 这不会是家庭作业吧?
  • @Stultuske 感谢您的提示。通过谷歌搜索获得了前 2 个。
  • @Henrik 正确,但我的专业是网络(兼职)。 Java 对我来说是新事物,但它很有趣,但无法在很短的时间内应付,而且还要兼顾工作和娱乐。
  • @DhaneshR 看到第三个和第四个比第一个更容易,我相信你会弄明白的

标签: java arrays


【解决方案1】:

这很容易。由于您已经完成了第 1 步和第 2 步,您只需向用户询问输入、搜索您的数组并输出索引(如果输入与数组中的值匹配)。

public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);
    Random random = new Random(); 
    int[] numbers = new int[8];

    for(int i = 0; i < 8; i++) {
        numbers[i] = random.nextInt(50) + 1;
        System.out.print(numbers[i] + ", ");
    }

    System.out.print("\nInput value: ");
    int input = scanner.nextInt();
    boolean found = false;

    for(int i = 0; i < numbers.length; i++) {
        if(input == numbers[i]) {
            System.out.println("Index: " + i);
            found = true;
        }
    }

    if(!found) {
        System.out.println("none");
    }
}

【讨论】:

    猜你喜欢
    • 2014-07-25
    • 1970-01-01
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多