2) - web viewpublic class variabletest {public static void main(string[] args) {//any variable...
Post on 12-Feb-2018
214 Views
Preview:
TRANSCRIPT
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 programSystem.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 variabledouble 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 remaindersalary = 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: http://download.oracle.com/javase/1.5.0/docs/api///The Math class: http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Math.html
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 executedSystem.out.println("You said true");
}else {
//If f is is not true (i.e. false),//this code block will be executedSystem.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:
http://cs.nmu.edu/~mkowalcz/cs120f10/notes/08/section%203/
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 leftguessesLeft = 12;//as long as we have guesses left.while (guessesLeft > 0) {
//Ask player two to guess a letter or phraseSystem.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 overSystem.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,000int 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 placesdouble 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 outputd = 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!int j = -1;while(j < 0) {
System.out.println("Enter a nonnegative number");j = in.nextInt();
}System.out.println("You said: "+j);
//adding up 0 through 100int sum = 0;int counter = 0;while(counter <= 100) {
sum = sum + counter;counter = counter + 1;
}System.out.println("The sum of 0 + 1 + ... + 100 = " + sum + ", yeah!");
//an infinite loop (you usually don't want that!)boolean b = true;while(b) {
System.out.println("hi");}
// Be careful of = versus ==// = is used for assignment (means left side becomes the right side)// == is used for testing equality.
}}
public class Modulo {public static void main(String[] args) {
int k = 3;int j = 0;
System.out.println(j % k); //remainder after dividing 7 by 3.//should be 1.
//The code block of this if statement always executes.if (true) {
j = 7;j = j + 1;
}
j = j / 2;
}}
11a)public class Javadocs {
public static void main(String[] args) {//Notes on using the Javadocs:
//When you see a method with "static" at the left, this//means you call it with the name of the class, a period, and//then the name of the method. For example:
//The javadoc says "static double random()", so you call it using:double r = Math.random();
//"static methods" are also sometimes called "functions".//They simply take input and produce output.
//This shows a combination of getting a static double from the Math class,//and using it in a static method (the cosine function).//The javadoc says "static double cos(double a)"double c = Math.cos(Math.PI);
//If there isn't a "static" labeling a method, that means the method is used on
//objects of that class. Objects are instances of a class.//For example, "hello" is an instance of the String class type.//The analogy is that 3.4 is an instance of the double primitive type.
//To use these methods, you use the name of the object// (or the variable containing it, more precisely),// a period, and then the name of the method.
//In either case (static or not), you have to supply whatever//inputs ("arguments") are required in between the parenthesis.
//using "static int max(int a, int b) " from the Math class.
System.out.println(Math.max(4,5));}
}
11b)import java.util.*;
public class StringsAndThings {public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
System.out.println("hello?");String t = myScan.nextLine();
if (t.equals("hello")) {System.out.println("hi");
}else {
System.out.println("eh?");}
//The == operator compares primitives to see//if they are the same value.
//But when it comes to objects, it compares//to see if they are the EXACT same object in memory.//Thus we have to use the equals method instead.
System.out.println("What state are you in (two letter abbreviation)?");String state = myScan.nextLine();
double tax;if (state.equals("MI")) {
tax = 6;
}else if (state.equals("WI")) {
tax = 5.5;}else if (state.equals("FL")) {
tax = 7 * Math.random(); //random tax between 0 and 7.}else {
System.out.println("I don't know that place called "+state);tax = 0;
}
System.out.println("The tax is "+tax+"%");
String a = "hello";String b = "zebra";
if (a.compareTo(b) < 0) {System.out.println(a +" comes before " + b);
}else if (a.compareTo(b) > 0) {
System.out.println(a +" comes after " + b);}else {
System.out.println(a +" must be equal to " + b);}
}}
12a)// The "Integer class" is different than the primitive int type.// Here I used the Integer class to convert a String to an int.
// http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Integer.html
public class Conversion {public static void main(String[] args) {
//how to convert a String into an int.
String t = "3872";int i = Integer.parseInt(t);System.out.println(i);
i = Integer.parseInt("999");System.out.println(i);
}
}
12b)import java.util.*;
//A program where the user guesses the computer's secret number.public class Guess {
public static void main(String[] args) {//create a scannerScanner userInput = new Scanner(System.in);
//Generate and store a random number (1 - 100)int secret = (int)(Math.random() * 100) + 1;//the (int) is called a "cast" and it forces the//double value into an int value (truncating fractions)
int guess = -1; //user's guess//Loop as long as the guess is wrong:while(guess != secret) {
//prompt the user to make a guessSystem.out.println("Take a guess.");
//get the guessguess = userInput.nextInt();
//Compare to see if they got it right:if (secret == guess) {
//If they got it right, say so.System.out.println("You got it right.");
}else if (guess < secret) {
//If guess is too low, say so.System.out.println("You guessed too low.");
}else {
//If guess is too high, say so.System.out.println("You guessed too high.");
}}
//Tell user: Congrat's you're great.System.out.println("You won!");
}
}
16)import java.util.*;
public class ChutesAndLadders {public static void main(String[] args) {
Scanner userIn = new Scanner(System.in); //creates a Scanner object
System.out.println("Are you ages 4 and up?");String answer = userIn.nextLine();
if (answer.equals("no")) {System.out.println("You aren't old enough to play");System.exit(0); //Exits the program immediately.
}
int player1; //current position of player 1int player2; //current position of player 2player1 = 0; //start just before the first square (off the board)player2 = 0; //start just before the first square (off the board)
while(player1 < 100 && player2 < 100 ) { //keep looping as long as the game is in progress.
System.out.println("Player 1's turn. Hit <enter> to roll.");userIn.nextLine();int dieRoll = (int)(Math.random() * 6) + 1;if (player1 + dieRoll <= 100) {
player1 = player1 + dieRoll;
}System.out.println("You rolled a "+dieRoll
+" and landed on square "+player1);
//chutes and ladders part.if (player1 == 1) {
player1 = 38;System.out.println("Ladder to "+player1);
}else if (player1 == 4) {
player1 = 14;System.out.println("Ladder to "+player1);
}else if (player1 == 16) {
player1 = 6;System.out.println("Chute to "+player1);
}//TODO: missing a lot more chutes and ladders
if (player1 < 100) { //if player 1 hasn't won yet, p2 gets a turn.System.out.println("Player 2's turn. Hit <enter> to roll.");
userIn.nextLine();dieRoll = (int)(Math.random() * 6) + 1;if (player2 + dieRoll <= 100) {
player2 = player2 + dieRoll;}System.out.println("You rolled a "+dieRoll
+" and landed on square "+player2);
//chutes and ladders inif (player2 == 1) {
player2 = 38;System.out.println("Ladder to "+player2);
}else if (player2 == 4) {
player2 = 14;System.out.println("Ladder to "+player2);
}else if (player2 == 16) {
player2 = 6;System.out.println("Chute to "+player2);
}//TODO: missing a lot more chutes and ladders
}}
if (player1 == 100) {System.out.println("Player 1 wins");
}else if (player2 == 100) {
System.out.println("Player 2 wins");}
}
}
top related