COMPSCI 121 EXAM 1

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Given a non-negative number x, which expression has the range -10 to 10?

(x%21)-10 x % 21 yields 0 to 20. Then - 10 yields -10 to 10.

Which gets the tens digit of x. Ex: If x = 693, which yields 9?

(x/10) % 10 x / 10 shifts right one place, putting the tens digit in the ones place. Then % 10 gets the (new) ones digit. Ex: 693 / 10 is 69, then 69 % 10 is 9.

compound operators

+=, -=, *=, /=, %= special operators that provide a shorthand notation for statements that change a variable EX: userAge += 1 being short for userAge = userAge + 1

Random class

- this class provided by Java is used to generate random numbers - part of the java.util package class provides methods that return a random integer in the range −231 to 231−1 or a programmer-defined range.

Using the Java Rectangle class

-contains for instance members for the X and Y location of the rectangle upper left corner, width, and height EX: new Rectangle(40, 80, 100, 120) Creates a rectangle w/ upper left corner at location (40,80) and size that is 100 units wide by 120 units high Rectangle class has mutator methods to manipulate size and location: -setSize(width, height) changes the width and height -setLocation(xLoc,yLoc) method changes the location of upper left corner -translate(xDist,yDist) repositions rectangle by specified distances in the x and y direction EX: translate(30,40) moves the rectangle to the right 30 units and downward 40 units NOTE: X-axis increases to the right and y-axis increases downard

class

-defines a type that groups data and methods to form an object ( like a blueprint explaining how to create objects and an instruction manual explaining how to use an object) -A class' public methods define the operations that can be performed on objects of that class type. EX: Declare and create a new object of type PeopleCounter named passengerCounter PeopleCounter passengerCounter = new PeopleCounter( ); SEE NOTES FOR EXPLANATION

Precedence rules for arithmetic operators

1: ( ) [evaluated first] 2: unary- [used for negation (unary minus) is next, like in 2*-x the -x is evaluated 1st w/ result *2] 3: */% next [evaluated] 4: + - last evaluated 5: note if one or more operators of equal precedence could be evaluated, evaluation occurs left to right

method stub (stub)

???

Constructor and method details

A detailed description of all constructors and methods for the class. For each method, the documentation provides the method declaration, a description of the method, a list of parameters (if any), a description of the method's return value, and a list of possible exceptions the method may throw (discussed elsewhere).

constructor

A method for creating an object in a class. Special method for an object that is called whenever a new object is created, and is used to initialize the objects internal data. A class may define more than 1 constructor. The Histogram( ) part of the statement indicates which constructor should be called Default constructor: a constructor that doesn't require arguments

Accessor

A method used to examine an attribute of an object without changing it. -method accesses the objects but doesn't modify the internal data EX: the printHistogram( ) method for a Histogram is an accessor (bc it must read the objects internal data to print the Histogram but it doesn't change the data)

incremental development

A program development plan intended to avoid debugging by adding and testing only a small amount of code at a time. Process of writing compiling and testing a small amount of code then writing compiling and testing a small amount more

string

A sequence of characters

Method call

A statement that invokes an objects method, allowing the program to perform a particular operation on that object EX: writing a method call to perform an operation on an object objectName.methodName( ); The "." Operator is also known as the member access operator

Javadoc -doc comments

A tool which will create an API(application programming interface) for a class or package. The specially formatted comments for Javadoc are called Doc comments, which are multi-line comments consisting of all text enclosed between the /** and */ characters.

escape sequence:

A two-character sequence starting with \ that represents a special character. Ex: '\n' represents a newline character. Escape sequences also enable representing characters like ', ", or \. Ex: myChar = '\'' assigns myChar with a single-quote character. myChar = '\\' assigns myChar with \ (just '\' would yield a compiler error, since \' is the escape sequence for ', and then a closing ' is missing).

character type char character literal

A variable of char type, as in char myChar;, can store a single character like the letter m. A character literal is surrounded with single quotes, as in myChar = 'm';.

Constant Variable

A variable that is not changed An initialized variable whose value cannot change is called a constant variable. A constant variable is also known as a final variable. A common convention, or good practice, is to name constant variables using upper case letters with words separated by underscores, to make constant variables clearly visible in code.

What's a class in programming? A class type?

ANSWER IT

ASCII

American Standard Code for Information Interchange is an early standard for encoding characters as numbers.

type cast

An operation that explicitly converts one data type into another. In Java it appears as a type name in parentheses, like (int). A programmer can precede an expression with (type) to convert the expression's value to the indicated type. Ex: If myIntVar is 7, then (double)myIntVar converts int 7 to double 7.0. A common type cast converts a double to an int. Ex: myInt = (int)myDouble. The fractional part is truncated. Ex: 9.5 becomes 9.

Get prefix of a phone number.

Dividing by a power of 10 shifts a value right. 321 / 10 is 32. 321 / 100 is 3. % by a power of 10 gets the rightmost digits. 321 % 10 is 1. 321 % 100 is 21. / : how many times a digit goes in % : move the decimal, 10 is the tens, 100 is the 100th

Common escape sequences

Escape sequence Char \n newline \t tab \' single quote \" double quote \\ backslash

Debugging

Finding and fixing problems in your algorithm or program. (Aka troubleshooting) Methodical debugging process: 1: predict possible cause of prob 2: conduct a test to validate cause 3: repeat NOTE: statements inserted for debugging must be created/removed with care

Module

Group of related packages

Parameter

Input specified in a method EX: in setNumberOfBins(int numberBins) The method has a parameter of type int named numberBins A parameter is like a variable declaration. Upon a call, the parameter's memory location is allocated, and the parameter is assigned with the argument's value. Upon return, the parameter is deleted from memory. NOTE: A parameter, like a variable declaration, cannot be an expression.

in order to use a math class a programmer must precede the method with

Math. -A programmer must precede the method name with Math. to call a Math class method. -EX: Math.sqrt(49); is 7

Mutator

Method may modify ("mutate") the object thereby changing the objects internal data

Return value

Methods can perform operations to return a value

divide-by-zero error

Occurs at runtime if a divisor is 0, causing a program to terminate. A divide-by-zero error is an example of a runtime error, a severe error that occurs at runtime and causes a program to terminate early

Method arguments

Programmers influence the behavior of methods by providing additional input values called "method arguments" in a method call

Method summary

Provides a list and brief description of all methods that can be called on objects of the class. The Java documentation only lists the public methods that a program may use.

Constructor summary

Provides a list and brief description of the constructors that can be used to create objects of the class.

Creating and object and assigning a variable w/ that object involves 3 parts

Reference variable New operator Constructor

the print and println statements output various values

System.out.print("Salary is"); System.out.println(wage*40*50); produces: Salary is 40000

Outputting text is achieved via:

System.out.print("desired text");

newline

System.out.println (note the ln at the end, short for "line"), starts a new output line after the outputted values, called newline

Comment

Text programmer adds to code to be read by humans to better understand the code but ignored by the compiler Single line comment: starts with // and includes all the following text on that line (commonly appears after a statement on the same line) Multi line comment: starts with /* and ends with */ where all text btwn is part of the comment (aka a block comment)

Modular development

The process of dividing a program into separate modules that can be developed and tested separately and then integrated into a single program.

Argument

The value passed to a parameter (multiple are separated by commas w/in the parentheses of a method call) assigned by position: 1st argument to 1st parameter, 2nd to 2nd etc EX: write a method call that sets the value of bin 1 to the value 10 for a Histogram object named coinFlipHistogram coinFlipHistogram.setBinValue(1, 10)

integer rounding

When the operands of / are integers, the operator performs integer division, which does not generate any fraction. EX: 10/4 would equal 2 (if both indicated at integers) 1/3 would equal 0 But if at least one is indicated as a double... ie: 10/4.0 then the answer is regular 2.5

this.classMember

Within a member method, the implicitly-passed object reference is accessible via the keyword this. In particular, a class member can be accessed as this.classMember. The "." is the member access operator. Using this makes clear that a class member is being accessed and is essential if a field member and parameter have the same identifier. EX: In addNumYears(), which line adds the parameter numYears to the existing value of field numYears? this.numYears = this.numYears + numYears;

Syntax error

a # refers to the # line in the code where the error occurs (sometimes syntax errors exist before the reported line)

class members

a class' fields and methods are collectively called class members A programmer defining a class first names the class, declares private fields, and defines public member methods.

Field member

a constant member in a class

identifier

a named created by a programmar for an item like a variable/method -must be a sequence of letters(a-z,A-Z), underscore(_), dollar sign($), and digits (0-9) -must start with a letter, underscore, or dollar sign NOTE: case sensitive

Algorithm

a sequence of instructions that solves a problem

variable declaration

a statement that declares a new variable, specifying the variable's name and type. Ex: int userAge; declares a new variable names userAge that can hold an integer value -note a programmer must declare a variable before any statement that assigns or reads the variable, so that the variable's memory location is known.

operator

a symbol that indicates what mathematical operation to perform on the operands: plus (+), minus (-), multiply (*), divide (/) symbol that performs a built in calculation

scanner

a text parser that can read numbers, words, or phrases from an input source such as the keyboard -getting input is achieved by first creating a scanner object via the statement: Scanner scnr = new Scanner(System.in); -the System.in corresponds to keyboard input. Then, given Scanner object scnr, the following statement gets an input value and assigns x with that value: x = scnr.nextInt();

reserved word/keyword

a word that is part of the language, like int, short, or double -cannot be used as an identifier (see list of words)

public methods

allow external code to manipulate the object -operations that can be called on an object as those operations can be called from outside the object

Incrementing the variable

alter the value of the loop control variable by adding 1 (increasing a variables value by 1) Note: a variable can appear on both sides of an equal sign [x=x+1] so if x=6 to start x is now assigned with the value 7

logic error (bug)

an error that occurs while a program runs adding something instead of multiplying -a compiler will sometimes report a warning which doesn't stop the compiler from creating an executable program but indicates a possible logic error

integer literal

an integer like 80 appearing in an expression -specific value in code like 2 NOTE: commas aren't allowed in integer literal so 1,333,555 is written as 1333555

new operator

an operator that allocates new objects -the next part of the statement, new Histogram( ) creates a new object by allocating memory for the object and initializing the object by calling a constructor

assignment

assigns a variable w/ a value [ie: x=5] x=5 is read as "x is assigned w/ 5"

assignment statement

assigns the variable on the left side of the = with the current value of the right-side expression

Doc comments

begin with /** and end with */; only describe specific program items, like methods or classes. tag section of the Doc comment may include block tags such as @author and @version to specify the class' author and version number respectively Programmers can use the @param and @return block tags to specify a method parameter and method return value respectively.

Whitespace

blank spaces between items within a statement -blank lines btwn statements called newlines

expression

combo of items like variables,literals,operators, and parentheses that evaluates to a value like 2*(x+1), commonly used on right side of an assignment ie: y=2*(x+1) can be a number like 80, variable name like numApples or simple calculation like numApples + 1

Computational Thinking

creating a sequence of instructions to solve a problem

class construct

defines a new type that can group data and methods to form an object

return statement

ends a method and frequently sends a value from a called method back to the calling method NOTE: -a method can only return one item -A void return type means the method returns no value. (cannot be assigned a variable Ex: A method that outputs data may have no need to return a value. The method typically has no return statement (but may have: return; with no expression).

modulo operator (%)

evaluates the remainder of the division of two integer operands. Ex: 23 % 10 is 3. Examples: 24 % 10 is 4. Reason: 24 / 10 is 2 with remainder 4. 50 % 50 is 0. Reason: 50 / 50 is 1 with remainder 0. 1 % 2 is 1. Reason: 1 / 2 is 0 with remainder 1. Note that any odd number % 2 is 1, while any even number % 2 is 0. ie: 50%2 = 0 51%2=1 NOTE ERRORS: ex: 100 % (1 / 2) = 100/0 which is an error

floating-point numeric data types

float x; double x;

randGen.nextInt(13) + 6

generates a random integer btwn 6 and 18 The passed number is the range size, so 18 - 6 + 1 = 13, which yields 0 to 12. That range is shifted by 6 to yield 6 to 18. to actually print the value use System.out.println(randGen.nextInt(13)+6);

The method scnr.nextLine()

gets all remaining text on the current input line, up to the next newline character (which is removed from input but not put in stringVar). What does the following statement get into the indicated variable, for the given input? firstString = scnr.nextLine(); secondString = scnr.nextLine(); 1) Hello there! Welcome. firstString gets _____ . Hello there! 1) NOTE if firstString= scnr.next(); then the firstString gets Hello (stopping at the first whitespace)

randGen.nextInt(20)

gives numbers in the range 0-19 (yields 20 possible numbers) randGen.nextInt(20) + 10 -gives numbers in the range 10-29

Package

group of related classes Note the import statement informs the compiler of the class' location -import packageName.ClassName; EX: import java.util.Scanner; imports the scanner class

What import statement must be used to generate random numbers?

import java.util.Random;

Integer numeric data types

int and double are the most common numeric data types. However, several other numeric types exist. EX: byte myVar; short myVar; int myVar; long myVar; long is used for integers expected to exceed about 2 billion.

type conversion

is a conversion of one data type to another, such as an int to a double.The compiler automatically performs several common conversions between int and double types, such automatic conversion known as implicit conversion. -For an arithmetic operator like + or *, if either operand is a double, the other is automatically converted to double, and then a floating-point operation is performed. -For assignments, the right side type is converted to the left side type if the conversion is possible without loss of precision. int-to-double conversion is straightforward: 25 becomes 25.0. double-to-int conversion may lose precision, so is not automatic.

seed

is a number or other value that is generated by software using one or more values.

Psuedo-random number generator

is any program, or function, which uses math to simulate randomness.

unary minus

minus - used as negative

variable

named item used to hold a value ie: x

overflow

occurs when the value being assigned to a variable is greater than the maximum value the variable can store. Overflow with floating-point results in infinity. Overflow with integer is discussed elsewhere.

outputting a variable's value

outputting a variable's value is achieved via: System.out.print(x) [Note: no quotes surround x. println( ) could also be used]

Using only the variable totalFlowers, complete the statement to assign remainingFlowers with the number of remaining flowers after creating as many bunches of 12 as possible.

remainingFlowers = totalFlowers%12 bc one bunch has 12 flowers so total%12 will give the number of remaining flowers after the max number of bunches were made

randGen.nextInt(6)

returns a number btwn 0-6

compile-time error

since a syntax error is detected by the compiler, a syntax error is known as a type of compile-time error -successfully compiling means the program doesnt have compile-time errors, but the program may have other kinds of errors

object

some internal data items plus operations that can be performed on that data -note an objects internal data are called private fields as the data is private to the object

common methods from the standard math class

sqrt(x) EX: sqrt(36)=6 pow(x, y) = x^y EX: pow(2, 3) =8 abs(x) EX: abs(-99)=99 full thing is Math.abs(x);

int wage

statement that creates an integer variable names wage

Reference variable

stores the memory address of an object -a reference is a variable type that refers to an object (thought of as storing the memory address of an object) -in statement: Histogram gradesHistogram = new Histogram( ); - the reference variable is "Histogram gradesHistogram"

string literal

text in double quotes " "

public methods

the operations that a program can directly invoke on objects of that class type. -operations that a program can directly invoke on objects of that class type [the class' public methods are often called the class interface] -methods for a class interface are listed after the public keyword in class definition -the internal data (and internal methods are listed after the private keyword

Outputting multiple items w/ one statement

use single output statement for each line of output by combining text, variable values, and a new line (do this by separating items w/ a + system) EX: System.out.println("Wage is: " + wage); Wage is: 20

random number in a range

using the import statement: -import java.util.Random Given a random number randNum, % can generate a random number within a range: randNum % 10Yields 0 - 9: Possible remainders are 0, 1, ..., 8, 9. Remainder 10 is not possible: Ex: 19 % 10 is 9, but 20 % 10 is 0. randNum % 51Yields 0 - 50: Note that % 50 would yield 0 - 49. (randNum % 9) + 1Yields 1 - 9: The % 9 yields 9 possible values 0 - 8, so the + 1 yields 1 - 9. (randNum % 11) + 20Yields 20 - 30: The % 11 yields 11 possible values 0 - 10, so the + 20 yields 20 - 30.

Given a 16-digit credit card number stored in x, which gets the last (rightmost) four digits? (Assume the fourth digit from the right is non-zero). x/10000 or x%10000

x % 10000 yields 0 - 9999, being the rightmost four digits. To get other digits like the next four digits, divide first to shift the desired digits to the rightmost digits, then use % to get just those digits.


Kaugnay na mga set ng pag-aaral

NU270 Week 4 PrepU: Clinical Decision Making / Clinical Judgment

View Set

C724: UNIT 6: Systems Development and Decision Making - UNIT TEST

View Set

Chapter exam premiums and proceeds

View Set