2)
public class Hi { //Hi has to match exactly the filename Hi.java (case sensitive)
public static void main(String[] args) { //This is the "main" function of the program. All my code goes inside it.
System.out.println("Hello, World!");
//TODO: Make some text-based graphics for this program
System.out.println("can you make \"java\" \\ C++ run other programs?");
System.out.println("//Yes!");
int myInteger; //defining (declaring) a variable.
//This lets Java know that we want a variable that holds integers,
//and is named myInteger.
int MyInteger; //variables are case sensitive, so this is
//a different variable than the one declared above.
myInteger = 72; //stores 72 in the myInteger variable.
myInteger = 36; //reassign the variable's value.
myInteger = myInteger + 6; //myInteger becomes 6 greater than what it is currently
int zero; //define a second variable.
zero = 1; //assign it zero.
System.out.println(myInteger / 3); //some basic arithmetic
int v = (int)(Math.random() * 10); //random number from 0 through 9.999..., truncated to an integer.
System.out.println(v); //print out the random number (now 0 through 9, since truncated).
}
}
//We've seen:
//======
//single line comments
//how to print stuff
//Strings (a sequence of characters; we can define one by surrounding text in quotes)
//Escape characters (how to get a quote or backslash in there)
//Variables
//Case sensitive names
//Every variable has a type.
//Think of them as boxes that have contents (that can change over time).
//The = means "gets" or "becomes".
//Java compiler is used to convert .java files to .class files (bytecode)
//3 types of errors are possible in Java:
//Syntax error: Not a legal Java program. ALWAYS caught by the compiler!
//Runtime error: Not caught by the compiler, but is caught during runtime.
//Semantic (logic) error: Not caught by the computer at all. Program just does the wrong thing,
//or otherwise behaves badly!
3)
//A basic Java application.
public class Hello {
public static void main(String[] args) {
System.out.println("Hello CS120 class!");
}
}
// Character escape sequences:
//
// \t Insert a tab in the text at this point.
// \b Insert a backspace in the text at this point.
// \n Insert a newline in the text at this point.
// \r Insert a carriage return in the text at this point.
// \f Insert a formfeed in the text at this point.
// \' Insert a single quote character in the text at this point.
// \" Insert a double quote character in the text at this point.
// \\ Insert a backslash character in the text at this point.
4)
public class VariableTest {
public static void main(String[] args) {
//Any variable declaration consists of the
//type followed by the variable name and a semicolon
int myVariable; //integer variable
double salary; //double variable (decimals allowed)
boolean havingGoodDay; //boolean means true or false.
salary = 100000.43; //changing the value of a variable.
System.out.println(salary); //printing the variable out to console
salary = salary * 1.05; //salary becomes whatever it was times 1.05 (a 5% raise)
System.out.println(salary); //printing the variable out to console (different value now)
//The 5 arithmetic operators in Java:
// * multiplication
// / division
// - substraction
// + addition
// % modulo (remainder after division)
myVariable = 33;
int d = 5;
System.out.println(myVariable / d); //integer division truncates the remainder
salary = 33;
System.out.println(salary / 5); //double (floating point) division gets what you'd expect.
havingGoodDay = true; //boolean variables can only take on the values true or false.
System.out.println(havingGoodDay);
//Naming conventions in Java:
//variable names always start with a lowercase first letter.
//If there are several words, we squish them all together
//and use a capital letter on each subsequent word.
//Javadocs are online documentation for Java features.
System.out.println(Math.sqrt(2.0)); //prints out square root of 2.
//order of operations:
//First: *, / and % from left to right.
//Then: + and - from left to right.
double firstRoot = (-2 + Math.sqrt(2*2 - 4*3*(-1))) / (2*3);
double secondRoot = (-2 - Math.sqrt(2*2 - 4*3*(-1))) / (2*3);
System.out.println("The first root is: "+firstRoot);
System.out.println("The second root is: "+secondRoot);
//Verify this is right (should be zero).
System.out.println(3*Math.pow(firstRoot, 2) + 2*firstRoot - 1);
System.out.println(3*Math.pow(secondRoot, 2) + 2*secondRoot - 1);
}
}
4b)
//Name: whole CS120 class.
//Approximate time to complete: 20 minutes.
//References used: Java API documentation.
//Java API documentation:
//The Math class:
public class UsingRandomness {
public static void main(String[] args) {
double a = Math.random();
System.out.println(a);
System.out.println(a);
if (a > .5) {
System.out.println("hello");
}
if (a <= .5) {
System.out.println("goodbye");
}
double b = Math.round(a*10);
System.out.println(b); //random number from 0 to 10 (not as much chance as getting 0 or 10 though).
System.out.println(b / 10); //random number from 0 to 1, in .1 increments.
//dice rolling.
//We will rolla "2d6" (in D&D notation) meaning rolling the six-sided die twice.
double dieRoll1 = Math.random() * 6;
dieRoll1 = Math.floor(dieRoll1) + 1;
System.out.println("Die roll is:" + dieRoll1);
double dieRoll2 = Math.random() * 6;
dieRoll2 = Math.floor(dieRoll2) + 1;
System.out.println("Die roll is:" + dieRoll2);
}
}
4c)
//Name: whole CS120 class
//Time to complete: 30 minutes
//Resources used: None
public class MyProgram {
public static void main(String[] args) {
double a;
double b;
double c;
//integer division truncates any fractions (gives you an int back!)
a = 4.0 / 7.0;
b = -3.0 / 2;
c = -120;
if (b*b - 4*a*c >= 0) {
//double is a type for decimal numbers (like 3.8, -9.999, etc.)
double root1;
//Math.sqrt() is a function. Put the input (called the argument) inside
//the parentheses.
//Order of operations *, /, +, - same as in algebra:
//* and / first from left to right.
//then + and - from left to right.
root1 = (-b + Math.sqrt(b*b - 4 * a * c)) / (2*a);
System.out.println(root1);
//"roundoff error" happens with decimals ("double" values).
System.out.println( a*root1*root1 + b*root1 + c); //we expect ths to be 0.
double root2;
root2 = (-b - Math.sqrt(b*b - 4 * a * c)) / (2*a);
System.out.println(root2);
System.out.println( a*root2*root2 + b*root2 + c); //we expect ths to be 0.
//The + operator either means "add" or "concatenate", depending on context.
//If one of the inputs is a "string", then it concatenates (puts together).
System.out.println("The first root is " + root1 + " and the second is " + root2);
}
if (b*b - 4*a*c < 0) {
System.out.println("There are no real roots");
}
}
}
6)
import java.util.*; //This tells Java that we will use classes
//from the java.util package (on your computer).
//Without this, I'll get an error when trying to make a Scanner object
//(Scanner resides in the java.util package).
public class InputExample {
public static void main(String[] args) {
//Types in Java:
//primitives (int, double, boolean)...there are only 8 primitives.
//classes (String, Scanner)...there are tons of classes (and we can make our own).
//Primitive values are just pieces of data (e.g. 1, false, -3.8).
//Class values are called "objects". They consist of data *and*
//operations that can be performed on that data (called "methods").
//Creates a Scanner object, stores it in the userInput variable.
Scanner userInput = new Scanner(System.in);
//String is a class as well. This is really what we are using
//when we put double quotes around a phrase. For example:
String u = "Say something!";
System.out.println(u);
//Let's get a String from the user.
//nextLine is a "method" available for Scanner objects.
//It's basically a that
//gets a String from the user.
String t = userInput.nextLine();
System.out.println("You said: "+t); //...and echo it back to them.
System.out.println("What's your favorite number?");
//let's get an int from the user.
int favoriteNumber;
favoriteNumber = userInput.nextInt();
System.out.println("Your fav # is "+favoriteNumber);
System.out.println("Say true or false.");
//get a true or false value from the user.
boolean f = userInput.nextBoolean();
//This is an "if statement". It lets us
//select what code to execute based on some
//conditions (in this case, whether f is true or false).
if (f) {
//If f is true,
//this code block will be executed
System.out.println("You said true");
}
else {
//If f is is not true (i.e. false),
//this code block will be executed
System.out.println("You said false");
}
}
}
6b)
import java.util.*; //let's us use the Scanner package
//The * means import every class in that package.
public class ObjectsExample {
public static void main(String[] args) {
//Data types: int, double, long.
//double
//roundoff error. (about 15 digits of accuracy)
//int
//integers only. less range. no roundoff error.
//long
//like an int, but has more precision.
//boolean
//true and false are the only possibilities.
//local variable pi - the caps one is a static variable.
double pi;
pi = Math.PI; //how you use a static variable: name of of the class, a dot, and the name of the variable.
System.out.println(pi);
//Step 0) import the package in which the class exists (see top of this program for import statement for Scanner).
//Step 1) Create a variable to store the object in.
Scanner myInput; //defines a variable called myInput, capable of holding a Scanner object
//Step 2) Create a new object and store it into the variable.
//This is called a constructor call (see javadocs)
//Step 3) Use it, by calling methods.
myInput = new Scanner(System.in);
String t; //defining a new variable
while(0 < 1) { // (0 < 1) is always true, so this loop goes forever.
System.out.println("What's your name?");
t = myInput.nextLine(); //calling a method to get a line of input from the user.
//get rid of leading and trailing space.
t = t.trim();
//capitalize the first letter, and lowercase the rest.
String firstLetter;
String theRest;
firstLetter = t.substring(0, 1);
theRest = t.substring(1);
firstLetter = firstLetter.toUpperCase();
theRest = theRest.toLowerCase();
System.out.println("Hi, " + firstLetter + theRest + ".");
//tell them how many letters are in their name.
int nameLength;
nameLength = t.length();
System.out.println("your name is " + nameLength + " characters long");
System.out.println("What's the radius of your circle?");
String radiusString = myInput.nextLine();
double r = Double.parseDouble(radiusString);
//Note that Double is a class, but double is a primitive.
//Here we are calling a *static* method on the class to convert to a *double*.
System.out.println("The circumference of your circle is " + 2 * Math.PI * r);
double rSquared = Math.pow(r, 2);
System.out.println("The area of your circle is " + Math.PI * rSquared);
System.out.println("In terms of PI, the circumference of your circle is " + 2*r + " * pi");
}
}
}
Good Class demos for using methods of static classes:
7)
import java.util.*;
public class IfStatementExample {
public static void main(String[] args) {
//System.in is the raw input stream from the console
//so that's always going to be the same
// (you could change it to a file though - we'll see
// how later in the semester)
Scanner in = new Scanner(System.in);
System.out.println("How old are you?");
int age = in.nextInt();
//Exactly one of these 4 main blocks will be executed.
if (age <= 3) {
System.out.println("Too young!");
//A nested if. If the age is at most 3, then
//exactly one of these 2 blocks will be executed.
if (age < 1) {
System.out.println("Hey Baby!");
}
else {
System.out.println("Hey toddler!");
}
}
else if (age < 10) {
System.out.println("You're ok");
}
else if (age < 18) {
System.out.println("grow up");
}
else {
System.out.println("get a job!");
}
//if statement without "else if" or even an "else".
if (age > 120) {
System.out.println("Way to old! You are probably lying.");
}
if (age < 10 & age >= 0) { //This & means "and"
System.out.println("You are a single digit person.");
}
//"or" means logical or. (one or the other or both)
if (age < 0 || age > 120) {
System.out.println("I find this unlikely.");
}
int salary;
if (age < 18) {
salary = 0;
}
else {
salary = 50000;
}
System.out.println("Your salary is " + salary);
// ! is the negation operator (the "not" operator)
if ( !(salary > 250) ) {
System.out.println("You aren't making much");
}
if (salary == 100000) {
System.out.println("You're rich");
}
}
}
8)
import java.util.*;
public class Example {
public static void main(String[] args) {
//Scanner is an example of a "class".
//primitive values (3.4, true, -5) - they're just a plain old value.
//class values (e.g. the thing that's inside my s variable below)
//are called objects.
Scanner s = new Scanner(System.in);
//we are calling an action on our scanner object (the action is
//called a "method" and this method just happens to be called nextInt).
int i = s.nextInt();
//3 is less than 7, so b gets the value: true.
boolean b = (3 < 7);
System.out.println(b); //prints true
if (3 < 7) {
int j = 5; //only has scope for this code block (the rest of
//the if statment)
System.out.println("yes, 3 < 7.");
}
//j = 2; //uncommenting this line would cause a compile time error.
//j does not have scope down here since it's declared inside the if
//statement block.
}
}
9)
import java.util.*;
//nextInt, nextDouble, and nextBoolean only take as many characters
//of input as necessary to satisfy your request (this may or may not
//contain newline characters). nextLine always returns the
//rest of the current line where the Scanner left off, and
//throws away the newline character.
//Therefore, if we're only interested in taking one piece
//of input per line, we just need to make a call like this:
// doctorWho.nextLine();
//...after every nextInt (the same thing
// applies for nextDouble and nextBoolean). This way we will
//never go wrong.
public class ScannerOddity {
public static void main(String[] args) {
Scanner doctorWho = new Scanner(System.in);
//You only ever want to create one Scanner
//for user input. If you create multiple ones,
//they will fight each other.
System.out.println("Your favorite number, please?");
int i = doctorWho.nextInt();
System.out.println("oh yeah, mine is " + (i+1) );
double d = doctorWho.nextDouble();
System.out.println(d);
System.out.println("... and the Doctor's name?");
doctorWho.nextLine(); //eat up the rest of the previous line!
String doctor = doctorWho.nextLine();
System.out.println("The doctor's name is: "+doctor);
}
}
9c)
import java.util.*;
//Attempt at a hangman program.
public class GuessTheWordGame {
public static void main(String[] args) {
//Create a scanner.
Scanner myInput;
myInput = new Scanner(System.in);
//Ask player one for the secret word.
System.out.println("What's your secret *secret* word?");
String secret;
secret = myInput.nextLine();
//Print out some space so player 2 doesn't see it.
int index = 0;
while(index < 40) {
System.out.println();
index = index + 1;
}
int guessesLeft; //number of guesses left
guessesLeft = 12;
//as long as we have guesses left.
while (guessesLeft > 0) {
//Ask player two to guess a letter or phrase
System.out.println("PLayer 2: guess a letter or phrase please.");
System.out.println(guessesLeft + " guesses left.");
String guess = myInput.nextLine();
//Say whether or not that letter (or phrase) was in the word.
boolean good;
good = secret.contains(guess);
if (good == true) {
System.out.println("Yes, it contains "+ guess +"!");
}
else {
System.out.println("No, it doesn't contains "+ guess +"!");
guessesLeft = guessesLeft - 1;
}
}
//Print game over
System.out.println("Game over");
}
}
9d)
import java.util.*;
public class WhileExample {
public static void main(String[] args) {
int count = 0; //shorthand for the two lines: int count; and count = 0;
//the while loop will repeat the code block after it
//as long as the boolean condition in the () is true.
while(count < 5) {
System.out.println("Damon is cool.");
System.out.println(count);
count = count + 1;
}
//for loop - it's sort of a shorcut way of doing a common kind of loop pattern. We will see more of these later.
for(int i = 0; i < 1000; i = i + 1) {
System.out.println(i);
}
//count up to 30000, print out a message and pause at every multiple of 10,000
int i = 0;
while(i <= 30000) {
System.out.println(i);
if (i % 10000 == 0) {
System.out.println("We got to a multiple of ten-thousand!");
//don't worry about exceptions - we haven't covered this part.
try {
Thread.sleep(1000); //1000 milliseconds = 1 second.
}catch(Exception e) {
}
}
i = i + 1;
}
//This loop won't do anything (because i is already bigger than 100).
while(i < 100) {
System.out.println("We got down here");
}
Scanner myInput = new Scanner(System.in); //creates the scanner
int age;
do {
System.out.println("What's your age?");
String s;
s = myInput.nextLine();
age = Integer.parseInt(s);
}while(age < 0);
if (age < 0) {
System.out.println("liar!"); //this should never end up getting executed, because of the do..while loop above.
}
else if (age < 5) {
System.out.println("how did you get this to compile??");
}
else if (age < 13) {
System.out.println("Go back to your homework.");
}
else if (age < 21) {
System.out.println("To young to drink.");
}
else {
System.out.println("Older gentleman / woman.");
}
}
}
10a)
public class Example2 {
public static void main(String[] args) {
//here is one way of truncating to two decimal places
double d = 33.2482;
int i = (int)(d*100);
System.out.println(i / 100.0);
//here is a way of formatting to two decimal places for output
d = 33.2482;
System.out.printf("%1.2f", d);
System.out.println(); //need this println, since printf doesn't
//produce a newline character
//Note that the first way truncated the extra digits
//and the second way rounded them.
}
}
10b)
public class InterestingStringThing {
public static void main(String[] args) {
int i = 5;
int j = 6;
//This next line has a logical error. Java
//will concatenate the string with i, and then
//the resulting string is concatenated with j,
//resulting in 56.
System.out.println("The sum is "+i+j);
//This way gets the right result. Using parenthesis
//forces the addition to occur first, and since
//both arguments (i.e. inputs) are int values,
//the result is an int value.
System.out.println("The sum is "+(i+j));
}
}
10c)
import java.util.*;
public class WhileExample {
public static void main(String[] args) {
int i = 10;
//count from 10 down to 0.
while(i >= 0) {
System.out.println(i);
i = i - 1;
}
Scanner in = new Scanner(System.in);
//keep asking the user for a nonnegative number until
//they get it right!