+ 2

I dont understand why this wont work can anyone help please, thanks

public class Mycar { String make,model,colour,randstr; double speed,engine,year; public static void main(String[] args) { Mycar car = new Mycar(); System.out.println(car.make = "Make: Vauxhall"); System.out.println(car.model = "Model: Astra"); System.out.println(car.engine = 1.8 + " " + (randstr = " ltr")); System.out.println(car.speed = 140 + " " + (randstr = " mph")); } }

14th Jul 2017, 9:00 PM
D_Stark
D_Stark - avatar
4 Antworten
+ 5
Basically, you're trying to do all your calculations from the println function, which doesn't work. You need to assign values to your object members first, and then you can print out the output for it. This is where constructors come in handy. You can set up default values in the class constructor, and then if its something that needs to be changed, you can change it manually or through end user input, as an example. Hope this helps. https://code.sololearn.com/c5YXrKkw2Iz8/#java public class Mycar { String make,model,colour; double speed,engine,year; public static void main(String[] args) { Mycar car = new Mycar(); car.make = "Vauxhall"; car.model = "Astra"; car.engine = 1.8; car.speed = 140; System.out.println(car.make); System.out.println(car.model); System.out.println(car.engine + " ltr"); System.out.println(car.speed + " mph"); } }
14th Jul 2017, 9:06 PM
AgentSmith
+ 3
Although @Netkos is mostly correct and his code would be the preferred way to accomplish what you're attempting it is possible to do: public class Mycar { static String make,model,colour,randstr; double speed,engine,year; public static void main(String[] args) { Mycar car = new Mycar(); System.out.println(car.make = "Make: Vauxhall"); System.out.println(car.model = "Model: Astra"); car.engine = 1.8; System.out.println(car.engine + " " + (randstr = " ltr")); car.speed = 140; System.out.println(car.speed + " " + (randstr = " mph")); } } The last 2 must be assigned outside of the print methods because their types are not compatible with String. It was attempting to assign the entire contents after the = within the parentheses of the println method to the variables. This would require the String variables to be static however, which may defeat the purpose. You could also surround car.engine = 1.8 with parentheses to make the assignment happen first. System.out.println((car.engine = 1.8) + " " + (randstr = " ltr"));
14th Jul 2017, 9:15 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
awsome thanks netkos !
14th Jul 2017, 9:23 PM
D_Stark
D_Stark - avatar
+ 1
thanks chaotic great help as always both examples are really clear makes sense to me now. i cant believe i was trying to assign the entire contant lol, thanks guys
14th Jul 2017, 9:37 PM
D_Stark
D_Stark - avatar