should arrays always be initialized at the beginning? what solution for the following code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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); } }

13th Jul 2018, 5:56 PM
De Vinci
4 Answers
+ 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 😊
13th Jul 2018, 7:44 PM
Jain Rishav Amit
Jain Rishav Amit - avatar
+ 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.
13th Jul 2018, 6:29 PM
Andre Daniel
Andre Daniel - avatar
+ 2
thank you guys
14th Jul 2018, 12:53 AM
De Vinci
+ 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
13th Jul 2018, 7:20 PM
De Vinci