+ 1

How do you create an array using a string variable in class?

this is just an example import java.util.*; class Animal String x; static void Message(String str){System.out.println(str);} main// Animal y = new Animal(); Scanner scn = new Scanner(System.in); String z = y.next(); y.x [] = {"monkey","elephant","tiger"}; if(z.equalsIgnoreCase(y.x[0]||y.x[1]||y.x[2]){Message(z + "these are my favourite animals");} thanks

8th Aug 2017, 5:35 PM
D_Stark
D_Stark - avatar
6 odpowiedzi
+ 2
Ohh . You only need it in the Animal class. String[] a; You don't need it there when initializing the array. y.x = {// etc.. Unless you want to write this: y.x = new String[]{"stuff}; Edit: I forgot you can't only use {} if the array has already been declared. So, you'd have to do: y.x = new String[]{"Stfff"};
8th Aug 2017, 6:11 PM
Rrestoring faith
Rrestoring faith - avatar
+ 1
Make the String an Array. Fix: String[] x;
8th Aug 2017, 5:39 PM
Rrestoring faith
Rrestoring faith - avatar
+ 1
oh cool so i dont need [] in main?
8th Aug 2017, 5:45 PM
D_Stark
D_Stark - avatar
+ 1
The parameters must be a String Array in main. So you do need []. A String itself is not an array. While it does use a char array internally, it is still just a class. Or, you can think of a String array as a 2d char array. (Though that isn't technically accurate). So, a String is a word. A String array is words.
8th Aug 2017, 5:50 PM
Rrestoring faith
Rrestoring faith - avatar
+ 1
sorry faith so i need [] in class Animal String x[]; <<< here main// y.x[] = <<<<here thanks
8th Aug 2017, 5:55 PM
D_Stark
D_Stark - avatar
+ 1
Thanks faith!
8th Aug 2017, 6:16 PM
D_Stark
D_Stark - avatar