cs 5ja introduction to java on thursday... last class we talked about a few different things: we...

46
CS 5JA Introduction to Java On Thursday... Last class we talked about a few different things: We talked about mathematical operators and about the order of operations when programming an equation in Java. We talked about other operators that are built-in to Java, including the append operator for the String object. We talked about the if statement and how to evaluate its conditional to decide if we execute a particular block of code or if we skip it. We talked about the equality operator and at relational operators and looked at how to use them within the conditional of an if statement. We assigned some homework which will turn you into actual programmers.

Post on 20-Dec-2015

214 views

Category:

Documents


0 download

TRANSCRIPT

CS 5JA Introduction to Java

On Thursday...Last class we talked about a few different things:

We talked about mathematical operators and about the order of operations when programming an equation in Java.

We talked about other operators that are built-in to Java, including the append operator for the String object.

We talked about the if statement and how to evaluate its conditional to decide if we execute a particular block of code or if we skip it.

We talked about the equality operator and at relational operators and looked at how to use them within the conditional of an if statement.

We assigned some homework which will turn you into actual programmers.

CS 5JA Introduction to Java

Today...We will talk about how to make a simple class that you can interact with using instructions (or methods) that you define.

We’ll talk about how you can pass arguments to your methods.

We will also look at some more control structures, including the if...else multiple selection keyword and the while looping mechanism.

We will also introduce logical operators that will make our conditionals more powerful and our code more compact.

CS 5JA Introduction to Java

Pop Quiz!What number is put into the variable result?a) int result = 15 % 2;b) int result = ((((17 % 5) * 4) + 13) * (14 / 2));c) int result = 17; result *= 3;

Write a line of code which creates a new variable to hold some text, and puts the words “Hello World” into it at the same time. How many ways can you accomplish this task?

What primitive data type should I use to store a number with decimals?

What does the conditional evaluate to? Will the code in the brackets get executed? int number = 10;if (number != 10) {

System.out.println(“I am here...”);};

CS 5JA Introduction to Java

Oops...

What is the value of x after the following line has been executed?

int x = 15.9;

The answer is that this would produce an error. In order to have it not give you an error you need to explicitly cast the variable of one type into a variable of another. In this case, a double into an int.

int x = (int) 15.9;

And this would truncate the number into 15. We will return to why we might need to cast something like this soon.

CS 5JA Introduction to Java

Let’s make a class...You’ve actually already made a class already.

public class HelloWorld

{

//an empty class...

}

But up until now we have only being using the special case of a main method. We haven’t actually instantiated the class. That is, we haven’t turned the description of the class into an actual object that we can work with.

You can think of a class as kind of a ghost. To add life to it you need to instantiate it.

CS 5JA Introduction to Java

Let’s make a class...You instantiate a class with the new keyword. That is, you create a new object out of your class. If you haven’t made your object, you can’t do anything with it. Once you instantiate the class, you assign it to a variable so that you can use it.

For example you make a file named Car.java and save it to a file:public class Car{ public Car(String make) { }}

Now you can also write another class which makes these cars, and save it to its own file CarFactory.java:

CS 5JA Introduction to Java

Let’s make a class...public class CarFactory

{

public static void main(String args[])

{

Car cheapCar = new Car(“Honda”);

Car averageCar = new Car(“Volkswagen”);

Car expensiveCar = new Car(“BMW”);

}

}

Now we have Car variables which each hold one actual Car object. We can now pass instructions to these cars.

CS 5JA Introduction to Java

The constructorIn our Car class we have a constructor which looks like this:

public Car(String make)

{

}

The constructor is a special method which gets called when you instantiate an object (turn a class into an object you can work with). That is, the constructor is invoked whenever you use the new keyword on an object. The constructor is used to initialize your object.

In this example, we are passing the make of the car to the Car constructor.

Let’s extend the constructor so that it actually does something...

CS 5JA Introduction to Java

The constructorpublic class Car{ String makeOfCar; //new code public Car(String make) { makeOfCar = make; //new code }}We’ve added two lines to our class. The first one creates a String variable named makeOfCar. The second one tells the constructor to take the String that you are passing in and assign it to our new variable.

When a variable is passed in or created within the constructor it is just a temporary, or local, variable. However, if you assign a local variable to an instance variable, it becomes part of your object.

CS 5JA Introduction to Java

Instance variablesOur Car object now has one instance variable defined. That means that each object (that is each instance of the class) has its own version of that variable. They are completely different buckets, even though they have the same name and are of the same type. The only way you can get to that bucket is through the larger bucket of the object itself.

In our CarFactory we made three cars. Each of those three cars has its own String variable called makeOfCar. In the cheapCar object, makeOfCar is “Honda”; in expensiveCar it is “BMW”.

We can also write instructions to get at the data we’ve initialized with the constructor.

CS 5JA Introduction to Java

MethodsYou send instructions to your objects using methods.

Let’s write a method for our Car class.

public void printMakeOfCar()

{

System.out.println(“Make of car : “ + makeOfCar);

}

This method retrieves the instance variable named makeOfCar and prints it to the screen.

CS 5JA Introduction to Java

MethodsLet’s have the CarFactory display the make of the car after we create the cars.

public static void main(String args[])

{

Car cheapCar = new Car(“Honda”);

Car averageCar = new Car(“Volkswagen”);

Car expensiveCar = new Car(“BMW”);

cheapCar.printMakeOfCar();

averageCar.printMakeOfCar();

expensiveCar.printMakeOfCar();

}

What does this do?

CS 5JA Introduction to Java

“Get” & “Set” methodsMake of car : Honda

Make of car : Volkswagen

Make of car : BMW

A common thing to do is to make get and set methods for your instance variables. You will probably have other objects that will want to retrieve data from your object, or to edit the data in your object.

Maybe the people in our CarFactory will want to set the price of the car, or maybe they will want to look at what price they gave it earlier. We can create a new instance variable for our Car class, and add methods for setting and getting the price.

CS 5JA Introduction to Java

MethodsNew lines of code in our Car class:

public class Car{ int priceOfCar;

public void setPriceOfCar(int price) { priceOfCar = price; } public int getPriceOfCar() { return price; } }

CS 5JA Introduction to Java

MethodsNow let’s have our CarFactory decide on price for the cars. And then because the Honda is such a good deal, we’ll have the factory print out a label to stick it to advertise how low the price is:

public static void main(String args[]){ //leaving out previous code so it all fits on one slide! cheapCar.setPriceOfCar(9499); averageCar.setPriceOfCar(14999); expensiveCar.setPriceOfCar(50000);

System.out.println(“Unbelievable Price! Only $“ + cheapCar.getPriceOfCar() + “!”);}

CS 5JA Introduction to Java

Return statementOur getPriceOfCar looks a little bit different than the other methods we’ve seen before:

public int getPriceOfCar()

{

return price;

}

First, instead of the void keyword in the method signature, we have an actual return type of int.

Second we have a new keyword, return. The return keyword passes a variable back to whatever object invoked it. In this case it is a variable of type int, as specified in the signature.

CS 5JA Introduction to Java

if...elseLast class we talked about the if statement, how can use if statements to evaluate a conditional to decide if you want to execute a block of code or not.

if (car.getPriceOfCar() > 20000)

{

System.out.println(“nice car!”);

}

There are also two other statements that compliment the if : else, and else if.

CS 5JA Introduction to Java

if...elseFor example, we can turn our if statement into an if...else statement

if (car.getPriceOfCar() > 20000)

{

System.out.println(“nice car!”);

}

else

{

System.out.println(“I guess your car is okay”);

}

That is, if the car cost more than $20000 execute the first block of code, otherwise execute the second block of code, the code after else.

CS 5JA Introduction to Java

if...else...else ifYou can also extend the else...if statement to more than two possible outcomes using the else if statement.

if (car.getPriceOfCar() > 20000)

{

System.out.println(“nice car!”);

}

else if (car.getPriceOfCar() > 1000)

{

System.out.println(“I guess your car is okay”);

}

else

{

System.out.println(“Is your car safe to drive?”);

}

CS 5JA Introduction to Java

if...else...else ifNote that the else if and the else keywords can only be used directly after the if statement, and the else if keyword must be before the else statement. The following would be an error because the else if follows the else...if (car.getPriceOfCar() > 20000){ System.out.println(“nice car!”);}else{ System.out.println(“Is your car safe to drive?”);}else if (car.getPriceOfCar() > 1000){ System.out.println(“I guess your car is okay”);}

CS 5JA Introduction to Java

nested ifs...You can also nest if statements, that is, put an if statement inside another if statement.

Basically, if the conditional evaluates to true, then the code inside the brackets will be executed. This includes any code, including other if statements!

if (car.getPriceOfCar() > 20000){ if (car.getMake().equals(“BMW”)) { System.out.println(“nice Beamer!”); } else { System.out.println(“nice car!”); }}

CS 5JA Introduction to Java

Logical operatorsA logical operator is used to create more complex conditionals by combining simple conditionals together.

There are two main ones that we’ll look at now: the conditional AND operator and the conditional OR operator.

Just like how with the equality operator we used a double equals sign, with the AND operator and the OR operator we use a double ampersand and a double ‘pipe’ sign respectively. That is,

&& (for the AND operator)

|| (for the OR operator)

CS 5JA Introduction to Java

Logical operatorsif (car.getPriceOfCar() > 20000 && car.getMPG() > 30){ System.out.println(“Your car is expensive and gets good mileage!”);}

is equivalent to the nested if statements:if (car.getPriceOfCar() > 20000){ if (car.getMPG() > 30) { System.out.println(“Your car is expensive and gets good mileage!”); }}

CS 5JA Introduction to Java

Logical operatorsWith the && operator, we are saying that both conditions in the conditional must evaluate to true, else we skip the block of code.

With the || operator, we are saying that at least one of the conditions in the conditional must evaluate to true, else we skip the block of code.

if (car.getPriceOfCar() > 20000 || car.getMPG() < 20){ System.out.println(“I don’t want this car– Either it is too expensive OR it gets really bad mileage!”);}else{ //this car is affordable AND it gets good mileage!}

CS 5JA Introduction to Java

Next classMore logical operators...

Looping control statements (the while loop and the for loop)...

We’ll start building a more complicated program with more classes and more methods...

A new homework assignment...

CS 5JA Introduction to Java

On Tuesday...We started talking about how to make a custom class to model some aspect of a system you are interested in.

We looked at how you need to instantiate the class with the new keyword, and then assign it to a variable in order to be able to use and manipulate it.

We talked about the class constructor, which is used to initialize an object as it gets instantiated.

We talked about storing data related to an object inside instance variables.

We talked about how you write methods inside your classes so that other parts of your program can talk to your object and manipulate the instance variables.

CS 5JA Introduction to Java

On Tuesday...We talked about the common set method which can edit an instance variable. We also talked about its counterpart, the get method that sends the data in the instance variable back to whoever asked for it. The data is sent back using the return keyword. The type of data is specified to be returned is specified with a method signature.

We also talked about extending the if statement with the else if keyword and the else keyword.

And finally, we introduced two logical operators, the conditional AND operator and the conditional OR operator.

CS 5JA Introduction to Java

Today...We’re going to look at two other types of control syntaxes which will let you repeat a set of instructions, the while loop and the for loop.

And if we have time, we’re going to look at some more examples of logical operators in conjunction with if statements (and which apply to any conditionals).

We’re going to look at a slightly more involved program which simulates a virtual ATM machine and virtual bank accounts.

This program will the basis of the homework for this week. You’ll add some methods to the classes I’ve defined. After next week you’ll have the opportunity to create your own custom classes and to make your own decisions about how to model (super simple) real-world problems.

CS 5JA Introduction to Java

The while loopJust as the if statement has a conditional that is evaluated to decide whether or not to execute a block of code, the while statement has a conditional that is evaluated to decide whether or not to loop over a block of code. The conditional is re-evaluated at every time the program reaches the end of the block of code.

The program will repeat the code again and again until the conditional no longer evaluates to true.

boolean keepRunning = true;while (keepRunning == true){ System.out.println(“running...”);}

What will this do?

CS 5JA Introduction to Java

The while loopAnother example:

int counter = 0;

while (counter < 10)

{

System.out.println(“counter = ” + counter);

counter++;

}

What will this do?

CS 5JA Introduction to Java

The while loopAnother example:

boolean keepGoing = true;

while (keepGoing == true)

{

System.out.println(“a) keepGoing = “ + keepGoing);

keepGoing = false;

System.out.println(“b) keepGoing = “ + keepGoing);

}

Will the second print statement get printed to the screen?

CS 5JA Introduction to Java

break and continue;The answer is that both print statement will be reached. The conditional gets re-evaluated only when the last line of code in block has been reached.

To exit the block before you reach the end you can use the break keyword.

boolean keepGoing = true;

while (keepGoing == true)

{

if (2 > 1)

break;

System.out.println(“I will never print this!”);

}

CS 5JA Introduction to Java

break and continue;On the other hand, you might want to check to see if a certain condition is true and, instead of exiting the block completely, go immediately back to the start of the loop. In this case you use the continue keyword.

(code on next slide)

CS 5JA Introduction to Java

break and continue;Scanner s = new Scanner(System.in);while (true){ System.out.println(“Guess a number between 1 and 10“); int num = s.nextInt(); if (num < 1 || num > 10) { System.out.println(“duh!!”); continue; } else if (num == 7) { System.out.println(“Wow– you got it!”); break; } else System.out.println(“Nope!”);}

CS 5JA Introduction to Java

The while loopJust like with if conditionals, while conditionals can contain logical operators:

int counter = 0;

boolean keepRunning = true;

while (keepRunning == true && counter < 10)

{

System.out.println(“a keepRunning = “ + keepRunning);

counter++;

}

This will evaluate to false as soon as one of the conditions is false. In this case, counter will reach 10 and we will exit out of the loop, even though the keepRunning variable always is equal to true.

CS 5JA Introduction to Java

Nested while loopJust as with the if statement, while loops can also be nested. When we are finished with the loop, either because the conditional has evaluated to false, or because we have used the break keyword to break out of the loop, we pop out to the outer loop.

int max = 4, x = 1, y; //shortcut

while (x < max) {

System.out.println(“outer”);

y = 1;

while (y < max) {

System.out.printf(“inner: %d * %d = %d”, x, y, (x * y));

y++;

}

x++;

}

Think about this for a minute. What will get printed out to the screen?

CS 5JA Introduction to Java

Nested while loopouter

inner: 1 * 1 = 1

inner: 1 * 2 = 2

inner: 1 * 3 = 3

outer

inner: 2 * 1 = 2

inner: 2 * 2 = 4

inner: 2 * 3 = 6

outer

inner: 3 * 1 = 3

inner: 3 * 2 = 6

inner: 3 * 3 = 9

CS 5JA Introduction to Java

the for loopAnother common looping mechanism is called the for loop. This loop can simplify code where you want to keep track of a particular index, or when you want to be exact about how many iterations of the loop occur.

for (int i = 0; i < 10; i++)

{

System.out.println(“i = “ + i);

}

You can think of this loop as being like the Indy 500, or in this case the Indy 10. Except instead of starting with lap 1, you start with lap 0.

You can see that the stuff in parentheses after the for keyword is separated by semi-colons. Lets look at the three parts in the parenthesis...

CS 5JA Introduction to Java

the for loopfor (int i = 0; i < 10; i++) {//stuff}

The int i = 0 creates and assigns a temporary control variable labeled, in this case, i. This control variable keeps track of “how many laps we have completed.” The control variable is also called the index.

the i < 10 is the conditional, the exact same conditional as in the while loop and the if statement. Usually, however, the conditional in a for loop refers to the control variable. It is what is describing “how many laps are in the race”. We keep on looping until the conditional is evaluated to false.

In this case, once i >= 10, we immediately exit the loop.

The i++ tells the guy holding up the sign with the lap number on it to change signs. The sign (that is, our int i) is updated at the end of every loop.

CS 5JA Introduction to Java

the for loopStarting at lap 5...for (int i = 5; i < 10; i++) { System.out.println(“i = “ + i); }

Measuring meters instead of laps...for (int i = 0; i < 1000; i+=100) { System.out.println(“You’ve swum “ + i + “ meters.”); }

Counting backwards...for (int i = 10; i >= 1; i--) { System.out.print(“ ...” + i ); }System.out.println(“ Liftoff!!!” );

CS 5JA Introduction to Java

the for loopYou can also nest for loops.

Here’s that same while loop that multiplied numbers re-written as a for loop.

for (int x = 1; x < 4; x++)

{

for (int y = 1; y < 4; y++)

{

System.out.printf(“%d * %d = %d”, x, y, (x * y));

}

}

Note: the reason you generally start with 0 will become apparent when we start working with arrays next week...

CS 5JA Introduction to Java

More complicated logical operatorsYou can think of the AND and OR operators as kind of like plus signs. Instead of adding two numbers together, they “add” the “truth” of two conditionals.

if (true && false) evaluates to falseif( (5 > 3) && (4 < 3) ) similarly, evaluates to false

if (false || true) evaluates to trueif( (5 > 3) || (4 < 3) ) similarly, evaluates to true

So, what does this do?if (false || true && false)

Just like with mathematical operators, there is a default order of operations. The AND is evaluated first, then the OR.

So, first true && false evaluates to false, then false || false evaluates to false.

CS 5JA Introduction to Java

More complicated logical operatorsAs with mathematical operators between two numbers, it clears things up if you specify the exact order with parenthesis. First we evaluate the maths, then we evaluate the relationals, and then equalities, and then the logicals...

It’s kind of like if you are cleaning up a messy room. If you clean the floor first, then it will just get dirty when you start cleaning the table! So you have a rule. First, throw away all trash that has the potential of rotting... Second, put things on my desk into little piles... Thirdly, brush any crumbs onto floor... Fourth, sweep floors...

int num1 = 5, num2 = 6;

if ( (num1 > 0 || num2 > 0) && (num1 < 10) )

if ( (num1 > 0 || (num2 > 0 && num1 < 10) )

if ( (num1==5 || num2==5) && (num1 > num2 || num2 > num1) )

CS 5JA Introduction to Java

More complicated logical operatorsYou can also include parentheses to clarify both the mathematical and the logical operators. Mathematical operators are always evaluated first. The precedence of the operators is listed in a table in Appendix A of your book.

if ((num1=(5+3)*(4-2)) || ((num2>(6/3)) && num1== 5))

As before, you evaluate the innermost parenthesis first. If there are more than one set of parenthesis on the same level, evaluate from left to right.

CS 5JA Introduction to Java

another example of objects...See code – downloadable from syllabus...

CS 5JA Introduction to Java

Next weekWe will take a look at the Java2D graphics package and start experimenting with graphics.

We’ll also explore one more control mechanism, the switch statement.

We’ll talk more about debugging and how to troubleshoot a) syntactic errors as well as b) how to hunt down unexpected behavior that actually compiles and runs.

And we will also introduce arrays and Lists, which are primitive and non-primitive ways to store a collection of data.

Homework will be up on the website in about an hour.