CS Exam 1

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

things to avoid when trying to print a variable's value

- When you are printing the value of a variable, never put double quotes " " around the variable because that will print out the variable name letter by letter. - For example, System.out.println("score"); will print out the string "score", rather than the value 4 stored in the variable. - Normally you do not want to print out the variable name, but the value of the variable in memory. - Avoid putting a variable inside quotes " " in a print statement since that would print the variable name instead of its value.

a type

- A type is a set of values (a domain) and a set of operations on them. For example, you can do mathematical addition with ints and doubles but not with booleans and Strings.

what is a variable?

- A variable is a name associated with a memory location in the computer. Computer memory can store a value and that value can change or vary.

There are standard algorithms that utilize String traversals to:

- Find if one or more substrings has a particular property - Determine the number of substrings that meet specific criteria - Create a new string with the characters reversed

How many rows does a have if it is created as follows int[ ][ ] a = { {2, 4, 6, 8},{1, 2, 3, 4}};?

2 - The size of outer list is the number of rows. - The size of the inner list is the number of columns.

What does the following code print? for (int i = 3; i < 8; i++) { System.out.print(i + " "); }

3 4 5 6 7 - The value of i is set to 3 before the loop executes and the loop stops when i is equal to 8. So the last time through the loop i is equal to 7.

What does the following code print? for (int i = 0; i < 5; i++) { for (int j = 3; j >= 1; j--) { System.out.print("*"); } System.out.println(); }

A rectangle of 5 rows with 3 stars per row. Yes, the outer loop runs from 0 up to 5 but not including 5 so there are 5 rows and the inner loop runs from 3 down to 1 so 3 times.

object variable type

String is an object type and is the name of a class in Java - A string object has a sequence of characters enclosed in a pair of double quotes - like "Hello".

some boolean expressions that are very useful in coding

// Test if a number is positive (number > 0) //Test if a number is negative (number < 0) //Test if a number is even by seeing if the remainder is 0 when divided by 2 (number % 2 == 0) //Test if a number is odd by seeing if there is a remainder when divided by 2 (number % 2 > 0) //Test if a number is a multiple of x (or divisible by x with no remainder (number % x == 0)

conditional

A conditional uses the keyword if followed by Boolean expression inside of an open parenthesis (and a close parenthesis ) and then followed by a single statement or block of statements. - The single statement or block of statements are only executed if the condition is true. - The open curly brace { and a close curly brace } are used to group a block of statements together. It is recommended to always put in the curly braces even if you have just one statement under the if statement. - Note that there is no semicolon (;) at the end of the boolean expression in an if statement even if it is the end of that line. The semicolon goes at the end of the whole if statement, often on the next line. Or { } are used to mark the beginning and end of the block of code under the if condition.

What does the following code print? for (int i = 1; i < 7; i++) { for (int y = 1; y <= 5; y++) { System.out.print("*"); } System.out.println(); }

A rectangle of 6 rows with 5 stars per row. The outer loop runs from 1 up to 7 but not including 7 so there are 6 rows and the inner loop runs 1 to 5 times including 5 so there are 5 columns.

For Loops: Reverse String

For-loops can also be used to process strings, especially in situations where you know you will visit every character. - While loops are often used with strings when you are looking for a certain character or substring in a string and do not know how many times the loop needs to run. For loops are used when you know you want to visit every character. - For loops with strings usually start at 0 and use the string's length() for the ending condition to step through the string character by character. - The ReverseString program has a for-loop that creates a new string that reverses the string s. We start with a blank string sReversed and build up our reversed string in that variable by copying in characters from the string s.

Common Errors with If Statements

Here are some rules to follow to avoid common errors: - Always use curly brackets { and } to enclose the block of statements under the if condition. Java doesn't care if you indent the code - it goes by the { }. - Don't put in a semicolon ; after the first line of the if statement, if (test);. The if statement is a multiline block of code that starts with the if condition and then { the body of the if statement }. - Always use ==, not =, in the condition of an if statement to test a variable. One = assigns, two == tests!

Nested Ifs and Dangling Else

If statements can be nested inside other if statements. Sometimes with nested ifs we find a dangling else that could potentially belong to either if statement. - The rule is that the else clause will always be a part of the closest if statement in the same block of code, regardless of indentation.

Enhanced For-Each Loop for 2D Arrays

In this case the for (int[ ] colArray : a) means to loop through each element of the outer array which will set colArray to the current column array. Then you can loop through the value in the column array. - When applying sequential/linear search algorithms to 2D arrays, each row must be accessed then sequential/linear search applied to each row of a 2D array.

scanner class

The Scanner class has several useful methods for reading user input. A token is a sequence of characters separated by white space nextLine() - Scans all input up to the line break as a String next() - Scans the next token of the input as a String nextInt() - Scans the next token of the input as an int nextDouble() - Scans the next token of the input as a double nextBoolean() - Scans the next token of the input as a boolean

truth tables

The following table (also called a truth table) shows the result for P && Q when P and Q are both expressions that can be true or false. - An expression involving logical operators like (P && Q) evaluates to a Boolean value, true or false. As you can see below the result of P && Q is only true if both P and Q are true.

How do you create an array of 10 doubles called prices?

double[] prices = new double[10];

primitive variable types

int - which store integers (numbers like 3, -76, 20393) double - which store floating point numbers (decimal numbers like 6.3 -0.9, and 60293.93032) boolean - which store Boolean values (either true or false).

The String methods that are most often used to process strings are:

int length() : returns the number of characters in a String object. int indexOf(String str) : returns the index of the first occurrence of str; returns -1 if not found. String substring(int from, int to) : returns the substring beginning at index from and ending at index (to - 1). Note that s.substring(i,i+1) returns the character at index i. String substring(int from) : returns substring(from, length()).

Boolean expressions

Boolean variables or expressions can only have true or false values.

Incrementing the value of a variable

If you use a variable to keep score you would probably increment it (add one to the current value) whenever score should go up. You can do this by setting the variable to the current value of the variable plus one (score = score + 1) - the score variable is set to the previous value of score + 1

Declaring and Creating an Array

- When we declare a variable, we specify its type and then the variable name. - To make a variable into an array, we put square brackets after the data type. This data type will be for all the elements in the array. - The declarations do not create the array. Arrays are objects in Java, so any variable that declares an array holds a reference to an object. If the array hasn't been created yet and you try to print the value of the variable, it will print null (meaning it doesn't reference any object yet).

Testing Equality (==)

Primitive values like ints and reference values like Strings can be compared using the operators == and != (not equal) to return boolean values. - The expression x == 4 evaluates to true if the memory location for variable x currently stores the value 4, otherwise the expression is false. - Note that x == 4 does not assign a value to variable x, rather it simply compares the value of x to 4. - The operator = changes the value of a variable. The operator == tests if a variable holds a certain value, without changing its value!

how to actually create an array after declaring the variable

To actually create an array after declaring the variable, use the new keyword with the type and the size of the array (the number of elements it can hold). This will actually create the array in memory. - You can do the declaration and the creation all in one step, see the String array names below. - The size of an array is set at the time of creation and cannot be changed after that.

What are the values of x, y, and z after the following code executes? int x = 0; int y = 1; int z = 2; x = y; y = y * 2; z = 3;

x = 1, y = 2, z = 3 x changes to y's initial value, y's value is doubled, and z is set to 3

What is the result of 3 % 8?

8 goes into 3 no times so the remainder is 3. The remainder of a smaller number divided by a larger number is always the smaller number!

relational operators

The Relational Operators below in Java are used to compare numeric values or arithmetic expressions. Although some programming languages allow using relational operators like < to compare strings, Java only uses these operators for numbers, and uses the string methods compareTo() and equals() for comparing String values. - < Less Than - > Greater Than - <= Less than or equal to - >= Greater than or equal to - == Equals - != Does not equal With <= and >=, remember to write the two symbols in the order that you would say them "less than" followed by "or equal to".

Fill in the blank with code to access the cars array. String[] cars = {"Honda", "Volvo", "BMW"}; // Access cars array to get Volvo String v =

cars[1]

storing user input in variables

- A Java program can ask the user to type in one or more values. - The Java class Scanner is used to read from the keyboard input stream, which is referenced by System.in. - Normally the keyboard input is typed into a console window, but since this is running in a browser you will type in a small textbox window displayed below the code. - The code String name = scan.nextLine() gets the string value you enter as program input and then stores the value in a variable

Initializer Lists for 2D Arrays

- You can also initialize (set) the values for the array when you create it. In this case you don't need to specify the size of the array, it will be determined from the values you give. - The code below creates an array called ticketInfo with 2 rows and 3 columns. - It also creates an array called seatingInfo with 3 rows and 2 columns.

Compound Assignment Operators

Compound assignment operators are shortcuts that do a math operation and assignment in one step. For example, x += 1 adds 1 to x and assigns the sum to x. It is the same as x = x + 1. This pattern is possible with any operator put in front of the = sign, as seen below. + shortcuts x = x + 1; x += 1; x++; - shortcuts x = x - 1; x -= 1; x- -; * shortcut x = x * 2; x *= 2; / shortcut x = x / 2; x /= 2; % shortcut x = x % 2; x %= 2; - The most common shortcut operator ++, the plus-plus or increment operator, is used to add 1 to the current value; x++ is the same as x += 1 and the same as x = x + 1. - It is a shortcut that is used a lot in loops. - If you've heard of the programming language C++, the ++ in C++ is an inside joke that C has been incremented or improved to create C++. - The -- decrement operator is used to subtract 1 from the current value: y-- is the same as y = y - 1. - These are the only two double operators; this shortcut pattern does not exist with other operators.

Fill in the blank with code to access the cars array. NOTE: The semicolon is provided for you after the box. String[] cars = {"Honda", "Volvo", "BMW"}; // Set the first item of the cars array to be Toyota ______ = "Toyota"

cars[0]

Consider the following code segment. Which of the following can be used as a replacement for the missing loop header so that the loop prints out "0 2 4 6 8 10"? int count = 0; /* missing loop header */ { System.out.print(count + " "); count += 2; }

while (count <= 10)

Tracing loops

- A really important skill to develop is the ability to trace the values of variables and how they change during each iteration of a loop. - You can create a tracing table that keeps track of the variable values each time through the loop as shown below. - When you are tracing through code, pretend to be the computer running the code line by line, repeating the code in the loop, and keeping track of the variable values and output.

Nested For Loops

- A nested loop has one loop inside of another. These are typically used for working with two dimensions such as printing stars in rows and columns as shown below. - When a loop is nested inside another loop, the inner loop is runs many times inside the outer loop. - In each iteration of the outer loop, the inner loop will be re-started. - The inner loop must finish all of its iterations before the outer loop can continue to its next iteration.

Array Creation and Access

- To keep track of 10 exam scores, we could declare 10 separate variables: int score1, score2, score3, ... , score10; But what if we had 100 exam scores? That would be a lot of variables! - Most programming languages have a simple data structure for a collection of related data that makes this easier. In Java and many programming languages, this is called an array.

What is the index is for the last element of an array called highScores?

highScores.length - 1 - Since the first element in an array is at index 0 the last element is the length minus 1.

Looping Through a 2D Array

- Since you can find out the number of rows and columns in a 2D array you can use a nested for loop (one loop inside of another loop) to loop/traverse through all of the elements of a 2D array.

compiler

A compiler translates Java code into a class file that can be run on your computer.

Index Variables

In the last lesson, we mentioned that you can use a variable for the index of an array. You can even do math with that index and have an arithmetic expression inside the [], like below.

What if you want to prevent the user from choosing something other than 1 or 2 sticks?

while (humanSticks != 1 && humanSticks != 2) { System.out.println("Error. How many sticks do you want to remove?"); humanSticks = in.nextInt(); }

Decrementing Loops

You can also count backwards in a loop starting from the last number and decrementing down to 0 or 1. All 3 parts of the loop must change to count backwards including the test of when to stop. For example, "for (int i=5; i > 0; i-)`` counts from 5 down to 1.

For loops

- Another type of loop in Java is a for loop. This is usually used when you know how many times you want the loop to execute. It is often a simple counter-controlled loop to do the loop body a set number of times.

Consider the following code segment. System.out.print("Java is "); System.out.println("fun "); System.out.print("and cool!"); What is printed as a result of executing the code segment?

Java is fun and cool!

data abstraction

One powerful feature in the array data abstraction is that we can use variables for the index! As long as the variable holds an integer, we can use it as an index.

Java has two different print commands to print output to the screen:

System.out.println(value) : prints the value followed by a new line (ln) System.out.print(value) : prints the value without advancing to the next line - A print statement can also contain numeric values and arithmetic expressions. Don't use double quotes for expressions that have a numeric value.

string literal

Text enclosed by double quotes. "Hi there!" - it can have zero to many characters enclosed in starting and ending double quotes.

Prefix versus Postfix Operator

The code System.out.println(count++) adds one to the variable after the value is printed. Try changing the code to ++count and run it again. This will result in one being added to the variable beforeits value is printed. When the ++ operator is placed before the variable, it is called prefix increment. When it is placed after, it is called postfix increment. System.out.println(count++); - Print the current value of count, then add one to count - Postfix System.out.println(++count); - Add one to count, then print the new value - Prefix x = y++; - Copy the value of y into x, then add one to y - Postfix x = ++y; - Add one to y, then copy the value of y into x - Prefix x = y- -; - Copy the value of y into x, then subtract one from y - Postfix x = - -y; - Subtract one from y, then copy the value of y into x Prefix

while loop condition

The loop condition usually involves a loop control variable that controls when to stop the loop. - The simplest loops are counter-controlled loops like below, where the loop variable is a counter that controls how many times to repeat the loop. - There are 3 steps to writing a loop using this loop control variable as seen below in a loop that counts from 1 to 10. Remember these 3 steps to writing a loop: 1. Initialize the loop variable (before the while loop) 2. Test the loop variable (in the loop header) 3. Change the loop variable (in the while loop body at the end) - change meaning like add 1 to the variable so you're not putting the same variable through the loop again

Multi-Selection: else-if Statements

Using if/else statements, you can even pick between 3 or more possibilites. Just add else if for each possibility after the first if, and else before the last possibility.

compound boolean expressions

What if you want two things to be true before the body of the conditional is executed? Use && as a logical and to join two Boolean expressions and the body of the condition will only be executed if both are true. - In English, we often use an exclusive-or like in the sentence "do you want to be player 1 or player 2?" where you can't be both player 1 and player 2. In programming, the or-operator is an inclusive-or which means that the whole expression is true if either one or the other or both conditions are true. - With numerical values, the or-operator is often used to check for error conditions on different ends of the number line, while the and-operator is often used to see if a number is in an range. - The not (!) operator can be used to negate a boolean value. We've seen ! before in != (not equal). - In Java, ! has precedence (is executed before) &&, and && has precedence over ||. - Parentheses can be used to force the order of execution in a different way. - If you mix ! with && and ||, be careful because the results are often the opposite of what you think.

What type should you use to record if it is raining or not?

While you can use a string to represent "True" or "False", using a boolean variable would be better for making decisions. - Java uses boolean for values that are only true or false.

compare while and for loop

You can compare a while loop to a for loop to understand that a for loop actually executes like a while loop does if you use the while loop to repeat the body of the loop a specific number of times.

how to test for a false value

You can test for a false value using the ! operator, which is read as "not". We will see a better way to test for both true and false in the next lesson. However, the code below shows how to print different messages based on whether a value is true or false. - The TestMidterm program reads in a boolean value from standard input and tests whether the value is true if (passedExam) or false if (!passedExam).

Java

a programming language that is used worldwide to create software that we all use. - Every program in Java is written as a class. - Java is an object-oriented language - Inside the class, there can be a main method that starts the program. - When you ask the Java environment to run a class, it will always start execution in the main method.

What if there's only one stick left and you want to prevent a user from choosing more than 1 stick?

while (currentAmount == 1 && humanSticks != 1) { System.out.println("Error. How many sticks do you want to remove?"); humanSticks = in.nextInt(); }

What code do you use if you want to prevent a user from entering 0 or a negative number?

while (startAmount <= 0) { System.out.println("Error. How many sticks do you want to start with?"); startAmount = in.nextInt(); }

Array elements are initialized to default values like the following.

- 0 for elements of type int - 0.0 for elements of type double - false for elements of type boolean - null for elements of type String

template for a simple Java program with a main method:

- A Java program starts with public class NameOfClass { }. If you are using your own files for your code, each class should be in a separate file that matches the class name inside it, for example NameOfClass.java. - Most Java classes have a main method that will be run automatically. It looks like this: public static void main(String[] args) { }.

Three Parts of a For Loop

- A for-loop combines all 3 parts of writing a loop in one line to initialize, test, and change the loop control variable. - The 3 parts are separated by semicolons (;). - Each of the three parts of a for loop declaration is optional (initialization, condition, and change), but the semicolons are not optional. - The for-loop is almost a shortcut way to write a while loop with all three steps that you need in one line. - One of the strange things about a for loop is that the code doesn't actually execute where you see it in the declaration. The code in the initialization area is executed only one time before the loop begins, the test condition is checked each time through the loop and the loop continues as long as the condition is true, and the loop control variable change is done at the end of each execution of the body of the loop, just like a while loop. - When the loop condition is false, execution will continue at the next statement after the body of the loop.

declaring variables in Java

- A variable allows you to store a value in a named memory location. - To create a variable, you must tell Java its data type and its name. - Creating a variable is also called declaring a variable. - The type is a keyword like int, double, or boolean, but you get to make up the name for the variable. - When you create a primitive variable Java will set aside enough bits in memory for that primitive type and associate that memory location with the variable name that you used. To declare (create) a variable, you: 1. specify the type 2. leave at least one space 3. then the name for the variable and end the line with a semicolon (;). Java uses the keyword int for integer, double for a floating point number (a double precision number), and boolean for a Boolean value (true or false). EX: declaration of a variable called score that has type int. int score; After declaring a variable, you can give it a value like below using an equals sign = followed by the value. - The first time a variable is assigned a value is referred to as variable initialization. int score; score = 4; Or you can set an initial value for the variable in the variable declaration. Here is an example that shows declaring a variable and initializing it all in a single statement. int score = 4; - The equal sign here = doesn't mean the same as it does in a mathematical equation where it implies that the two sides are equal. - Here it means set the value in the memory location associated with the variable name on the left to a copy of the value on the right. The line above sets the value in the memory location called score to 4.

while loop

- A while loop executes the body of the loop as long as (or while) a Boolean condition is true. When the condition is false, we exit the loop and continue with the statements that are after the body of the whileloop. If the condition is false the first time you check it, the body of the loop will not execute. - Notice the while statement looks a lot like an if statement, but it runs more than once. The curly brackets { } are optional when there is just 1 statement following the condition, but required if there are more than 1 statement in the loop. Always using curly brackets is a good practice to follow.

comments

- Adding comments to your code helps to make it more readable and maintainable. In the commercial world, software development is usually a team effort where many programmers will use your code and maintain it for years. Commenting is essential in this kind of environment and a good habit to develop. Comments will also help you to remember what you were doing when you look back to your code a month or a year from now. There are 3 types of comments in Java: 1. // Single line comment 2. /* Multiline comment */ 3. /** Documentation comment */ - In Java and many text-based coding languages, // is used to mark the beginning of a comment. Everything on the line that follows the // is ignored by the compiler. - For multi-line comments, use /*to start the comment and */ to end the comment. - There is also a special version of the multi-line comment, /** */, called the documentation comment. Java has a cool tool called javadoc that will pull out all of these comments to make documentation of a class as a web page.

array

- An array is a block of memory that stores a collection of data items (elements) of the same type under one name. - Arrays are useful whenever you have many elements of data of the same type that you want to keep track of, but you don't need to name each one. Instead you use the array name and a number (called an index) for the position of an item in the array. - You can make arrays of ints, doubles, Strings, and even classes that you have written like Students. - An array is like a row of small lockers, except that you can't cram lots of stuff into it. You can only store one value at each locker. - You can store a value in an array using an index (location in the array). An array index is like a locker number. It helps you find a particular place to store your stuff and retrieve stuff. You can get or store a value from or to an array using an index. - Arrays and lists in most programming languages start counting elements from the number 0, so the first element in an array is at index 0. This is similar to how Strings are indexed in Java - the first character is at index 0.$

Initializer Lists

- Another way to create an array is to use an initializer list. - You can initialize (set) the values in the array to a list of values in curly brackets { } when you create it, like below. - In this case you don't specify the size of the array, it will be determined from the number of values that you specify.

2D Arrays

- Arrays in Java can store many items of the same type. - You can even store items in two-dimensional (2D) arrays which are arrays that have both rows and columns. - A row has horizontal elements. - A column has vertical elements. - Two dimensional arrays are especially useful when the data is naturally organized in rows and columns like in a spreadsheet, bingo, battleship, theater seats, classroom seats, or a picture. In the picture below there are 3 rows of lockers and 6 columns.

Nested Loops for 2D Arrays: Getting the number of rows and columns

- Arrays know their length (how many elements they can store). - The length is a public read-only field so you can use dot-notation to access the field (arrayName.length) - The length of the outer array is the number of rows and the length of one of the inner arrays is the number of columns.

short circuit evaluation

- Both && and || use short circuit evaluation. - That means that the second condition isn't necessarily checked if the result from the first condition is enough to tell if the result is true or false. - In a complex conditional with a logical and (&&) both conditions must be true, so if the first is false, then the second doesn't have to be evaluated. - If the complex conditional uses a logical or (||) and the first condition is true, then the second condition won't be executed, since only one of the conditions needs to be true.

code tracing

- Code Tracing is a technique used to simulate by hand a dry run through the code or pseudocode as if you are the computer executing the code. Tracing can be used for debugging or proving that your program runs correctly or for figuring out what the code actually does. - Trace tables can be used to track the values of variables as they change throughout a program. To trace through code, write down a variable in each column or row in a table and keep track of its value throughout the program. Some trace tables also keep track of the output and the line number you are currently tracing.

using the math class

- Games would be boring if the same thing happened each time you played the game. Games often use random numbers to generate different possibilities. You need to know how to use the Math.random()method to generate a random number. - There are lots of mathematical methods that you might want to use in your programs like Math.abs(absolute value). - These methods are in the Math class defined in the java.lang package. - These are static methods which means you can call them by just using ClassName.methodName() without creating an object or just the method name if they are called from within the same class. - Static methods (also called class methods) are called using the class name and the dot operator . followed by the method name, for example Math.random(). You do not need to create an object of the class to use them

casting and ranges of variables

- In Java, type casting is used to convert variables from one type to another. - By casting we don't mean something to do with fishing, but it is a similar idea to casting a pot in clay. In Java when you cast you are changing the "shape" (or type) of the variable. - The casting operators (int) and (double) are used right next to a number or variable to create a temporary value converted to a different data type. - For example, (double) 1/3 will give a double result instead of an int one. - Java assumes that if you are doing division with integers that you want an integer result and it will truncate and throw away the part after the decimal point. - But, if you use a mixture of integers (int) and decimal (double) numbers Java will assume that you want a double result. - If there is at least one double in the operation, Java will widen the type of the other operand to double too and return the result in a double. - If you have integers and you want a double result from some mathematical operation cast one of the integers to a double using (double) as shown above. Values of type double can be rounded to the nearest integer by adding or subtracting .5 and casting with (int) using formulas like the following. Note int nearestInt = (int)(number + 0.5); int nearestNegInt = (int)(negNumber - 0.5);

flowchart

- In industry, a flowchart is used to describe a process through symbols and text. - A flowchart usually does not show variable declarations, but it can show assignment statements (drawn as rectangle) and output statements (drawn as rhomboid). - The flowchart in figure 3 shows a process to compute the fair distribution of pizza slices among a number of people. - The process relies on integer division to determine slices per person, and the mod operator to determine remaining slices. - A flowchart shows pseudo-code, which is like Java but not exactly the same. Syntactic details like semi-colons are omitted, and input and output is described in abstract terms

How Java Stores 2D Arrays

- Java actually stores two-dimensional arrays as arrays of arrays. - Each element of the outer array has a reference to each inner array. - The picture below shows a 2D array that has 3 rows and 7 columns. - Notice that the array indices start at 0 and end at the length - 1. - On the exam assume that any 2 dimensional (2D) array is in row-major order. - The outer array can be thought of as the rows and the inner arrays the columns.

what happens to repeating decimal numbers like 3.33333....?

- Java limits the number of digits you can save for any double number to about 14-15 digits. You should be aware that the accuracy of any calculation on a computer is limited by the fact that computers can only hold a limited number of digits - For example, int values are stored in 4 bytes of memory. There is an Integer.MAX_VALUE defined as 2147483647 and an Integer.MIN_VALUE defined as -2147483648. If you try to store any number larger or smaller than these numbers in an int variable, it will result in an error called integer overflow. - If an expression would evaluate to an int value outside of the allowed range, an integer overflow occurs. This could result in an incorrect value within the allowed range.

Operators

- Java uses the standard mathematical operators for addition (+), subtraction (-), multiplication (*), and division (/). - Arithmetic expressions can be of type int or double. - An arithmetic operation that uses two int values will evaluate to an int value. - An arithmetic operation that uses at least one double value will evaluate to a double value. - Java uses the operator == to test if the value on the left is equal to the value on the right and != to test if two items are not equal. - Don't get one equal sign = confused with two equal signs ==! They mean different things in Java. One equal sign is used to assign a value to a variable. Two equal signs are used to test a variable to see if it is a certain value and that returns true or false as you'll see below. - Use == and != only with int values and not doubles because double values are an approximation and 3.3333 will not equal 3.3334 even though they are very close.

Loops and Strings

- Loops are often used for String Traversals or String Processing where the code steps through a string character by character. - Remember that strings are a sequence of characters where each character is at a position or indexstarting at 0. - The first character in a Java String is at index 0 and the last characters is at length() - 1. So loops processing Strings should start at 0!

Counting Loop Iterations

- Loops can be also analyzed to determine how many times they run. This is called run-time analysis or a statement execution count. The number of times a loop executes can be calculated by (largestValue - smallestValue + 1). - If the loop uses counter <= limit, limit is the largest value. - If the loop uses counter < limit, limit-1 is the largest value that allows the loop to run. - The number of times a nested for loop body is executed is the number of times the outer loop runs multiplied by the number of times the inner loop runs (outer loop runs * inner loop runs).

Array Storage

- Many programming languages actually store two-dimensional array data in a one-dimensional array. - The typical way to do this is to store all the data for the first row followed by all the data for the second row and so on. - This is called row-major order. - Some languages store all the data for the first column followed by all the data for the second column and so on. - This called column-major order.

capitalization and semicolons

- Most command keywords in Java must be in lowercase, but class names such as System and String are capitalized. - Commands in Java must end with a semicolon ; - Think of the semicolon ; in Java like a period in English. - You use a semicolon ; to show the end of a Java statement, just the way you use a period to show the end of an English sentence. - Your programs won't run if you forget the semicolon at the end of each statement.

Relational Operators in If Statements

- Most if statements have a boolean condition that uses relational operators like ==, !=, <, >, <=, >= - A common mistake in if statements is using = instead of == in the condition by mistake. You should always use ==, not =, in the condition of an if statement to test a variable. One equal sign (=) assigns a value to a variable, and two equal signs (==) test if a variable has a certain value.

See the examples below in Java that loop through an int and a String array.

- Notice the type of the loop variable is the type of the array. - Use the enhanced for each loop with arrays whenever you can, because it cuts down on errors. - You can use it whenever you need to loop through all the elements of an array and don't need to know their index and don't need to change their values. - It starts with the first item in the array (the one at index 0) and continues through in order to the last item in the array. - This type of loop can only be used with arrays and some other collections of items like ArrayLists which we will see in the next unit.

common errors with loops

- One common error with loops is infinite loops. An infinite loop is one that never stops (the condition is always true). - The infinite loop above is pretty obvious. But, most infinite loops are accidental. They usually occur because you forget to change the loop variable in the loop (step 3 of a loop). - Another common error with loops is an off-by-one error where the loop runs one too many or one too few times. This is usually a problem with step 2 the test condition and using the incorrect relational operator < or <=.

compound expressions with operators

- Operators can be used to create compound expressions with more than one operator. - You can either use a literal value which is a fixed value like 2, or variables in them. - When compound expressions are evaluated, operator precedence rules are used, so that *, /, and % are done before + and -. - However, anything in parentheses is done first. It doesn't hurt to put in extra parentheses if you are unsure as to what will be done first.

conditional control flow

- Recall the program to compute the number of pizza slices per person from Module 1. - it fails when a value of 0 is entered for numPeople (second input value). - To avoid division by 0, the calculation for slicesPerPerson and leftoverSlices should be skipped when the number of people is 0. - In fact, the calculation is nonsense if the number of people is a negative number so the program should check if a positive value is read from input. - The program should actually ensure positive values are input for both the number of people and number of pizza slices, but for now you will only test the number of people. You will see how to test compound boolean expressions in a later lesson. - The flowchart in Figure 2 demonstrates the desired control flow based on an if statement, represented with a diamond symbol. If the condition numPeople > 0 is true, the process follows the path labelled true, which contains the 4 steps to calculate and print slicesPerPerson and leftoverSlices. The 4 statements along the true branch must be nested within curly braces in a Java program otherwise only the first step would be considered part of the true branch. If the condition numPeople > 0 is false, the false branch is followed and the 4 statements for calculating and printing are skipped.

Assignment statements

- Remember that a variable holds a value that can change or vary. - Assignment statements initialize or change the value stored in a variable using the assignment operator =. - An assignment statement always has a single variable on the left hand side of the = sign. - The value of the expression on the right hand side of the = sign (which can contain math operators and other variables) is copied into the memory location of the variable on the left hand side. - Instead of saying equals for the = operator in an assignment statement, say "gets" or "is assigned" to remember that the variable on the left hand side gets or is assigned the value on the right. - In the figure above, score is assigned the value of 10 times points (which is another variable) plus 5.

the modulo operator

- The percent sign operator (%) is the mod (modulo) or remainder operator. - The mod operator (x % y) returns the remainder after you divide x (first number) by y (second number) so 5 % 2 will return 1 since 2 goes into 5 two times with a remainder of 1. Remember long division when you had to specify how many times one number went into another evenly and the remainder? - that remainder is what is returned by the modulo operator. The result of x % y when x is smaller than y is always x. The value y can't go into x at all (goes in 0 times), since x is smaller than y, so the result is just x. So if you see 2 % 3 the result is 2.

if statements

- The statements in a Java main method normally run or execute one at a time in the order they are found. - If statements (also called conditionals or selection) change the flow of control so that certain lines of code only run when something is true. - An if statement checks a boolean condition that is either true or false. - A block of statements will execute if the condition is true and will be skipped if the condition is false.

enhanced for-loop (for-each) for arrays

- There is a special kind of loop that can be used with arrays called an enhanced for loop or a for each loop. - This loop is much easier to write because it does not involve an index variable or the use of the []. - It just sets up a variable that is set to each value in the array successively. - To set up a for-each loop, use for (type variable: arrayname) where the type is the type for elements in the array, and read it as "for each variable value in arrayname".

Access and Modify Array Values

- To access the items in an array, we use an indexed array variable which is the array name and the index inside of square bracket [ ]. - Remember that an index is a number that indicates the position of an item in a list, starting at 0. - An indexed variable like arrayname[index] can be used anywhere a regular variable can be used, for example to assign a new value or to get a value from the array like below. - The first value in an array is stored at index 0 and the index of the last value is the length of the array minus one (since the first index is 0). Use arrayname[index] to access or modify array items. - Using an index value outside of 0 - (length-1) will result in an ArrayIndexOutOfBoundsException being thrown.

creating a 2D array

- To create an array use the new keyword, followed by a space, then the type, and then the number of rows in square brackets followed by the number of columns in square brackets, like this newint[numRows][numCols]. - The code below creates a 2D array with 2 rows and 3 columns named ticketInfo and a 2D array with 3 rows and 2 columns named seatingChart. - The number of elements in a 2D array is the number of rows times the number of columns.

Declaring 2D Arrays

- To declare a 2D array, specify the type of elements that will be stored in the array, then ([ ][ ]) to show that it is a 2D array of that type, then at least one space, and then a name for the array. - Note that the declarations below just name the variable and say what type of array it will reference. - The declarations do not create the array. - Arrays are objects in Java, so any variable that declares an array holds a reference to an object. - If the array hasn't been created yet and you try to print the value of the variable, it will print null (meaning it doesn't reference any object yet).

Get a value from a 2D Array

- To get the value in a 2D array give the name of the array followed by the row and column indicies in square brackets. - The code below will get the value at row index 1 and column index 0 from ticketInfo. - It will also get the value at row index 0 and column index 1 from seatingChart.

two common patterns in for-loops

- Two common patterns in for-loops are to count from 0 up to an number (using <) or count from 1 to the number including the number (using <=). - Remember that if you start at 0 use <, and if you start at 1, use <=. - The two loops below using these two patterns both run 10 times. The variable i (for index) is often used as a counter in for-loops.

the modulo operator has a lot of great uses

- Use it to check for odd or even numbers (num % 2 == 1) is odd and (num % 2 == 0) is even. Actually, you can use it to check if any number is evenly divisible by another (num1 % num2== 0) - Use it to get the last digit from an integer number (num % 10 = last digit on right). - Use it to get the number of minutes left when you convert to hours (num % 60). - Use it whenever you have limited storage and you need to wrap around to the front if the value goes over the limit (num % limit).

For Loop to Traverse Arrays

- We can use iteration with a for loop to visit each element of an array. - This is called traversing the array. - Just start the index at 0 and loop while the index is less than the length of the array. - Note that the variable i (short for index) is often used in loops as the loop counter variable and is used here to access each element of an array with its index. note: Using a variable as the index is a powerful data abstraction feature because it allows us to use loops with arrays where the loop counter variable is the index of the array! This allows our code to generalize to work for the whole array.

Foreach Loop Limitations

- What if we had a loop that incremented all the elements in the array. Would that work with an enhanced for-each loop? - Unfortunately not! Because only the variable in the loop changes, not the real array values. We would need an indexed loop to modify array elements. Enhanced for each loops cannot be used in all situations. Only use for-each loops when you want to loop through all the values in an array without changing their values. - Do not use for each loops if you need the index. - Do not use for each loops if you need to change the values in the array. - Do not use for each loops if you want to loop through only part of an array or in a different order.

Two-way selection: if-else statements

- What if you want to pick between two possibilities? - If you are trying to decide between a couple of things to do, you might flip a coin and do one thing if it lands as heads and another if it is tails. - In programming, you can use the if keyword followed by a statement or block of statements and then the else keyword also followed by a statement or block of statements. Note: The else will only execute if the condition is false. - If/else statements can also be used with relational operators and numbers like below. If your code has an if/else statement, you need to test it with 2 test-cases to make sure that both parts of the code work.

Set Value(s) in a 2D Array

- When arrays are created their contents are automatically initialized to 0 for numeric types, null for object references, and false for type boolean. - To explicitly put a value in an array, you can use assignment statements with the name of the array followed by the row index in brackets followed by the column index in brackets and then an = followed by a value

Common Errors When Looping Through an Array

- When processing all array elements, be careful to start at the first index which is 0 and end at the last index. - Usually loops are written so that the index starts at 0 and continues while the index is less than arrayName.length since (arrayName.length - 1) is the index for the last element in the array. - Make sure you do not use <= instead of <! If the index is less than 0 or greater than (arrayName.length - 1), an ArrayIndexOutOfBoundsException will be thrown. - Off by one errors, where you go off the array by 1 element, are easy to make when traversing an array which result in an ArrayIndexOutOfBoundsException being thrown.

create array of primitive type and object type

- When you create an array of a primitive type (like int) with initial values specified, space is allocated for the specified number of items of that type and the values in the array are set to the specified values. - When you create an array of an object type (like String) with initial values, space is set aside for that number of object references. The objects are created and the object references set so that the objects can be found. - Arrays know their length (how many elements they can store). - It is a public read-only instance variable so you can use dot-notation to access the instance variable (arrayName.length) - Dot-notation is using variable name followed by a . and then the instance variable (property) name or a method name. Try the following. - Note that length is an instance variable and not a method, unlike the String length() method, so you don't add parentheses after length. The length instance variable is declared as a publicfinal int. public means you can access it and final means the value can't change.

loops

- When you play a song, you can set it to loop, which means that when it reaches the end it starts over at the beginning. - A loop in programming, also called iteration or repetition, is a way to repeat one or more statements. - If you didn't have loops to allow you to repeat code, your programs would get very long very quickly! - Using a sequence of code, selection (ifs), and repetition (loops), the control structures in programming, you can construct an algorithm to solve almost any programming problem!

Naming Variables

- While you can name your variable almost anything, there are some rules. A variable name should start with an alphabetic character (like a, b, c, etc.) and can include letters, numbers, and underscores _. It must be all one word with no spaces. - You can't use any of the keywords or reserved words as variable names in Java (for, if, class, static, int, double, etc). - The name of the variable should describe the data it holds. A name like score helps make your code easier to read. A name like x is usually not a good variable name in programming, because it gives no clues as to what kind of data it holds. Do not name your variables crazy things like thisIsAReallyLongName. You want to make your code easy to understand, not harder. - The convention in Java and many programming languages is to always start a variable name with a lower case letter and then uppercase the first letter of each additional word. Variable names can not include spaces so uppercasing the first letter of each additional word makes it easier to read the name. Uppercasing the first letter of each additional word is called camel case. Another option is to use underscore _ to separate words, but you cannot have spaces in a variable name. - Use meaningful variable names! - Start variable names with a lower case letter and use camelCase. - Variable names are case-sensitive and spelling sensitive! Each use of the variable in the code must match the variable name in the declaration exactly. Never put variables inside quotes (" "), unless you actually want to print the name of the variable rather than its value.

String Concatenation

- You often need to print a message that mixes text with a variable value. You can use the string concatenation operator + to combine strings. - So "hi " + "there" will create a new String object with the value "hi there". - If the variable name has a value "Jose", then the code "Hi " + name will create a new String object with value "Hi Jose". - Also note that the variable has to be on the left side of the = and the value on the right. Switching the two is called assignment dyslexia.

other math functions that you can use

- int abs(int) : Returns the absolute value of an int value (which is the value of a number without its sign, for example Math.abs(-4) = 4). - double abs(double) : Returns the absolute value of a double value. - double pow(double, double) : Returns the value of the first parameter raised to the power of the second parameter. - double sqrt(double) : Returns the positive square root of a double value. - double random() : Returns a double value greater than or equal to 0.0 and less than 1.0 (not including 1.0!).

syntax errors

- reported to you by the compiler if your Java code is not correctly written - Examples of syntax errors are a semicolon ; missing or if the code has a open curly brace { or open quote ", but no close curly brace } or close quote ". - Informally, a syntax error is called a bug, and the process of removing errors is called debugging. - The compiler tries to make sense of your code, but if your code has syntax errors, you will see error messages displayed below the code. - Compiler error messages will tell the line number that the compiler found the error and the type of error. - The error messages are not always easy to understand and sometimes the actual error is before the line that the compiler says is the problem. - Debugging can be frustrating but you will get better at it with practice! - an error detected by the compiler is called a compile time error

Here are some examples that move a random number into a specific range.

// Math.random() returns a random number between 0.0-0.99. double rnd = Math.random(); // rnd1 is an integer in the range 0-9 (including 9). int rnd1 = (int)(Math.random()*10); // rnd2 is in the range 1-10 (including 10). The parentheses are necessary! int rnd2 = (int)(Math.random()*10) + 1; // rnd3 is in the range 5-10 (including 10). The range is 10-5+1 = 6. int rnd3 = (int)(Math.random()*6) + 5; // rnd4 is in the range -10 up to 9 (including 9). The range is doubled (9 - -10 + 1 = 20) and the minimum is -10. int rnd4 = (int)(Math.random()*20) - 10;

Consider the following code segment. What is count's value after running this code segment? (To trace through the code, keep track of the variable count and its value through each iteration of the loop.) int count = 1; while (count <= 10) { count *= 2; } count = count - 10;

6 Yes, the loop will keep multiplying count by 2 to get 2, 4, 8, 16 and then it subtracts 10 from 16 after the loop.

while find and replace loop

A while loop can be used with the String indexOf method to find certain characters in a string and process them, usually using the substring method. - The example in the mixed up code below finds and removes all the letter a's in a string.

The following table shows the result for P || Q when P and Q are both expressions that can be true or false.

As you can see below the result of P || Q is true if either P or Q is true. It is also true when both of them are true.

What does the following code print? (To trace through the code, keep track of the variable x and its value, the iteration of the loop, and the output every time through the loop.) int x = -5; while (x < 0) { x++; System.out.print(x + " "); }

-4 -3 -2 -1 0 x is set to -5 to start but then incremented by 1 so it first prints -4.

data types

There are two types of variables in Java: primitive variables that hold primitive types and object variables that hold a reference to an object of a class. - A reference is a way to find the object (like a UPS tracking number helps you find your package)

math.random

You can use Math.random and a cast to integer to return a random integer between some starting and ending value. The code below will create a random integer from 0 to 9. Remember that casting a double value to integer (int) will throw away any values after the decimal point. - Math.random() returns a random number between 0.0-0.99. - (int)(Math.random()*range) + min moves the random number into a range starting from a minimum number. - The range is the (max number - min number + 1).

negation!

You can use the ! operator to negate the value of a Boolean expression. When you see !, think of the word "not".


Ensembles d'études connexes

Anatomy 1 ch 11 - How Skeletal Muscles Produce Movement

View Set

Chapter 17 the uterus and Vagina

View Set

8. Motivace a týmová práce v řízení

View Set