+ 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(); } }
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();
}
}
+ 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();
}
}
+ 1
thanks