Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Similar presentations


Presentation on theme: "CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis."— Presentation transcript:

1 CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis 1

2 REVIEW MODIFIERS – Keyword static used in Method signature – Keyword static used in variable declaration – public, private, protected. Receiving Input Command Line Receiving Input via the Scanner – Keyboard. – Reading text file. Wrapper Classes. 2

3 Modifiers Modifiers are keywords that set visibility and or rights on members of a class. Some of the modifier keywords that we should be familiar from CS115 are: static public private – Some others that we will use in CS116 are: final abstract protected transient 3

4 The Keyword Static The keyword static can be applied to methods and also instance variables of a class. Applied to methods: Methods that have been declared static can be called by using the name of the class they belong to. Therefore we do not need to instantiate an object of that class in order to invoke its static methods. An example is the methods of the library class Math. If we look at the API all the methods of this class have the word static in their signature. That means that we can call method pow, as an example, by : double a= Math.pow(a, b); 4

5 Static applied to methods We have also seen static used in classes where there is a main method in addition to other methods. Rule: – If we want to invoke, from the main method, another method of the same class (that the main method belongs to) then that method has to be declared static. There is another way to call a non static method from the main (assuming that both are in the same class) by creating an object of the same class as the main and invoking the method by using the object. 5

6 Static applied to methods The previous rule applies to all methods which are static in a class and not just the main method! 6

7 Static applied to instance variables (attributes) of a class If an instance variable (field) is declared static then its value can be seen by all objects of the same class. i.e static int id=0; id++; the ++ after the identifier id means that the its value is incremented by one every time we execute the line of code id++ 7

8 Static Variables Thus if id=0; id++ causes a new value of id=1 calling id++ again causes a new value of id=2 And so on. If id is also declared static then every time we increment the value of id every object of the class sees the new value. 8

9 Static Variables Suppose that id is a static variable and that it belongs to class Student (template class). Suppose that in StudentClient we have instantiated the following objects: Student student1=new Student(); Student student2=new Student(); Student student3=new Student(); If the value of id=3 then all the student objects share the same value for id (that is 3). 9

10 Example of static variable public class Student { static int id=0; int currentID=0; String studentName=" "; public Student() { id++; currentID=id; studentName=“John Doe”; } public Student ( String sn) { Studentname=sn; } followed by accessor /mutator/toString() methods 10

11 Example of static variable We notice that in class Student – Every time the constructor is called the value of id is advanced by one with respect to its previous value. – Once the value of id is advanced its new value is assigned to a non static variable : currentID. – That is because the non static variables have values that are dedicated to each object and their values are not shared by all objects of the class. 11

12 Example of static variable public class StudentClient { public static void main(String [] args) { Student st1=new Student() // value of id=1 now for st1. Every time we call the constructor of the class Student id advances by 1 //Also,The value of id is passed to currentID =1 Student st2=new Student() // value of id=2 now for both st1 and st2, // currentID=1 for st1 but //currentID=2 for st2. Student st3=new Student() // value of id=3 for st1, st2, st3 // currentID=1 for st1 //currentID=2 for st2 //currentID=3 for st3 12

13 Example of static variable Therefore we could use the static variable id to track how many objects we have created for that class (i.e. the Student class). Notice that the new value of the static variable id is shared amongst all objects of the class. 13

14 Example of static variable The value of id is the same for each object student3 is created: 14 Student 1 id-=3 currentID=1 Student 2 Student 3 id-=3 currentID=2currentID=3 Since id is static all 3 objects see its new value when it changes (if a 4 th Student was to be created all 4 objects will have id=4). The variable currentID is not static therfore each object sees the value of currentID assigned for that object alone.

15 public and private Modifiers Keyword pubic can be applied to java elements: – Data fields (variables), methods, constructors an outer class, an inner class. – Rule: An element declared public is visible from another class. Keyword private can be applied to Java elements: – Data fields (variables), methods, constructors an inner class. Can not be applied to an outer class. – Rule: An element declared private is not visible from another class. Only to members of its own class. 15

16 RECEIVING INPUT Different ways to read input into our programs: – User provides input via Command Line when the java interpreter is called. – Read user provided input via the keyboard using the Scanner object during execution (interpretation) of the program (you should had learnt this in CS115). – Read a text file using the Scanner object (you should had learnt this in CS115). – We will learn later on in this course how to read different types of data files using streams (including writing new data into those files). 16

17 Command Line Input Command line implies that: – A DOS window is opened (cmd command from start menu or assecories->command prompt) – The command line path is pointingt o the path where the java program file (tehone with the main method) is located. 17

18 Command Line Input We can obtain input data for a program from the DOS window when we use the interpret command. This is called “command line “ input. i.e some path…………>java StudentClient arg1 arg2 arg3 Where arg1 arg2 arg3 are the 3 pieces of data (in this example) that will be read as individual Strings by the main method of the program. 18

19 Command Line Input This approach is only good as long as the class has a main method. The String array argument of the main method captures the values entered by the user. There is no pre determined number of data values that the user can enter from the command line. 19

20 Command Line Input Suppose that we have the class StudentClient and that it expects 3 inputs (called arguments) from command line: >java StudentClient arg1 arg 2 arg3 public class Student public static void main(String [] args) { String a=args[0]; String b=args[1]; String c=args[2]; 20

21 Command Line Input The Strings a, b, c now have the values that the user entered: i.e. >java StudentClient Joe, 20, 4.65 thus: a has the value Joe as a String b has the value 20 as a String c has the value 4.65 as a String 21

22 Command Line Input If we wanted to do arithmetic operations with the String versions of values 20 and 4.65 then we have to parse the String verions by using the appropriate wrapper class i.e int x= Integer.parseInt(b); results in the int version of the String 20 (int x=20) double y=Double.parseDouble( c ); results in the double version of the String 4.65 (double y=4.65) 22

23 Input Using the Scanner Class Sometimes we need to be able to capture input from the user while the program is running.. One way of providing input to the program is via the keyboard. A DOS window is required. Program should be interpreted from command line. The Scanner library class provides the functionality to allow us to capture keyboard input (and also read input from a file—we will cover the file reading later) Scanner class is part of the Library package java.util – Therefore we have to import the Scanner class 23

24 Receiving Input from the User Using the Scanner library class. Sometimes we need to prompt the user during the execution of the program so that input is provided after a specific set of instructions has been executed. The previous technique of making the input part of the command to start the execution WILL NOT work then. We can provide this functionality by using the Scanner library class. The user can be prompted to enter data, after the program starts execution, via the keyboard. The Scanner object will read the characters typed on the keyboard. 24

25 Input Using the Scanner Class Scanner class provides methods for reading byte, short, int, long, float, double, and String data types from the Java console (keyboard) and other sources (like a file). Scanner parses (separates) input into sequences of characters called tokens. By default, tokens are separated by standard white space characters (tab, space, newline, etc.) i.e in the String “My name is Joe” there are 4 tokens. The first token is the substring “My” and so on. 25

26 A Scanner Constructor Scanner( InputStream source ) creates a Scanner object for reading from source. If source is System.in, this instantiates a Scanner object for reading from the Java console (keyboard). (System.in is the keyboard) Example: Scanner scan = new Scanner( System.in ); scan then is the object that we are going to use to read characters from the keyboard if System.in has been passed to the constructor of the Scanner class. The Scanner class has methods that help us capture the user ‘s input (as an example from the keyboard or a file). 26

27 Scanner class methods Some of the methods are listed in the next slide. Connect to the link for the java API http://java.sun.com/javase/7/docs/api/ http://java.sun.com/javase/7/docs/api/ and study the methods of Scanner class. 27

28 Scanner next… Methods Return typeMethod name and argument list dataTypenextDataType( ) returns the next token in the input stream as a dataType. dataType can be byte, int, short, long, float, double, or boolean i.e nextDouble() or nextInt() Stringnext( ) returns the next token in the input stream as a String StringnextLine( ) returns the remainder of the line as a String 28

29 Prompting the User The next… methods do not prompt the user for an input value Use System.out.print to print the prompt, then call the next… method Example: 1. Scanner scan = new Scanner( System.in ); 2. System.out.print( "Enter your age > " ); 3. int age = scan.nextInt( ); In this example the user program stops execution after statement 2 is executed. The program waits for the user to type something (a number in this case) 29

30 Prompting the User On the DOS window we will see: C:\Users\George>java MyProgram Please enter your age > _ After the user enters a number (let us say that the user typed the number 19) and presses the Enter key, the program resumes execution and line 3 is executed. Line 3 reads what the user typed (19) as a String and at the same time converts it into an int data type. It assigns that data type (stores in memory) to the identifier age in this example. From there on the program continues with the execution of other instructions. It is possible that we may want to stop the program further down again and ask the user to enter another input. 30

31 Scanner Example Suppose that we want to read a String that a user of our program enters on the keyboard: import java.util.Scanner; class UsingScanner { public static void main(String[] args) { Scanner scan =new Scanner(System.in); System.out.println("Enter a decimal number"); String a=scan.next(); double d=Double.parseDouble(a); System.out.println(d); } 31

32 Scanner Example Interpreting this program has the following outcome: C:\CS115\Myexamples\ScannerExamples>java UsingScanner Enter a decimal number 12.34 The number you entered is:12.34 Notice that after the statement “Enter a decimal number” is displayed, the program waits for the user to enter something on the keyboard. Notice that the next action is for the user to type 12.34 on the keyboard. The program then prints the last statement “The number you entered is:12.34” 32

33 Scanner Example In the program the line: String a=scan.next(); captures whatever the user typed as a String data type (even if the user typed a number!) Our program converts the data type String represented by the identifier a to a double data type via the line: double d=Double.parseDouble(a); 33

34 Wrapper Classes We can always convert a String to a primitive data type using classes called “Wrapper classes”. In this example the class Double is the Wrapper class (notice that it is written with a capital D to differentiate it from the primitive data type double written with a lower case d). Its job is to convert a String to a double data type by invoking the method parseDouble that takes a primitive data type double as argument. 34

35 The Wrapper Classes “Wrap” the value of a primitive data type into an object Useful when methods require an object argument Also useful for converting Strings to an int or double 35

36 Wrapper Classes Primitive Data TypeWrapper Class doubleDouble floatFloat longLong intInteger shortShort byteByte charCharacter booleanBoolean 36

37 Back to Scanner We can capture the input from the keyboard directly as a numeric primitive data type instead of capturing it as a String first and then converting it (parsing it) to the particular numeric data type: i.e. Scanner scan =new Scanner(System.in); System.out.println("Enter a decimal number"); double a=scan.nextDouble(); 37

38 Using the nextDouble method with Scanner object import java.util.Scanner; class UsingScannerDouble { public static void main(String[] args) { Scanner scan =new Scanner(System.in); System.out.println("Enter a decimal number"); double d=scan.nextDouble(); System.out.println("The number you entered is:"+d); } Output: Enter a decimal numbner 13.456 The number you entered is:13.456 38

39 Text Reading Continue reviewing Chapter 7. 39


Download ppt "CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis."

Similar presentations


Ads by Google