我想将用于放入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]));
}
}
答案 0 :(得分:3)
像这样:
yourNumbers[counter] = x;
上面的代码说明:将x
的值存储在索引(位置)yourNumbers
中的数组counter
中。因为counter
是for
循环的迭代变量,所以每次循环前进计数器时,x
的下一个值将存储在数组中的下一个可用位置。
您必须确保数组的长度与counter
的值相同。在您的代码中,执行以下操作:
int[] yourNumbers = new int[10];
为什么呢?因为counter
从0
转到9
,所以数组的长度必须为10
。
答案 1 :(得分:2)
替换此
int x = scan.nextInt();
与
yourNumbers[counter] = scan.nextInt();
此外,条件应为counter<9
,或更好counter<yourNumbers.length
答案 2 :(得分:1)
只需将输入传递到数组的下一个元素,而在for循环中:
yourNumbers[counter] = x;
但是,我还应该指出,在分配x值之前,您应该验证输入实际上是一个整数。如果该值不是整数,则程序将崩溃。