Presentation is loading. Please wait.

Presentation is loading. Please wait.

Basic I/O - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 110/1/2015.

Similar presentations


Presentation on theme: "Basic I/O - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 110/1/2015."— Presentation transcript:

1 Basic I/O - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus Email: zhen.jiang@temple.edu 110/1/2015

2 Table of Contents Your first Java program Simple Output/Input Variable Data types Arithmetic (use of variables) String and its use in I/O statement Summary of programs Summary of concepts Other materials 210/1/2015

3 http://www.cis.temple.edu/~jiang/Welcome.java http://www.cis.temple.edu/~jiang/Welcome1.java Welcome – Your first program 310/1/2015

4 Environment JDK (Java Development Kit) IDE (Integrated Development Environment) Installment guide http://www.cis.temple.edu/~jiang/Installment1068.pdf Test run 410/1/2015

5 5 Before you run a program, you must compile it. compiler: Translates a computer program written in one language (i.e., Java) to another language (i.e., byte code)‏ Compile (javac)Execute (java) outputsource code ( Hello.java )‏ byte code ( Hello.class )‏ 10/1/2015

6 Details Names Main { } and ( ) Println and print (p93) ; 610/1/2015

7 Textbook Highlighted by content in ppt slides Indexed by page number in ppt slides Discussion Summary Exercises (in ppt slides and class), assignment, quiz, test, final

8 10/1/20158

9 Learning target www.cis.temple.edu/~jiang/ShowButtonDemo.pdf www.cis.temple.edu/~jiang/ButtonDemo.pdf www.cis.temple.edu/~jiang/WindowDestroyer.pdf Three key topics Loop, (instance) method, and text/string/array processing 10/1/20159

10 Hello.java,Hello.java Simple Output 10 syntax error: A problem in the structure of a program. 1public class Hello { 2 pooblic static void main(String[] args) { 3 System.owt.println("Hello, world!") 4 } 5} 2 errors found: File: Hello.java [line: 2] Error: Hello.java:2: expected File: Hello.java [line: 3] Error: Hello.java:3: ';' expected compiler output: 10/1/2015

11 11 Error messages do not always help us understand what is wrong: File: Hello.java [line: 2] Error: Hello.java:2: expected pooblic static void main(String[] args) { Why can’t the computer just say “You misspelled ‘public’”? 10/1/2015

12 12 First lesson Computers can’t read minds. Computers don’t make mistakes. If the computer is not doing what you want, it’s because YOU made a mistake. 10/1/2015

13 13 Java is case-sensitive Public and public are not the same 1 Public class Hello { 2 public static void main(String[] args) { 3 System.out.println("Hello, world!"); 4 } 5 } 1 error found: File: Hello.java [line: 1] Error: Hello.java:1: class, interface, or enum expected compiler output: 10/1/2015

14 14 System.out.println: A statement to print a line of output. pronounced “print-linn” The use of System.out.println (P93) : System.out.println(" "); Prints the given message as a line of text. System.out.println( ); Prints the given number as a line of text. 10/1/2015

15 15 System.out.println( + +… + ); Performs a output string concatenation and prints all as a line of text. System.out.println(); Prints a blank line. 10/1/2015

16 16 String: A sequence of text characters, also called message. Start and end with quotation mark characters Examples: "hello" "This is a string" "This, too, is a string. It can be very long!" 10/1/2015

17 17 A string may not span across multiple lines. "This is not a legal string." A string may not contain a “ character. The ‘ character is okay. "This is not a "legal" string either." "This is 'okay' though." This begs the question… 10/1/2015

18 18 A string can represent certain special characters by preceding them with a backslash \ (this is called an escape sequence, p89). \ttab character \nnewline character \" quotation mark character \\backslash character Example: System.out.println("Hello!\nHow are \"you\"?"); 10/1/2015

19 19 What is the output of each of the following println statements? System.out.println("\ta\tb\tc"); System.out.println("\\\\"); System.out.println("'"); System.out.println("\"\"\""); System.out.println("C:\nin\the downward spiral"); Write a println statement to produce the following line of output (space counted): / \ // \\ /// \\\ 10/1/2015

20 20 What a println statement will generate the following output (one statement only)? This program prints a quote from the Gettysburg Address. "Four score and seven years ago, our 'fore fathers' brought forth on this continent a new nation." What a println statement will generate the following output? A "quoted" String is 'much' better if you learn the rules of "escape sequences." Also, "" represents an empty String. Don't forget to use \" instead of " ! '' is not the same as " 10/1/2015

21 21 comment: A note written in the source code to make the code easier to understand (p104). Comments are not executed when your program runs. Most Java editors show your comments with a special color. Comment, general syntax: /* */ or, // Examples: /* A comment goes here. */ /* It can even span multiple lines. */ // This is a one-line comment. 10/1/2015

22 22 … at the top of each file (also called a "comment header"), naming the author and explaining what the program does. … at the start of every method, describing its behavior or function. … inside methods, to explain the complex pieces of code. 10/1/2015

23 23 Comments provide important documentation. Comments provide a simple description of what each class, method, etc. is doing. Later programs will span hundreds or thousands of lines, split into many classes and methods. When multiple programmers work together, comments help one programmer understand the other's code. 10/1/2015

24 Sample Program, P15 Sample Program http://www.cis.temple.edu/~jiang/1068FirstProgram.pdf Simple Input 2410/1/2015

25 A piece of your computer's memory that is given a name and type and can store a value. Usage compute an expression's result store that result into a variable use that variable later in the program Variable 2510/1/2015

26 26 To use a variable, it must be declared. Variable declaration syntax (P51): ; Convention: Variable identifiers follow the same rules as method names. Examples: int x; double myGPA; int varName; 10/1/2015

27 27 Declaring a variable sets aside a piece of memory in which you can store a value. int x; int y; Inside the computer: x: ?y: ? (You know! The memory has an uncertain value.)‏ 10/1/2015

28 28 identifier: A name given to an entity in a program such as a class or method. Identifiers allow us to refer to the entities. Examples (in bold): public class Hello public static void main double salary Conventions for naming in Java (which we will follow): classes: capitalize each word (ClassName)‏ everything else: capitalize each word after the first (myLastName)‏ 10/1/2015

29 Name, p103 Begin with [a]-[Z], _, or $ Contain only [a]-[Z], [0]-[9], _, and $ No keyword Case distinct “punctuate”, capital letter or ‘_’, page 104 2910/1/2015

30 30 Examples: legal:susansecond_place_myName TheCureANSWER_IS_42$variablemethod1 myMethodname2 illegal:me+u49erquestion? side-swipehi thereph.d jim's2%milksuzy@yahoo.com 10/1/2015

31 31 keyword: An identifier that you cannot use, because it already has a reserved meaning in the Java language. Complete list of Java keywords: abstract default if private this boolean do implements protected throw break double import public throws byte else instanceof return transient case extends int short try catch final interface static void char finally long strictfp volatile class float native super while const for new switch continue goto package synchronized NB: Because Java is case-sensitive, you could technically use Class or cLaSs as identifiers, but this is very confusing and thus strongly discouraged. 10/1/2015

32 32 Data types data type: A category of data values. Example: integer, real number, string Data types are divided into two classes: primitive types: Java's built-in simple data types for numbers, text characters, and logic. class types: type of objects, coming soon! 10/1/2015

33 33 Java has eight primitive types. Here are two examples: NameDescriptionExamples int integers 42, -3, 0, 926394 double real numbers 3.4, -2.53, 91.4e3 Numbers with a decimal point are treated as real numbers. Question: Isn’t every integer a real number? Why bother? 10/1/2015

34 Temperature Sum of a group of integers Average of a group of integers Number of seconds left in a game 3410/1/2015

35 Lesson two: Are you able to handle the data that is out of the original plan? What a kind (type) of data is in use? Should it be changed to new type? What is the new type? 3510/1/2015

36 36 Discrete Types byte short int long Continuous Types float double Non-numeric Types boolean char 10/1/2015

37 TypeRepresentatio n BitsBytes#Values boolean True or False 1N/A2 char ‘a’ or ‘7’ or ‘\n’1622 16 = 65,536 byte …,-2,-1,0,1,2,…812 8 = 256 short …,-2,-1,0,1,2,…1622 16 = 65,536 int …,-2,-1,0,1,2,…4> 4.29 million long …,-2,-1,0,1,2,…8> 18 quintillion float 0.0, 10.5, -100.732 double 0.0, 10.5, -100.764 10/1/201537

38 Arithmetic (Use of variables) 17/3=? http://www.cis.temple.edu/~jiang/Variable. pdf http://www.cis.temple.edu/~jiang/Variable. pdf 3810/1/2015

39 39 Assignment statement: A Java statement that stores a value into a variable. Variables must be declared before they can be assigned a value. Assignment statement syntax: = ; Examples: x = 2 * 4;x: 8myGPA: 3.25 myGPA = 3.25; 10/1/2015

40 40 A variable can be assigned a value more than once. Example: int x; x = 3; System.out.println(x); // 3 x = 4 + 7; System.out.println(x); // 11 10/1/2015

41 41 Once a variable is assigned a value, it can be used in any expression. int x; x = 2 * 4; y = x +3; System.out.println(x * 5 - 1); The above has output equivalent to: System.out.println(8 * 5 - 1); What happens when a variable is used on both sides of an assignment statement ? int x; x = 3; x = x + 2; // what happens? 10/1/2015

42 42 ERROR: Declaring two variables with the same name Example: int x; int x;// ERROR: x already exists ERROR: Reading a variable’s value before it has been assigned Example: int x; System.out.println(x); // ERROR: x has no value 10/1/2015

43 43 The assignment statement is not an algebraic equation! = ; means: "store the value of into ” Some people read x = 3 * 4; as "x gets the value of 3 * 4 " ERROR: 3 = 1 + 2; is an illegal statement, because 3 is not a variable. ERROR: a = 1 + * 2; is an illegal statement, because the expression is incomplete. 10/1/2015

44 44 A variable can only store a value of its own type. Example: int x; x = 2.5; // ERROR: x can only store int An int value can be stored in a double variable. Why? Type compatibility: The value is converted into the equivalent real number (p64). Example: double myGPA;myGPA: 2.0 myGPA = 2; 10/1/2015

45 char int byte long short double float boolean 10/1/201545

46 46 Manipulating data via expressions Expression: A data value or a set of operations that produces a value. Examples: 1 + 4 * 3 3 "CSE142" (1 + 2) % 3 * 4 10/1/2015

47 47 Arithmetic operators we will use: +addition - subtraction or negation *multiplication / division % modulus, a.k.a. remainder 10/1/2015

48 48 When Java executes a program and encounters an expression, the expression is evaluated (i.e., computed). Example: 3 * 4 evaluates to 12 System.out.println(3 * 4) prints 12 (after evaluating 3 * 4)‏ How could we print the text 3 * 4? 10/1/2015

49 49 When dividing integers, the result is also an integer: the quotient. Example: 17 / 3 evaluates to 5, not 5.666666 (truncate the decimal part)‏ Examples: 35 / 5 is 7 84 / 10 is 8 156 / 100 is 1 24 / 0 is illegal (what do you think happens?) 10/1/2015

50 50 The modulus computes the remainder from a division of integers. Example: 14 % 4 is 2 1425 % 27 is 21 3 52 4 ) 14 27 ) 1425 12 135 2 75 54 21 What are the results of the following expressions? 45 % 6 4 % 2 8 % 20 11 % 0 10/1/2015

51 51 What expression obtains (ChangeMaker.java, P77)ChangeMaker.java the last digit (unit’s place) of a number? Example: From 230857, obtain the 7. the last 4 digits of a Social Security Number? Example: From 658236489, obtain 6489. the second-to-last digit (ten’s place) of a number? Example: From 7342, obtain the 4. the part of a number rounded off to the nearest hundredth? Example: From 73.424, obtain the 73.42. From 73.425, obtain the 73.42. the part of a number rounded up to the nearest hundredth? Example: From 73.424, obtain the 73.42. From 73.425, obtain the 73.43. 10/1/2015

52 52 Precedence: Order in which operations are computed in an expression. Operators on the same level are evaluated from left to right. Example: 1 - 2 + 3 is 2 (not -4 )‏ Spacing does not affect order of evaluation. Example: 1+3 * 4-2 is 11 + - Addition, Subtraction * / % Multiplication, Division, Mod ()‏ Parentheses 10/1/2015

53 53 1 * 2 + 3 * 5 / 4 \_/ | 2 + 3 * 5 / 4 \_/ | 2 + 15 / 4 \___/ | 2 + 3 \________/ | 5 1 + 2 / 3 * 5 - 4 \_/ | 1 + 0 * 5 - 4 \___/ | 1 + 0 - 4 \______/ | 1 - 4 \_________/ | -3 10/1/2015

54 54 When an operator is used on an integer and a real number, the result is a real number (Type compatibility, p64). Examples: 4.2 * 3 is 12.6 1 / 2.0 is 0.5 Type cast (p65) Examples: (int)4.2 is 4 (double)17 is 17.0 7 / 3 * 1.2 + 3 / 2 \_/ | 2 * 1.2 + 3 / 2 \___/ | 2.4 + 3 / 2 \_/ | 2.4 + 1 \________/ | 3.4 Notice how 3 / 2 is still 1 above, not 1.5. 10/1/2015

55 55 String concatenation: Using the + operator between a string and another value to make a longer string. Examples: "hello" + 42 is "hello42" 1 + "abc" + 2 is "1abc2" "abc" + 1 + 2 is "abc12" 1 + 2 + "abc" is "3abc" "abc" + 9 * 3 is "abc27" (what happened here?)‏ "1" + 1 is "11" 4 - 1 + "abc" is "3abc" "abc" + 4 - 1 causes a compiler error. Why? 10/1/2015

56 56 Write a program to print out the following output. Use math expressions to calculate the last two numbers. Your grade on test 1 was 95.1 Your grade on test 2 was 71.9 Your grade on test 3 was 82.6 Your total points: 249.6 Your average: 83.2 10/1/2015

57 57 The computer internally represents real numbers in an imprecise way. Example: System.out.println(0.1 + 0.2); The output is 0.30000000000000004! 10/1/2015

58 int s are stored in 4 bytes (32 bits) In 32 bits, we can store at most 2 32 different numbers What happens if we take the largest of these, and add 1 to it? 10/1/201558

59 ERROR! This is known as overflow: trying to store something that does not fit into the bits reserved for a data type. http://en.wikipedia.org/wiki/Arithmetic_overflow Overflow errors are NOT automatically detected! It’s the programmer’s responsibility to prevent these. The actual result in this case is a negative number. 10/1/201559

60 int n = 2000000000; System.out.println(n * n); // output: -1651507200 10/1/201560

61 the result of n*n is 4,000,000,000,000,000,000 which needs 64-bits: ---------- high-order bytes ------- 00110111 10000010 11011010 11001110 ---------- low order bytes -------- 10011101 10010000 00000000 00000000 In the case of overflow, Java discards the high-order bytes, retaining only the low-order ones In this case, the low order bytes represent 1651507200, and since the right most bit is a 1 the sign value is negative. 10/1/201561

62 What happens if we create a double value of 1, and then keep dividing it by 10? Answer: eventually, it becomes 0. This is known as underflow: a condition where a calculated value is smaller than what can be represented using the number of bytes assigned to its type http://en.wikipedia.org/wiki/Arithmetic_underflow Again, Java does not detect this error; it’s up to the programmer to handle it. 10/1/201562

63 Legal assignment Left is a single variable Right is a legal expression Prefix and postfix increment/decrement, p79 Combined assignment, p73 Initialization & Declaration, p57 Constants (i.e., final), P60 6310/1/2015

64 64 ShorthandEquivalent longer version ++; = + 1; --; = - 1; Examples: int x = 2; x++;// x = x + 1; // x now stores 3 double gpa = 2.5; gpa++;// gpa = gpa + 1; // gpa now stores 3.5 10/1/2015

65 after executing int m = 4; int result = 3 * (++m) result has a value of 15 and m has a value of 5 after executing int m = 4; int result = 3 * (m++) result has a value of 12 and m has a value of 5 10/1/201565

66 66 Java has several combined operators that allow you to quickly modify a variable's value. ShorthandEquivalent longer version += ; = + ( ) ; -= ; = - ( ) ; *= ; = * ( ) ; /= ; = / ( ) ; %= ; = % ( ) ; Examples: x += 3 - 4;// x = x + (3 - 4); gpa -= 0.5;// gpa = gpa – (0.5); number *= 2;// number = number * (2); 10/1/2015

67 67 A variable can be declared and assigned an initial value in the same statement. Declaration/initialization statement syntax: = ; Examples: double myGPA = 3.95; int x = (11 % 3) + 12; 10/1/2015

68 68 It is legal to declare multiple variables on one line:,,..., ; Examples: int a, b, c; double x, y; It is also legal to declare/initialize several at once: =,..., = ; Examples: int a = 2, b = 3, c = -4; double grade = 3.5, delta = 0.1; NB: The variables must be of the same type. 10/1/2015

69 To avoid confusion, always name constants (and variables). area = PI * radius * radius; is clearer than area = 3.14159 * radius * radius; Place constants near the beginning of the program, CircleCalculation2.java, p108. http://www.cis.temple.edu/~jiang/CircleCalculation2.pdf 10/1/201569

70 Once the value of a constant is set (or changed by an editor), it can be used (or reflected) throughout the program. public static final double INTEREST_RATE = 6.65; If a literal (such as 6.65) is used instead, every occurrence must be changed, with the risk than another literal with the same value might be changed unintentionally. 10/1/201570

71 Syntax public static final Variable_Type = ; Examples public static final double PI = 3.14159; public static final String MOTTO = "The customer is always right."; By convention, uppercase letters are used for constants. 10/1/201571

72 Swap.java http://www.cis.temple.edu/~jiang/Swap.pdf Payroll.java http://www.cis.temple.edu/~jiang/Payroll.pdf 7210/1/2015

73 Math.PI, Math.pow, Math.sqrt, etc. (p412) 7310/1/2015

74 74 text processing: Two data types involved charString Represents individual charactersRepresents sequences of characters Primitive typeObject type (i.e., not primitive) Written with single quotesWritten with double quotes e.g.: ‘T’ ‘t’ ‘3’ ‘%’ ‘\n’ e.g.: “We the people” “1. Twas brillig, and the slithy toves\n” “” “T” String 10/1/2015

75 75 char : A primitive type representing single characters. P52. Individual characters inside a String are stored as char values. Literal char values are surrounded with apostrophe (single-quote) marks, such as 'a' or '4' or '\n' or '\'' Example, p67. char letter = 'S'; System.out.println(letter); // prints S System.out.println((int)letter); // prints 83, // explained on p932 10/1/2015

76 Most programming languages use the ASCII character set. Java uses the Unicode character set which includes the ASCII character set. The Unicode character set includes characters from many different alphabets (but you probably won't use them). 10/1/201576

77 String : an object type for representing sequences of characters Sequence can be of length 0, 1, or longer Each element of the sequence is a char We write strings surrounded in double-quotes We can declare, initialize, assign, and use String variables in expressions just like other data types String s = “Hello, world\n”;// declare, init System.out.println(s);// use value s = s + “I am your master\n”; // concatenate // and assign 10/1/201577

78 78 Unlike primitive types, String can have methods, P86. Here is a list of methods for strings: returns the index where the start of the given string appears in this string (-1 if not found)‏ indexOf( str )‏ returns a new string with all uppercase letters toUpperCase()‏ returns a new string with all lowercase letters toLowerCase()‏ returns the characters in this string from index1 up to, but not including, index2 substring( index1, index2 )‏ returns the number of characters in this string length()‏ returns the character at the given index charAt( index )‏ DescriptionMethod name 10/1/2015

79 Let s be a variable of type String General syntax for calling a String method: s. ( ) Some examples: String s = “Cola”; int len = s.length();// len == 4 char firstLetter = s.charAt(0); // ‘C’ int index = s.indexOf(“ol”); // index == 1 String sub = s.substring(1,3); // “ol” String up = s.toUpperCase(); // “COLA” String down = s.toLowerCase(); // “cola” 10/1/201579

80 Displaying message Input P116-118 converting a string to number, p123 Output P121-122 converting a number to string http://www.cis.temple.edu/~jiang/Payroll2.pdf 8010/1/2015

81 Welcome.java Hello.java Exercises (slide 17-18, 49, 54) FirstProgram.java Variable.java ChangeMaker.java CircleCalculation2.java Swap.java Payroll.java Payroll2.java (a similar program ChangeMakerWindow.java) Summary of programs in discussion 8110/1/2015

82 Running environment and execution of program (see lab work) Template of java program, i.e., file, class, and main (see in lab work) Program debug (memory tracking) println and print (P93), escape sequence (P89) Input via keyboard and plain text output (P96-97) I/O via JOptionPane (showInputDialog P116-8, showMessageDialog P121-2) Variable (P50-1), name (P55, P103), assignment (P55), declaration (P51), type (P52), initialization (P57) Constants (P60), type compatibility (P63-4) and type cast (P65-66) String, its conversion to number P123 and vice versa (concatenation P82) Arithmetic operators (e.g., %, P68), precedence order (P72) Imprecision (round-off error), and overflow (online materials) Prefix and postfix increment/decrement (P78,79), combined assignment (P73) Math class, P410-413 Summary of Concepts 8210/1/2015

83 Printf (p101) Delimiters for input (p99) Windows program (p125) http://www.cis.temple.edu/~jiang/ChangeMakerWind ow.pdf Other materials (FYI, not required for test) 8310/1/2015


Download ppt "Basic I/O - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 110/1/2015."

Similar presentations


Ads by Google