CSC 116 - Test 2
printf
%d - integer %f - double %s - string %.Df - real number, rounded to D places after the decimal %W.Df- real number, W chars wide, rounded to D places after the decimal %-W.Df - real number, W wide(left-align, rounded to D after the decimal ex. System.out.printf("your GPA is %.1f\n", gpa); //your GPA is 3.2 //
String s = "apple"; s.charAt(0);
'a'
PrintStream tips
-DON'T declare a PrintStream object in a method that is called many times because the file gets reopened and its contents are wiped except for the last line -DON'T open the same file for both reading and writing at the same time
do while tips
-do not need to prime values prior to the loop because controlled statements are guaranteed to execute at least once -remember to keep tested variables in the scope, but declare them outside of the control structure
how to throw an exception
-exceptions are objects, so we must construct them ex. throw new if(n < 0) { throw new IllegalArgumentException("negative n"); } *in comments under return part, write @throws IllegalArgumentException if n < 0
File objects
-java programs can read files, process files, and write files -we must import java.io to create File objects -when we create a file object, it does not create a new file on the system, but there is the potential to create a file.
String s = "apple"; s.indexOf("p"); s.indexOf("k");
1 -1
while loops are executed 0 or many times, while do while loops are executed ...
1 or many times
String s = "apple"; s.length();
5
Creating a file object
File f = new File("data.txt");
What values would each of the following have?
Random rand = new Random(); rand.nextInt(20) + 50; //50-69 rand.nextInt(20 + 50); //0-69 rand.nextInt(10) * 4; //0,4,8,12,16,20,24,28,32,36
Scanner syntax
Scanner console = new Scanner(System.in);
Scanning through a file
Scanner input = new Scanner(new File("data.txt"));
Scanner Processing
Scanners are designed for file processing in a forward manner, there's no support for reading the input backwards.
program verification
a field of computer science that involves reasoning about the formal properties of programs to prove the correctness of a program
sentinel
a special value that signals the end of input
cumulative algorithms
an operation in which an overall value is computed incrementally, often using a loop
String s = "Apple"; s.toLowerCase(); s.toUpperCase();
apple APPLE
File Methods
canRead()- boolean- returns whether a file is able to be read delete() - boolean- deletes the given file exists()- boolean- returns whether or not the file exists on the system getAbsolutePath()- String- the full path to where the file is located getName()- String- the name of this file as a String, without any path attached isDirectory()- boolean- whether this file represents a directory on the system isFile()- boolean- whether this file represents a file on the system length()- long- the number of characters in the file mkdirs()- boolean - creates the directory represented by this file, if it does not exist renameToFile()- boolean- changes this file's nameto be the given files name
refactoring
changing a program's internal structure without modifying its external behavior to improve simplicity, readability, maintainability, etc
Character.isUpperCase()
checks to see if char is upper case, returns a boolean
Character.isDigit()
checks to see if the char is a digit, returns a boolean *['0','9'];
Character.isLetter()
checks to see if the char is a letter, returns a boolean
Character.isLowerCase()
checks to see if the char is lower case, returns a boolean
compile and execute source code
compile: javac -d bin src/ProjectName.java execute: java -cp bin ProjectName
Character.getNumericalValue()
converts a char that looks like a digit into a digit
Character.toLowerCase()
converts char to lower case char
Character.toUpperCase()
converts char to upper case char
chars and ints
each char is mapped to an integer value internally called an ASCII value 'A' = 65, 'B' = 66... 'a' = 97, 'b' = 98... mixing chars and ints causes an automatic conversion to int ex. 'a' + 10 =107 ex. 'A' + 'A' = 130 to convert an int into the equivalent char, type-cast it ex. (char) ('a' + 2) = 'c'
remember to close the Scanner
ex. input.close();
if(!boolean)
execute whatever's in the if statement if the boolean is false
if(insertBooleanHere)
execute whatever's in the if statement if the boolean is true
black box testing
ignores the internals of the program
Strings are ...
immutable -cannot change the state of an object -methods like substring() and toLowerCase() return a new string, they DO NOT modify the current String
Booleans are...
important for control structures
All scanner methods
in.nextInt(); in.nextDouble(); The following returns the user input as a string in.next(); in.nextLine();
unlike String, char...
is not an object, so you can't call methods on it like .toLowerCase(), etc.
short circuit evaluation
java stops evaluating the test if it knows the answer ex. || true or && false
while loop
loops that work to parse through situations that require indefinite loops - where we don't know how many times the loop will run ex. int x = 1; while (x < 20) { x+=10; } *must update the condition inside the loop, or else there will be an indefinite loop
De morgan's law
means that (!a || !b) is the same as !(a && b) and (!a && !b) is the same as !(a || b)
Object Equality
need to use the equals(Object) method to compare the equality of objects based on object content
de morgan's law example
original: if (x==7 && y>3) negated: if(x!=7 && y<=3)
Scanner look ahead
perform a test before you read a value -each next() method has a corresponding hasNext() method
String s = "apple"; s.substring(1); s.substring(0,3);
pple app
Character class
provides methods that can check information about a char Character.getNumericalValue('6'); //6 Character.isDigit('6'); //true Character.isLetter('a'); //true Character.isLowerCase('Q'); //false Character.isUpperCase('Q'); //true Character.toLowerCase('Q'); //'q' Character.toUpperCase('q'); //'Q'
Math.random()
returns a random number between [0.0,1.0) -can use multiplication to extend range
All String methods
s.charAt(index); s.substring(index); s.indexOf("a"); s.length(); s.toLowerCase(); s.toUpperCase();
directories needed
src, bin, test, project_docs, doc, test-files, lib
for loops can be rewritten as while loops, but the difference is..
the scope of the variable
Precedence
unary(sign and increment/decrement)- ++,-- multiplicative operators- *,/,% additive operators- +,- relational operators <,>,<=,>= equality operators ==,!= assignment operators =, +=, -=, /=, *=, %=
try catch
we can "catch" exceptions to handle them -if a method throws an exception, then any method that calls the original method must handle the exception with either a "throws clause" or a "try catch block" -try catch control structure allows the program to continue running even if the file doesn't exist ex. try{ Scanner input = new Scanner(new File("input.txt")); while(input.hasNextLine()){ System.out.println(input.nextLine()); } catch (FileNotFoundException e) { System.out.println("Error reading file: " + e); }
PrintStream
we can use PrintStream to write to our files -can write to many destinations -throws a FileNotFoundException ex. PrintStream output = new PrintStream(new File("hello.txt"));
fencepost problem
will have an extra thing concatenated at the end, switch around what's inside the loop vs outside
printing to the console with PrintStream
you can pass System.out to a method that has an input parameter of type PrintStream ex. PrintStream out1 = System.out; out1.println("hello, console");
Random Objects
you must construct it ex. Random r = new Random(); random int between -2^31 and 2^31 -1 : int x = r.nextInt(); random int between [0,(max - 1)] : int y = r.nextInt(10); //would produce a random number between 0 and 9 inclusive random real number between [0.0,1.0) double z = r.nextDouble(); random logical value of true or false: boolean b = r.nextBoolean(); ***EVERY TIME YOU CALL R.NEXTINT() YOU GET A NEW RANDOM NUMBER...so if you want to use a random number value in multiple places, you must store it in a variable