2

我想将 x 的用途放入 yourNumbers 数组中,我该怎么做?编辑:我将如何使用循环清理底部的 println 部分。

import java.util.Scanner; 
 public class array {
public class SS_Un8As1 {
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int[] yourNumbers = new int[10];
    for (int counter=0; counter < yourNumbers.length; counter++){
        System.out.print("Enter your number: ");
        yourNumbers[counter] = scan.nextInt();
     }         
   System.out.println("Original numbers: " + yourNumbers[0] + "," + yourNumbers[1] + "," + yourNumbers[2] + "," + yourNumbers[3] + "," + yourNumbers[4] + "," + yourNumbers[5] + "," + yourNumbers[6] + "," + yourNumbers[7] + "," + yourNumbers[8] + "," + yourNumbers[9]);
   System.out.println("Original numbers multiplied by five: " + yourNumbers[0]*5 + "," + yourNumbers[1]*5 + "," + yourNumbers[2]*5 + "," + yourNumbers[3]*5 + "," + yourNumbers[4]*5 + "," + yourNumbers[5]*5 + "," + yourNumbers[6]*5 + "," + yourNumbers[7]*5 + "," + yourNumbers[8]*5 + "," + yourNumbers[9]*5);
   System.out.println("Original numbers minus the next number: " + (yourNumbers[0]-yourNumbers[1]) + "," + (yourNumbers[1]-yourNumbers[2]) + "," + (yourNumbers[2]-yourNumbers[3]) + "," + (yourNumbers[3]-yourNumbers[4]) + "," + (yourNumbers[4]-yourNumbers[5]) + "," + (yourNumbers[5]-yourNumbers[6]) + "," + (yourNumbers[6]-yourNumbers[7]) + "," + (yourNumbers[7]-yourNumbers[8]) + "," + (yourNumbers[8]-yourNumbers[9]) + "," + (yourNumbers[9]-yourNumbers[0]));
}

}

4

3 回答 3

3

像这样:

yourNumbers[counter] = x;

上面的代码说明:将x数组yourNumbers中的值存储在索引(位置)counter中。因为counter是循环的迭代变量,所以for每次循环推进计数器时,下一个值x将存储在数组中的下一个可用位置。

必须确保数组的长度与 的值相同counter。在您的代码中,执行以下操作:

int[] yourNumbers = new int[10];

为什么?因为counter去 from 0to 9,所以数组必须是 length 10

于 2013-07-24T20:31:48.737 回答
2

替换这个

int x = scan.nextInt();

yourNumbers[counter] = scan.nextInt();

此外,条件应该是counter<9,或更好counter<yourNumbers.length

于 2013-07-24T20:33:21.417 回答
1

只需将输入传递给数组的下一个元素,同时在 for 循环中:

yourNumbers[counter] = x;

但是,我还应该指出,在分配 x 值之前,您应该验证您的输入实际上是一个整数。如果该值不是整数,您的程序将崩溃。

于 2013-07-24T20:33:24.043 回答