How to add an array? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to add an array?

how to add a multiple colors to v1 in this code, using an array...? public class Vehicle { int maxSpeed; int wheels; String color; double fuelCapacity; void horn() { System.out.println("Beep!"); } } class MyClass { public static void main(String[ ] args) { Vehicle v1 = new Vehicle(); Vehicle v2 = new Vehicle(); v1.color = "red"; v2.horn(); } }

1st Nov 2017, 1:08 PM
Dawid Pado
Dawid Pado - avatar
3 Answers
+ 9
public class Vehicle { int maxSpeed; int wheels; String[] colors = new String[5];//how may colors you want double fuelCapacity; void horn() { System.out.println("Beep!"); } } class MyClass { public static void main(String[ ] args) { Vehicle v1 = new Vehicle(); Vehicle v2 = new Vehicle(); v1.colors[0] = "red"; v1.colors[1] = "blue"; v2.horn(); } }
1st Nov 2017, 1:14 PM
Kamil
Kamil - avatar
+ 2
You can also just pass a new array to v1.color public class Vehicle { int maxSpeed; int wheels; String[] color; double fuelCapacity; void horn() { System.out.println("Beep!"); } } class MyClass { public static void main(String[ ] args) { Vehicle v1 = new Vehicle(); Vehicle v2 = new Vehicle(); v1.color = new String[]{"red", "yellow"}; v2.horn(); } }
1st Nov 2017, 1:16 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
thanks
1st Nov 2017, 1:15 PM
Dawid Pado
Dawid Pado - avatar