[英]Program not storing values in an array
Was trying to make a sorting program of integers entered by user and wanted it to take as many integer user wants, without first asking how many int he wanna sort , but while taking input it just crashes , basically the problem is it is not storing values in array试图制作一个用户输入的整数排序程序,并希望它采用用户想要的任意数量的整数,而不首先询问他想要排序多少个整数,但是在输入时它只是崩溃了,基本上问题是它不存储值在数组中
import java.util.Scanner;
class apple {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int j = 0;
int[] arr;
arr = new int[j];
while (true) {
arr[j] = scan.nextInt();
if (arr[j]==(int)'\n'){break;}
j++;
arr = new int[j];
}
for(j = 0 ;j < arr.length ;j++){
System.out.print(arr[j] + " ");
}
}
}
First, use Scanner.hasNextInt()
in conjunction with Scanner.nextInt()
.首先,将
Scanner.hasNextInt()
与Scanner.nextInt()
结合使用。 Next, you are creating an array of size 0
;接下来,您要创建一个大小为
0
的数组; it can't store any values unless you first copy it 1 (because Java arrays are fixed length).它不能存储任何值,除非您先将其复制1 (因为 Java 数组是固定长度的)。 You can use
Arrays.copyOf(int[], int)
to do that.您可以使用
Arrays.copyOf(int[], int)
来做到这一点。 And, you can use Arrays.toString(int[])
to display your array after you fill it.而且,您可以在填充数组后使用
Arrays.toString(int[])
来显示它。 Something like,就像是,
Scanner scan = new Scanner(System.in);
int j = 0;
int[] arr = new int[j];
while (scan.hasNextInt()) {
arr = Arrays.copyOf(arr, ++j);
arr[j - 1] = scan.nextInt();
}
System.out.println(Arrays.toString(arr));
Java Collections (like ArrayList
2 ) are more flexible, allowing a variable number of elements. Java集合(如
ArrayList
2 )更灵活,允许可变数量的元素。 Sadly they cannot operate directly with primitive types 3 , but can be used to store the corresponding wrapper classes .遗憾的是,它们不能直接与原始类型3 一起操作,但可用于存储相应的包装类。 Something like,
就像是,
List<Integer> al = new ArrayList<>();
while (scan.hasNextInt()) {
al.add(scan.nextInt()); // <-- int will be autoboxed to Integer
}
// int j = al.size(); // <-- like array.length, if you want to know how
// many numbers were read.
System.out.println(al); // ArrayList, unlike arrays, overrides toString
1 Which has a cost. 1有成本。
2 A collection backed by an array. 2由数组支持的集合。
3 Although primitive types can be autoboxed . 3虽然原始类型可以自动装箱。
@Elliot Frisch explains how to do this with an array that you "grow" each time you want to add element by reallocating and copying the array. @Elliot Frisch 解释了如何在每次要通过重新分配和复制数组添加元素时“增长”的数组来执行此操作。
A simpler idea is to replace the int[] arr;
一个更简单的想法是替换
int[] arr;
with和
List<Integer> list = new ArrayList<>();
and then you can just use list.add(scan.nextInt());
然后你可以使用
list.add(scan.nextInt());
to add the integer to the list.将整数添加到列表中。 The
ArrayList
takes care of "growing" the storage behind the scenes. ArrayList
负责在幕后“增长”存储。 (A LinkedList
would work just as well here.) (一个
LinkedList
在这里也能正常工作。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.