繁体   English   中英

如何在for循环中的数组中存储值?

[英]How do I store values in an array within a for loop?

我试图获取一堆数字作为输入,并将其输出为首先是未排序的数组,然后是已排序的数组。 如何将输入的值存储在for循环中的数组内? 现在,它仅存储最后输入的值。

String strNumberOfValues, strValue;
int intNumberOfValues, intValue;
 Scanner input = new Scanner(System. in );
System.out.println("Please enter the number of values you would like to enter");
strNumberOfValues = input.nextLine();
intNumberOfValues = Integer.parseInt(strNumberOfValues);
 for (int i = 0; i < intNumberOfValues; i++) {
    System.out.println("Please enter value for index value of " + i);
    strValue = input.nextLine();
    intValue = Integer.parseInt(strValue);
    for (int j = 0; j == 0; j++) {
        int[] intArray = {
            intValue
        };
        System.out.println("Here is the unsorted list: \n" + Arrays.toString(intArray));

在循环开始之前声明并初始化数组:

intNumberOfValues = Integer.parseInt(strNumberOfValues);
int[] intArray = new int[intNumOfValues];
for (int i = 0; i < intNumberOfValues; i++) {
    System.out.println("Please enter value for index value of " + i);
    strValue = input.nextLine();
    intArray[i] = Integer.parseInt(strValue);
}
System.out.println("Here is the unsorted list: \n" + Arrays.toString(intArray));
. . .

请注意,您的内循环是无用的。 它只执行一次,并且循环中不使用循环索引j 它所做的只是进一步限制了intArray声明的范围,因此即使对于打印数组值的行也未定义该符号。 顺便说一句,在获得所有输入值之前,该print语句不应该执行,这就是为什么我将其移至答案的外循环之后。 (还要注意,这里不再需要变量intValue ,除非在其他地方使用,否则可以将其从程序中删除。)

作为样式,我还建议您避免将变量类型用作变量名的前缀。

您必须先声明数组,然后再根据索引分配值。

String strNumberOfValues, strValue;
int intNumberOfValues, intValue;

Scanner input = new Scanner(System. in );
System.out.println("Please enter the number of values you would like to enter");

strNumberOfValues = input.nextLine();
intNumberOfValues = Integer.parseInt(strNumberOfValues);

int [] intArray = new int[intNumberOfValues];

for (int i = 0; i < intNumberOfValues; i++) {
   System.out.println("Please enter value for index value of " + i);
   strValue = input.nextLine();
   intValue = Integer.parseInt(strValue);
   intArray[i] = intValue;
}
    System.out.println("Here is the unsorted list: \n" + Arrays.toString(intArray));

在您的内部for循环中,您每次都在重新声明数组,因此实际上仅保存了最后一个值。 您必须事先用用户输入的大小声明数组,然后在单个for循环中逐个索引地填充该数组:

String strNumberOfValues, strValue;
int intNumberOfValues, intValue;
Scanner input = new Scanner(System. in );
System.out.println("Please enter the number of values you would like to enter");
strNumberOfValues = input.nextLine();
intNumberOfValues = Integer.parseInt(strNumberOfValues);
int[] intArray = new int[intNumberOfValues];

for (int i = 0; i < intNumberOfValues; i++) {
    System.out.println("Please enter value for index value of " + i);
    strValue = input.nextLine();
    intValue = Integer.parseInt(strValue);
    intArray[i] = intValue;
}
System.out.println("Here is the unsorted list: \n" + Arrays.toString(intArray));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM