如何通过索引号显示数组的值?

huangapple go评论70阅读模式
英文:

How to display the value of an array by the index number?

问题

用户输入10个数字。之后,程序会要求用户输入他们想要检索的索引号,就像下面的示例一样。

[![enter image description here][1]][1]

这是我的代码


public class ArrayElement {

    public static void main(String[] args) {
        int [] Array = new int[10];
        int index;

        Scanner input = new Scanner(System.in);

        System.out.println("输入10个元素:");

        for (int i = 0; i<10; i++){
            Array[i] = input.nextInt();

        }

        System.out.print("输入您想要检索的索引号:");
        index = input.nextInt();

    }
}

<details>
<summary>英文:</summary>

The user enters 10 numbers. After that, the program asks the user to enter the index number they want to retrieve like the example below.

[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/MnuPB.png

How do I ask the user to input an index number and print the array in that specific index number?

This is my code so far

```import java.util.Scanner;

public class ArrayElement {

    public static void main(String[] args) {
        int [] Array = new int[10];
        int index;

        Scanner input = new Scanner(System.in);

        System.out.println(&quot;Enter 10 elements:&quot;);

        for (int i = 0; i&lt;10; i++){
            Array[i] = input.nextInt();

        }

        System.out.print(&quot;Enter an index you want to retrieve: &quot;);
        index = input.nextInt();

    }
}


</details>


# 答案1
**得分**: 1

public static void main(String[] args) {
    int[] Array = new int[10];
    int index;
    Scanner input = new Scanner(System.in);
    System.out.println("Enter 10 elements:");
    for (int i = 0; i < 10; i++) {
        Array[i] = input.nextInt();
    }
    System.out.print("Enter an index you want to retrieve: ");
    index = input.nextInt();

    System.out.print("Element at index " + index + " is " + Array[index]);
}

Output: Element at index 6 is 42

<details>
<summary>英文:</summary>

    public static void main(String[] args) {
    		int [] Array = new int[10];
    		int index;
    		Scanner input = new Scanner(System.in);
    		System.out.println(&quot;Enter 10 elements:&quot;);
    		for (int i = 0; i&lt;10; i++){
    			Array[i] = input.nextInt();
    		}
    		System.out.print(&quot;Enter an index you want to retrieve: &quot;);
    		index = input.nextInt();
    		
    		System.out.print(&quot;Element at index &quot;+index+&quot; is &quot;+Array[index]);
    	}

    Output : Element at index 6 is 42

</details>



# 答案2
**得分**: 1

你可以按以下方式获取数组特定索引处的元素:

```cpp
int element = Array[index];
英文:

you can get the element of a particular index of an array as follows

int element = Array[index];

huangapple
  • 本文由 发表于 2020年9月24日 16:57:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/64042966.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定