+ 2
should arrays always be initialized at the beginning? what solution for the following code?
the following code show that the arr variable has not been initialized : import java.util.Scanner; class P { public static void main (String [] args) { Scanner input= new Scanner (System.in); char [] arr; int a=0; arr [a]=input.next().charAt(0); while (arr [a]!= 'n'){ a++; arr [a]=input.next().charAt(0); } System.out.println (arr.length); } }
4 ответов
+ 3
You are doing something wrong in your code, when arr is not initialised, then without giving memory to it we can not assign values to it.
If you want user to input a array of charcter, then you can ask user to enter string and then you can use toCharArray() method of String class or you can also use charAt() method to insert one variable at one time..
Do this;
char []arr;
String s=input.next();
option 1:
arr=s.toCharArray();
option 2:
arr= new arr[s.length()];
int i=0;
while( i<a.length() ){
arr[i]=s.charAt(i);
i++;
}
I hope this will help you out...
if not, then let me know
Happy learning 😊
+ 3
Correct. In Java, before assigning any values to elements in an array, you must define the array's size.
A solution would be to put it as
char [] arr = new char[1];
It will only have one element at index 0.
Due to SoloLearn limitations, the while loop will not work as expected.
+ 2
thank you guys
+ 1
i want to keep the size depends on the input of the user, i tried to put an intial size as you did..but it didn't work