【问题标题】:Java - user input/ arrays [duplicate]Java - 用户输入/数组[重复]
【发布时间】:2016-06-15 06:25:20
【问题描述】:

所以我很难找到如何将整数放入数组中的方法,我的目标是制作一个用户将存储 10 个数字然后显示它的程序。

这就是我到目前为止所做的:

import java.util.Scanner;

public class wtf {
    public static void main(String args[]){
        Scanner input = new Scanner(System.in);
        int array[] = new int[10];

        for(int i=1;i<array.length;i++){
            System.out.print("Enter a number: ");
            array[] = input.nextInt();
        }
    }
}

但不幸的是有一个错误。

【问题讨论】:

  • array[] is wrong ,你必须提到哪个索引。数组[i]

标签: java arrays


【解决方案1】:

首先你需要指定要插入数据的索引

在你的情况下是

 array[i - 1] = input.nextInt();

由于数组是从零开始的,最好像这样循环

for(int i=0; i<array.length; i++){
....

【讨论】:

    【解决方案2】:

    访问数组时缺少索引。

    你需要的是:

    // You should also start from i = 0
    for(int i=0;i<array.length;i++){
        System.out.print("Enter a number: ");
    
        // need array[i] here
        array[i] = input.nextInt();
    }
    

    如果你想在后面显示数字,你可以这样做:

    for (int i = 0; i < array.length; i++)
    {
        System.out.println(array[i]);
    }
    

    【讨论】:

      【解决方案3】:

      您不能将元素添加到数组中,您只需覆盖现有的元素。 所以你需要提供放置元素的索引。

      你应该换一行:

              array[i-1] = input.nextInt();
      

      i-1 因为数组是从 java 中的 0 索引的,而你的 fors i 是从 110

      除了你在 1 和 9 之间迭代(i = 1i &lt; array.length),你应该使用下面的代码在 1 和 10 之间迭代:

      for(int i=1;i<=array.length;i++){
      

      所以基本上你应该使用以下块之一:

      1-索引

      for(int i=1;i<=array.length;i++){
          System.out.print("Enter a number: ");
          array[i-1] = input.nextInt();
          }
      }
      

      0-索引

      for(int i=0;i<array.length;i++){
          System.out.print("Enter a number: ");
          array[i] = input.nextInt();
          }
      }
      

      另一种选择是使用集合,例如ArrayList 在这种情况下,您不需要预先提供它的大小。

      【讨论】:

      • 非常感谢,现在我知道如何正确索引数组了 :)
      【解决方案4】:

      首先你需要为整型数组对象指定一个索引... 数组的每个元素都有其特定的索引...从 0 到 n-1 其中 n 是数组中的元素数。 其次,编程中的索引总是从0开始 索引经常与位置混淆。 位置有它通常的含义,从 1 开始... 考虑一个具有元素的数组 56 98 65 12

      这里 98 位于索引 1 和位置 2

      你现在需要做的就是

      将输入行改为:

      array[i]=input.nextInt();
      

      【讨论】:

      • the index in programming always starts from 0 Index - 这是不正确的
      猜你喜欢
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      • 2018-01-20
      • 1970-01-01
      • 1970-01-01
      • 2019-03-27
      • 2021-12-07
      • 2014-06-20
      相关资源
      最近更新 更多