Applications in Java Towson University 2013. *Ref:

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

1 CSC 221: Computer Programming I Fall 2006 interacting objects modular design: dot races constants, static fields cascading if-else, logical operators.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
L3:CSC © Dr. Basheer M. Nasef Lecture #3 By Dr. Basheer M. Nasef.
Building Java Programs
1 COMP 110 Static Methods and Variables Tabitha Peck M.S. March 24, 2008 MWF 3-3:50 pm Philips 367.
Overloaded Constructors constructors can be overloaded, like other methods – i.e., a class can define several constructors all constructors must have the.
Enhancing classes Visibility modifiers and encapsulation revisited
Random (1) Random class contains a method to generate random numbers of integer and double type Note: before using Random class, you should add following.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
1 Chapter 5 Methods. 2 Introducing Methods A method is a collection of statements that are grouped together to perform an operation.
Static Class Members Wrapper Classes Autoboxing Unboxing.
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Conditionals II Lecture 11, Thu Feb
10-Aug-15 Classes and Objects in Java. 2 Classes and Objects A Java program consists of one or more classes A class is an abstract description of objects.
Introduction to Objects A way to create our own types.
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
1 CSC 221: Computer Programming I Spring 2010 interaction & design  modular design: roulette game  constants, static fields  % operator, string equals.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
CSC 204 Programming I Loop I The while statement.
CSC Java Programming, Fall, 2008 Week 2: Java Data Types, Control Constructs, and their C++ counterparts, September 4.
Mt. Rushmore, South Dakota CSE 114 – Computer Science I Static Methods andVariables.
1 Introducing Methods A method is a collection of statements that are grouped together to perform an operation.
Chapter 5: Methods 1. Objectives To declare methods, invoke methods, and pass arguments to a method (§ ). To use method overloading and know ambiguous.
GCOC – A.P. Computer Science A. College Board Topics – A.P. Computer Science A Program Design - Read and understand a problem's description, purpose,
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Session Three Review & Conditional Control Flow. Java File Hierarchy Projects Packages Classes Methods.
10-Nov-15 Java Object Oriented Programming What is it?
1.  At the end of this slide, student able to:  Object-Oriented Programming  Research on OOP features.  Do a code walkthrough to examine the implementation.
Georgia Institute of Technology More on Creating Classes part 2 Barb Ericson Georgia Institute of Technology Oct 2005.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
C# C1 CSC 298 Elements of C# code (part 1). C# C2 Style for identifiers  Identifier: class, method, property (defined shortly) or variable names  class,
Objects & Classes Weiss ch. 3. So far: –Point (see java.awt.Point) –String –Arrays of various kinds –IPAddress (see java.net.InetAddress) The Java API.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Constructors & Garbage Collection Ch. 9 – Head First Java.
1 CS 177 Week 11 Recitation Slides Class Design/Custom Classes.
Lesson 6 – Libraries & APIs Libraries & APIs. Objective: We will explore how to take advantage of the huge number of pre-made classes provided with Java.
More loops while and do-while. Recall the for loop in general for (initialization; boolean_expression; update) { }
Static. 2 Objectives Introduce static keyword –examine syntax –describe common uses.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Objects and Classes.
COMP 110 Static variables and methods Luv Kohli October 29, 2008 MWF 2-2:50 pm Sitterson 014.
Chapter 5 Defining Classes II Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Week 12 - Monday.  What did we talk about last time?  Defining classes  Class practice  Lab 11.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
Structured Programming Structured Programming is writing a program in terms of only 3 basic control structures: sequence selection repetition We have already.
1 Lecture # 2. * Introducing Programming with an Example * Identifiers, Variables, and Constants * Primitive Data Types * Byte, short, int, long, float,
CSC 212 – Data Structures Lecture 6: Static and non-static members.
Review – Primitive Data What is primitive data? What are 3 examples of primitive data types? How is a piece of primitive data different from an object?
Georgia Institute of Technology More on Creating Classes Barb Ericson Georgia Institute of Technology June 2006.
Lecture 9: Object and Classes Michael Hsu CSULA. 2 OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
Shlomo Hershkop Basics overview. Shlomo Hershkop Basic Review - Overview Practice coding Practice coding finger guessing game finger guessing.
CPSC 233 Tutorial 12 March 4/5 th, TopHat Quiz int[] a = {0}; int[] b = {1}; a = b; What is the value of a[0] i) 0 ii) 1.
Session Three Review & Conditional Control Flow. Java File Hierarchy Projects Packages Classes Methods.
Values vs. References Lecture 13.
Static and non-Static Chapter 5.
Introduction to Java Programming
Outline Boolean Expressions The if Statement Comparing Data
Chapter 5 Methods.
Simple Classes in Java CSCI 392 Classes – Part 1.
Variables, Types, Operations on Numbers
Applying OO Concepts Using Java
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
In this class, we will cover:
Presentation transcript:

Applications in Java Towson University *Ref:

The Guessing Game

3 Summary: –The game involves a ‘game’ object and three ‘player’ objects. –The game generates a random number between 0 and 9, and the three player objects try to guess it. Classes: GuessGame.class, Player.class, GameLauncher.class The Logic: –The GameLauncher class is where the application starts; it has the main() method. –In the main() method, a GuessGame object is created, and its startGame() method is called. –The GuessGame object’s startGame() method is where the entire game plays out. It creates three players, then “thinks” of a random number. –It then asks each player to guess, checks the results, and either prints out information about the winning player(s) or ask them to guess again. The Guessing Game

4 Classes GameLauncher main(String[] args) GuessGame p1 p2 p3 startGame() Player number guess() Make a GuessGame object and tells it to startGame Instance variables for the three players Method for making a guess The number this player guesses

5 public class GuessGame { Player p1; Player p2; Player p3; public void startGame() { p1 = new Player(); p2 = new Player(); p3 = new Player(); int guessp1 = 0; int guessp2 = 0; int guessp3 = 0; boolean p1isRight = false; boolean p2isRight = false; boolean p3isRight = false; int targetNumber = (int) (Math.random() * 10); System.out.println("I'm thinking of a number between 0 and 9..."); while (true) { System.out.println("Number to guess is " + targetNumber); p1.guess(); p2.guess(); p3.guess(); guessp1 = p1.number; System.out.println("Player one guessed " + guessp1); GuessGame class guessp2 = p2.number; System.out.println("Player two guessed " + guessp2); guessp3 = p3.number; System.out.println("Player three guessed " + guessp3); if (guessp1 == targetNumber) { p1isRight = true; } if (guessp2 == targetNumber) { p2isRight = true; } if (guessp3 == targetNumber) { p3isRight = true; } if (p1isRight || p2isRight || p3isRight) { System.out.println("We have a winner!"); System.out.println("Player one got it right? " + p1isRight); System.out.println("Player two got it right? " + p2isRight); System.out.println("Player three got it right? " + p3isRight); System.out.println("Game is over."); break; } else { System.out.println("Players will have to try again."); } // end of if/esle } // end of while loop } // end of StartGame() } // end of class GuessGame

6 public class Player { int number = 0; public void guess() { number = (int) (Math.random()*10); System.out.println("I'm guessing " + number); } // end of guess() } // end of class Player Player and GameLauncher public class GameLauncher { public static void main(String[] args) { GuessGame game = new GuessGame(); game.startGame(); } // end of main() } // end of class GameLauncher

Numbers and Statics

8 Math class Math class doesn’t have any instance variables. If you try to make an instance of class Math: Math mathObject = new Math();  You’ll get error! Methods in the Math class don’t use any instance variable values. (known as a kind of utility method) Because the methods are ‘static’, you don’t need to have an instance of Math. All you need is the Math class. int x = Math.round(42.2); int y = Math.min(56, 12); int z = Math.abs(-343);

9 Regular (non-static) vs. static methods The keyword static lets a method run without any instance of the class. A static method means “behavior not dependent on an instance variable, so no instance/object is required. Just the class.” Regular (non-static) method public class Song { String title; public Song(String t) { title = t; } // end of Song() public void play() { SongPlayer player = new SoundPlayer(); player.playSound(title); } // end of paly() } // end of class Song Static method public static int min(int a, int b) { // returns the lesser of a and b } // end of min() Song title play() Math min() max() abs() random() … Math.min(42,36); s1 = new Song(); s2 = new Song(); s1.play(); s2.play();

10 Calling a method Static mehtod  using a class name Math.min(88, 77); Math.max(88, 77); Math.round(88.77); Math.abs(-88); Math.random()*10; Non-static method  using a reference variable name Song s1 = new Song(); s1.play();

11 Using non-static variables from inside a static method The compile thinks, “I don’t know which object’s instance variable you’re talking about!” public class Duck { private int size; public static void main(String[] args) { System.out.println("Size of duck is " + size); } // end of main() public void setSize(int s) { size = s; } // end of setSize() public int getSize() { return size; } // end of getSize() } // end of class Duck 1 error found: Error: non-static variable size cannot be referenced from a static context

12 Using non-static methods from inside a static method The compile thinks, “I don’t know which object’s instance variable you’re talking about!” public class Duck { private int size; public static void main(String[] args) { System.out.println("Size of duck is " + getSize()); } // end of main() public void setSize(int s) { size = s; } // end of setSize() public int getSize() { return size; } // end of getSize() } // end of class Duck 1 error found: Error: non-static method getSize() cannot be referenced from a static context

13 Static variable Value is the same for All instances of the class class Duck2 { int duckCount; public Duck2() { duckCount++; } // end of Duck2() } // end of class Duck2 The constructor Duck2() always set duckCount to 1 each time a Duck2 was made after resetting to 0. public class Duck3 { private int size; private static int duckCount = 0; public Duck3() { duckCount++; } // end of Duck3() public void setSize(int s) { size = s; } public int getSize() { return size; } } // end of class Duck3 duckCount keep incrementing each time the Duck3() constructor runs, because duckCount is static and won’t be reset to 0.

14 Static variable vs. instance variable Duck size static duckCount getSize() setSize() Size : 20 duckCount : 4 Duck object Size : 8 duckCount : 4 Duck object Size : 12 duckCount : 4 Duck object Size : 22 duckCount : 4 Duck object A Duck object doesn’t keep its own copy of duckCount (static). Duck objects all share a single copy of it. Each Duck object has its own size variable, but only one copy of the duckCount in the class

15 static final variables: constants A variable marked final means that – once initialized – it can never change. The value of the static final variable will stay the same as long as the class is loaded. Math.PI public static final double PI= ; Naming convention:  Constant variable names should be in all caps! Any code can access it. No need for an instance of class Math PI doesn’t change

Wrapping a primitive

17 Wrapper class for every primitive type Wrapper class for every primitive type is in the java.lang package public class Num { public void doNums() { ArrayList listOfNumbers = new ArrayList (); listOfNumbers.add(3); int num = listOfNumbers.get(0); } // end of doNums() } // end of class Num Compiler does all the wrapping for you from number 3 (int) to Integer. Compiler automatically unwraps the Integer object to int so you can assign the int value directly to a primitive.