Lecture 6, CS 302-6, September 16
i. Clarification from last time – Math.pow(3,-2)
ii.
Quadratic
formula example – Quad.java
i.
pseudorandom
vs random
1. Humans are (maybe?) capable of random, computers cannot do random
ii. http://www.fourmilab.ch/hotbits/
1. This is based on radioactive decay, and is truly random
i.
import
java.util.Random;
ii. Initialize
1. Unseeded:
a. Random rand=new Random()
2. Seeded
a. Random rand=new Random(long)
b. The value for the long determines what rand generates
iii. rand.nextInt, rand.nextDouble, etc to get values
1. nextInt(); //anywhere in int range (-2,147,483,648 to 2,147,483,648)
2. .nextDouble(); //vallue between 0.0 and 1.0
iv.
20 sided Dice Example – D20.java
i. “a”
ii. “c”
iii. “1”
iv. “&”
v. “ “
i. name is variable, “Rob” is literal
1. ‘literal’ refers to the value stored in a variable
i. Use string.length() to get number of characters in a string.
1. String name=”Rob”;
2. System.out.println(name.length()); // 3
3. String hello=”Hello World!”;
4. System.out.println(hello.length()); // 11
i. String empty=“”; //Length=0
i. Like addition, but for Strings
1. int+String or String+int both create Strings
i. Scanner in=new Scanner();
ii. in.next(); gets one word
iii. in.nextLine(); – whole line (multiple words)
iv. So, if the input is “Hello World!”:
1. in.next()->”Hello”
2. in.nextLine()->”Hello World!”
i. int count=Integer.parseInt(string)
ii. double price=Double.parseDouble(string)
iii. This works only for strings like “123”, “123.12”, etc.
iv. If Java can’t translate the string, we get a run-time error
1. Integer.parseInt(“Hello World!”);
2. Integer.parseInt(“Two”);
i. These can be used to print characters that aren’t ‘easy to print’
1. \” //prints “
2. \\ //prints \
3. \n //prints new line
i. theString.charAt()
ii. The first character in a string is 0, second is 1, etc.
iii. String name=”Rob”
1. Character 0 is “R”
2. Character 1 is “o”
3. Character 2 is “b”
4. System.out.println(name.charAt(1)); //Prints “o”
i. theString=”STRING”
ii. theString.substring(1,4)=”TRI”
iii. theString.substring(0,1)=”S”
iv. theString.substring(4)=”NG”
1. if the second argument isn’t provided, the substring will go until the end of the string