[英]Converting input String to int array with Variable length in java
Here is a snippet of my code. 这是我的代码片段。 I want to get of user a number with variable length and convert it to int array.
我想给用户一个可变长度的数字并将其转换为int数组。 example: input: 352040 , output:{3,5,2,0,4,0}
示例:输入:352040,输出:{3,5,2,0,4,0}
Scanner in = new Scanner(System.in);
System.out.println(" Enter your size number: ");
int length = in.nextInt();
System.out.println(" Enter a number: ");
int number = in.nextInt();
int[] intArray = null;
String str = Integer.toString(number);
for ( int i =0; i < length ;i++)
intArray[i] = Integer.parseInt(String.valueOf(str.charAt(i)));
System.out.println(Arrays.toString(intArray));
This comes up with an error(Exception in thread "main" java.lang.NullPointerException) and I cant understand why. 这带来了一个错误(线程“ main”中的异常java.lang.NullPointerException),我不明白为什么。
Thanks for any help. 谢谢你的帮助。
Agree with comments, split("") will work only on javascript
here is a code snippet that does what OP wants... 同意评论,split(“”)仅适用于
javascript
这是一个代码片段,可以满足OP的需求...
String s = "352040";
int[] intArray = new int[s.length()];
for(int i = 0; i < s.length(); i++) {
intArray[i] = Integer.valueOf(s.substring(i, i+1));
}
System.out.println(Arrays.toString(intArray));
having an object array needs to go through 2 steps. 具有对象数组需要经历两个步骤。 you failed to cover the second step.
您未能涵盖第二步。
The preceding program declares an array (named anArray) with the following line of code:
前面的程序用下面的代码行声明一个数组(名为anArray):
// declares an array of integers int[] anArray;
//声明一个整数数组int [] anArray;
2. Creating, Initializing, and Accessing an Array 2.创建,初始化和访问阵列
One way to create an array is with the new operator .
创建数组的一种方法是使用new运算符 。 The next statement in the ArrayDemo program allocates an array with enough memory for 10 integer elements and assigns the array to the anArray variable.
ArrayDemo程序中的下一条语句为具有10个整数元素的足够内存分配一个数组,并将该数组分配给anArray变量。
// create an array of integers anArray = new int[10];
//创建一个整数数组anArray = new int [10]; If this statement is missing, then the compiler prints an error like the following, and compilation fails:
如果缺少此语句,则编译器将输出如下错误,并且编译失败:
ArrayDemo.java:4: Variable anArray may not have been initialized.
ArrayDemo.java:4:变量anArray可能尚未初始化。
How to resolve your issue: 如何解决您的问题:
instead of your array variable point to null, point to an array object by creating it like: 而不是将数组变量指向null,而是通过像这样创建数组对象来指向它:
int[] intArray = new int[length];
You need to create the array first. 您需要首先创建阵列。
int[] intArray = new int[length]; // Create array
String str = Integer.toString(number);
for ( int i =0; i < length -1;i++)
intArray[i] = Integer.parseInt(String.valueOf(str.charAt(i)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.