1.
Using a variable
In order to create more interesting programs, we must use variables. These are named values, similar to variables in algebra. Consider the following program:
public class SampleCode { public static void main(String[] args) { int x; x = 3; System.out.println(x); } }Again, we focus on the green part of the program. Compile and run the program. As you see, it prints out the number 3. But how?This program uses a variable named "x". First, it declares the variable:
int x;
This line tells the compiler two things: first, that we will use a variable named "x", and second, that this variable can hold integers. These are numbers like 15, 2, 0, -3, and such.Once a variable is declared, it must be initialized. That is, we have to set the variable equal to some value. This is done here:
x = 3;
This sets the variable "x" equal to the value 3.Finally, once a variable has been declared and initialized, it can be used. This is done here:
System.out.println(x);
This prints out the value of the variable x, which happens to be 3. And that is how the program works!
Problem #1: Change the value of x to different values and compile and run the program.
2. Using a variable without declaring or initializing it
As noted, we must first declare a variable before we use it. Otherwise, the compiler will not know how to use the variable. To see this, let's omit the line that declares the variable and see what happens. Note that we will comment out the line by placing two forward slashes at the front of it. This turns the line into a comment, which is text that the compiler ignores. It is just as though the comment was not there at all. So we have:
// int x; <-- COMMENTED OUT declaring x
x = 3;
System.out.println(x);
Paste this code into your program in place of the green code, then compile it.
Problem #2: What error message do you get when you compile a program that uses a variable without first declaring it?
We also noted that you must initialize a variable before using it. Why? Because declaring a variable simply tells the compiler the variable's name and what kind of values it can hold (like integers) -- but it does not tell it what value it should start out with. We must do that! To see this, comment out the initializing code, as such:
int x;
// x = 3; <-- COMMENTED OUT initializing x
System.out.println(x);
Again, paste this code into your program and compile it.
Problem #3: What error message do you get when you compile a program that uses a variable without first initializing it?
3. Declaring and initializing on the same line
As a shortcut, it is ok to both declare and initialize a variable all at once, like this:
int x = 3; // declares and initializes x
System.out.println(x);
Paste this code into your program and compile it. It should work the same as the previous programs.
4. Assigning, re-assigning, and re-declaring
We can change the value that a variable holds, or reassign it, as such:
int x;
x = 3;
System.out.println(x); // x equals 3 here
x = 4;
System.out.println(x); // x equals 4 here!Compile and run this code. See how it prints out 3 on one line and 4 on the next? This is because we changed the value assigned to x. So a variable can hold one value for a while, and then it can hold another value for a while.
Now, we can still declare and initialize x on one line, like this:
int x = 3;
System.out.println(x); // x equals 3 here
x = 4;
System.out.println(x); // x equals 4 here!But we cannot declare the variable x twice. So this is an error:
int x = 3;
System.out.println(x);
int x = 4; // <-- Error!
System.out.println(x);
Problem #4: What error message do you get when you compile a program that declares the same variable twice?
5. Using two variables
As you probably guessed, we can use more than one variable in our program. Here, we use a second variable named "y", that can also hold integers:
int x = 3;
int y = 4;
System.out.println(x);
System.out.println(y);Compile and run this program. It prints out 3 and 4 on separate lines. We can still reassign values to variables, as such:
int x = 3;
int y = 4;
System.out.println(x);
System.out.println(y);
x = 5;
y = 6;
System.out.println(x);
System.out.println(y);Compile and run this program. It prints out 3, 4, 5, and 6 on separate lines. Do you see why?
Problem #5: Predict what the following program will print out. Then compile and run it to check your answer.
Hint: be careful!
int x = 5;
int y = 4;
System.out.println(x);
System.out.println(y);
x = 3;
x = 2;
System.out.println(x);
System.out.println(y);
6. Declaring two variables on one line
Sometimes, we may declare two variables on the same line. This is done like this:
int x = 3, y = 4; // Declare both x and y on this line
System.out.println(x);
System.out.println(y);As usual, the compiler is very picky about this, and you have to get it just right. The next problem shows this:
Problem #6: The following code has an error. What is it? Compile it to check your answer.
int x = 3, int y = 4; // Try to declare both x and y on this line
System.out.println(x);
System.out.println(y);
Problem #7: Think about the error message in problem #6. Why did the compiler give this message? What does it mean?
7. Using two variables in an expression
We learned in the previous lesson that we can use Java as a calculator, printing out values like (10 + 20), which will print out as 30. We can use variables in this way, too. For example:
int x = 3, y = 4;
System.out.println(x);
System.out.println(y);
System.out.println(x + y); // print out the SUM (x + y)
Compile and run this code. See how it prints out 3 then 4 and then 7 (because 7 is the sum of 3+4)?Now it's your turn:
Problem #8: Change your program to print the product of x times y.
8. A nicer UI
The part of the program that the user can see is called the user interface, or the UI for short. Our UI has been very simple so far: just printing some numbers. But these numbers are unclear -- what do they mean? We learned in the previous example to provide some explanatory text in our UI. This is important, and we will do it here.
int x = 3, y = 4;
System.out.print("x = ");
System.out.println(x);
System.out.print("y = ");
System.out.println(y);
System.out.print("x + y = ");
System.out.println(x + y);Compile and run this code. Do you see how the yellow lines make the program more understandable to the user?
Problem #9: Add a nicer to UI to your program in problem #8.
9. Reading an "int" variable
Most programs need to let users enter some information. That is, users can assign values into variables. Java provides a simple way to do this using a "scanner", a line like this:
x = scanner.nextInt(); // reads an int from the user
Actually, we must do one more thing -- we have to tell the compiler about the scanner, which we do by adding one more line to our gray code, as such:class SampleCode {
public static java.util.Scanner scanner = new java.util.Scanner(System.in);
public static void main(String[] args) {
int x;
x = scanner.nextInt(); // reads an int from the user
System.out.print("x = ");
System.out.println(x);
}
}Notice that there is an extra gray line -- this line is required if your program is going to read values from the user.
Compile and run this program. You will see that it is waiting for a value. Type in an integer and see what happens.
10. Prompting for input
The previous program has a problem: when we run it, the program waits for the user to enter a number -- but how is the user supposed to know that this is happening? How does the user know what to do? As programmers, it is our responsibility to always tell the user what to do in simple, clear language. We do this by providing a prompt to the user, like this:
class SampleCode {
public static java.util.Scanner scanner = new java.util.Scanner(System.in);
public static void main(String[] args) {
int x;
System.out.print("Enter a number: "); // prompt the user
x = scanner.nextInt(); // reads an int from the user
System.out.print("x = ");
System.out.println(x);
}
}
Compile and run this program. See how much clearer that is for the user?
Problem #10: Run the program again, but when it asks you to enter a number, instead enter a word (like your name). What happens?
11. More Practice
Do each of the following. For each program, any numbers that you print out should include some clear explanatory text on the same line. Also, any arithmetic should be done by Java, not by you.
Problem #11: Write a program that reads in some number of quarts and prints out the equivalent number of ounces. Its UI should look like this (where the underlined values are entered by the user):
How many quarts? 3
3 quarts is the same as 96 ounces.
Note #1: there are 8 ounces in a cup and 4 cups in a quart.
Note #2: as always, you must match the UI exactly. Be careful with your output.
Use your program to answer the following:
How many ounces are in 15 quarts? 1753 quarts?
800 ounces is the same as how many quarts?
Why was it harder to answer part (b) than part (a) using your program?
Problem #12: Write a program that computes someone's weekly salary. Its UI should look exactly like this (where, as always, the underlined values are entered by the user):
Salary per hour, in dollars: 9
Hours per week: 20
Working 20 hours per week at $9 per hour pays $180 per week.
Note #1: This program will only work with integers for the salary. Of course, salaries often are not integer values -- like, say, $9.50 per hour. But 9.5 is not an integer. We will learn how to handle values that are not integers soon!
Note #2: Here, you will have two inputs variables, and so you will have to call scanner.nextInt twice, once for each input variable.
Use your program to answer the following:
How much would you earn in a week if you work 15 hours and your salary was $8 per hour?
Say you need $153 to buy a plane ticket, and you earn $17 per hour (after taxes!). How many hours of work are needed to pay for the plane ticket?
Problem #13: Write a program that computes the perimeter of a rectangle. Its UI should look exactly like this (where, as always, the underlined values are entered by the user):
Width of the rectangle (in feet): 4
Height of the rectangle (in feet): 3
A 4-foot by 3-foot rectangle has a perimeter of 14 feet.
Note #1: The perimeter of a rectangle is the distance around it. If you started at one corner, you would walk one width, then one height, then back another width, and down another height, before returning to where you started. So the perimeter is the sum of the width + height + width + height, or two times the width plus two times the height (right?)Use your program to answer the following:
What is the perimeter of a rectangle that is 123 feet wide and 45 feet high?
A typical football field is 360 feet long (including the endzones) and about 150 feet wide. What is the distance required, in feet, to walk once around the field?
Problem #14: Write a program that computes the area of a rectangle. Its UI should look exactly like this (where, as always, the underlined values are entered by the user):
Width of the rectangle (in feet): 4
Height of the rectangle (in feet): 3
A 4-foot by 3-foot rectangle has an area of 12 square feet.
Note #1: The area of a rectangle is the product of its width times its height. Notice the units of the area are not feet but square feet.
Use your program to answer the following:
What is the area of a rectangle that is 123 feet wide and 45 feet high?
Say you are painting the side of a building that is 142 feet long. You have enough paint to cover 2,414 square feet of wall. If you paint a rectangle along the entire length of the building, and you use all your paint, how high will your paint reach?