You can print things out with System.out.println and you can do math. The next step is to learn about variables. In programming a variable is nothing more than a name for something so you can use the name rather than the something as you code. Programmers use these variable names to make their code read more like English, and because programmers have a lousy ability to remember things. If they didn't use good names for things in their software they'd get lost when they came back and tried to read their code again.
If you get stuck with this exercise, remember the tricks you've been taught so far for finding differences and focusing on details:
public class VariablesAndNames { public static void main( String[] args ) { int cars, drivers, passengers, cars_not_driven, cars_driven; double space_in_a_car, carpool_capacity, average_passengers_per_car; cars = 100; space_in_a_car = 4.0; drivers = 30; passengers = 90; cars_not_driven = cars - drivers; cars_driven = drivers; carpool_capacity = cars_driven * space_in_a_car; average_passengers_per_car = passengers / cars_driven; System.out.println( "There are " + cars + " cars available." ); System.out.println( "There are only " + drivers + " drivers available." ); System.out.println( "There will be " + cars_not_driven + " empty cars today." ); System.out.println( "We can transport " + carpool_capacity + " people today." ); System.out.println( "We have " + passengers + " to carpool today." ); System.out.println( "We need to put about " + average_passengers_per_car + " in each car." ); } }
Note: The _ in space_in_a_car
is called
an underscore character. Find out how to type it if you do not already
know. We use this character a lot to put an imaginary space between words
in variable names.
U:\My Documents\CompSci\>java VariablesAndNames There are 100 cars available. There are only 30 drivers available. There will be 70 empty cars today. We can transport 120.0 people today. We have 90 to carpool today. We need to put about 3.0 in each car. U:\My Documents\CompSci\>
Assignments turned in without these things will not receive any points.
space_in_a_car
, but is that necessary? What happens if it's just 4?
space_in_a_car
? Changing it to 4 doesn't
seem to do anything.
space_in_a_car
was previously defined as a
double
variable. If it had been defined as an int
variable, putting 4 into it would have made a difference.Copyright © 2010 Zed A. Shaw. Used by permission.
(The original Python version of this assignment is part of Zed Shaw's excellent Learn Python the Hard Way course and was translated to/reinterpreted for Java by Graham Mitchell.)