CHAPTER2

Uploaded from authorPOINTLite
Views:
 
Category: Education
     
 

Presentation Description

No description available.

Comments

Presentation Transcript

PRIMITIVE TYPES,STRINGS AND INTERACTIVE I/O: 

PRIMITIVE TYPES,STRINGS AND INTERACTIVE I/O Become familiar with the Java data types used for numbers, characters, and similar simple data. These types are called primitive types. Learn about the assignment statement and expressions. Find out about the Java data type used for Strings of characters and learn how to do simple string processing. Learn about simple keyboard input and screen output. Learn one way to do input and output using a windowing system. CHAPTER 2

Primitive Types and Expressions: 

Primitive Types and Expressions Variables in a program are used to store data such as numbers and letters. Variables have Variable Declaration In a Java program, a variable must be declared before it can be used. Variables are declared as follows: Syntax: Type Variable_1,Variable_2,…; Example: int styleNumber,x,y; char answer; double amount;

Slide3: 

There are two main kinds of types in Java, reference types and primitive types. The data types in java

Primitive types: 

byte 8 位 2 的补码 (byte) 0 short 16位 2 的补码 (short) 0 int 32 位 2 的补码 0 long 64位 2 的补码 0L float 32位 IEEE 754浮点数标准 0.0f double 64位 IEEE 754浮点数标准 0.0d char 16位 同一码字符集 ‘\u0000’ (Unicode character) boolean 1位 true or false false Primitive types 相当于化学中的无机物,是构成物理世界最基本的原子、分子!

Reference Types: 

Reference Types Is a pointer, is a memory address of an object or something. Point A=new Point(3,5); String str=new String(“hello”); Car mycar=new Car(3860); int[] array_a=new int[5]; Dog a_dog=new Dog(); Dog[] many_dogs=new Dog[10]; May be is null. 对象相当于化学中的有机物,是构成物理世界生物的复杂结构!引用则是指向对象的指针

Reference Types: 

Reference Types s1 s2 10001 s2=s1; a string 10001 class Mydate { int year; int month; int day; } Mydate today=new MyDate() 10008 today s1=new String(“a string”); Example: String s1;String s2;

Variable vs object: 

Variable vs object 25 a 3000 Int a=25; 2004 9 5 year month day Date dt=new Date(); 5000 dt 5000

Operators : 

Operators Arithmetic Operators: ++ -- + - * / % Relation Operators: > >= < <= == != Boolean Operators && || ! & | Bit Operators ~ & | ^ >> << >>> Assignment Operators = (op)= Conditional Operators ? : Assignment operators = (op)=

Expressions: 

Expressions An operation or a quantity stated in symbolic form, such as x* y2, or x + y Example: p73 Rate*rate+delta 2*(salary+bonus) 1/(time+3*mass) (a-7)/(t+9*v) -b/(2*a)+Math.sqrt(delta)/(2*a) -b/(2*a)-Math.sqrt(delta)/(2*a) X>y a<=b choice!=‘y’ (a==3)&&(b==4) !stop||(x>=10) byteshortintlongfloatdouble Scientific (e) notation: 8.65*108 8.65e8, 4.83*10-4 4.83e-4

Type Casting: 

Type Casting In many situations, you are not allowed to store a value of one type in a variable of another type. In these situations, you must use a type cast that converts the value to an “equivalent” value of the target type. Syntax: (Type_Name) Expression Example: double guess; guess=7.8; int answer; answer=(int) guess; The value stored in answer will be 7. Note that the value is truncated, not rounded.

Precedence Rules: 

Precedence Rules First: the unary operators: + - ++ -- ! Second: the binary arithmetic operators: * / % Third: the binary arithmetic: + - Fourth: the relation operators: < > <= >= Fifth: the relation operators: == != Sixth: the bit operator: & Seventh: the bit operator: | Eighth: the boolean operator && Ninth: the boolearn operator ||

Statements: 

Statements An elementary instruction in a source language. Expression+”;” If-else statement Switch-case-default statement Do-while statement For statement While statement Etc.

The Class String: 

The Class String String str1=new String(“Time and tide wait for no man”); String str2; str2=“Tomorrow comes never”; String str3=“Doubt is the key of knowledge”; Words,words,mere words, no matter from the heart. William Shakespeare, Troilus and Cressida You can concatenate two strings by connecting them with the ‘+’ sign. String a=“Nothing is difficult to the man who will try.” String b=“Great hopes make great man.” String c=a+b; c=?

Methods in the class String: 

Methods in the class String length() equals(Other_string) trim() charAt(position) substring(start) substring(start,end) indexOf(A_string) indexOf(A_string,start) to LowerCase() toUpperCase() compareTo(A_string)

StringBuffer class: 

The contain of this object can be change. StringBuffer a=new StringBuffer(“Rome was not built in a day.”); Methods: length() append() insert() delete() replace() StringBuffer class Help of javadoc

Slide16: 

Wrapper Classes Every primitive type has a wrapper class. Wrapper classes allow you to have something like a primitive type that is of a class type. Wrapper classes also contain a number of useful predefined constants and static methods.

Methods for Converting String to Numbers and inverse p114: 

Methods for Converting String to Numbers and inverse p114 Convert data type 封装类的名称

Escape Characters: 

Escape Characters \ (backslash) is escape characters Because it escape from the usual meaning of a character. \” Double quote \’ Single quote \\ Backslash \n New line \r Carriage return \t Tab To use Special characters

The parameters of main(): 

The parameters of main() Public class demo { public static void main(String[] args) { System.out.println(“args[0]=“+args[0]); System.out.println(“args[1]=“+args[1]); } } C:\myjava> javac demo.java C:\myjava> java demo good morning Args[1] Args[0] Parameters of Command’s line

2.3 Keyboard and Screen I/O: 

2.3 Keyboard and Screen I/O Output:You can output one line with System.out.println(). The items output can be quoted strings, variables, constants such as numbers, or almost any object you can define in Java. Syntax: System.out.println(output_1+output_2+…+); Example: System.out.println(“Hello world!”); Println versus print Input:System.in.read() read a ascii from keyboard. Basic I/O

Slide21: 

You use methods in the class SavitchIn to read values from the keyboard. When you invoke one of these methods, you use the class name SavitchIn as if it were the calling object. In other words, a typical method invocation has the form: Variable=SavitchIn.Method_Name(); *readint() Syntax: int_variable=SavitchIn.readLineInt(); Long_variable=SavitchIn.readLineLong(); Float_variable=SavitchIn.readLineFloat(); Double_variable=SavitchIn.readLineDouble(); Char_variable=SavitchIn.readLineNonWhiteChar(); String_variable=SavitchIn.readLine(); SavitchIn class in our book

2.4 Document and Style: 

2.4 Document and Style Using Meaningful Names for Variables Documentation and Comments // /* */ /**@ */ Indenting Named Constants public static final double PI=3.14159; Other stipulation String Color | drawString() sqrt() The First Character should be capiliation The second word should be started with capiliation

Slide23: 

You can use the methods showInputDialog and showMessageDialog to produce input and output windows for your java programs. When using these methods, you must include the following at the start of the file that contains your program: import javax.swing.*; Input: String_variable=JOptionPane.showInputDialog(String_Expression); Output: JOptionPane.showMessageDialog(null,String_Expression); 2.5 Windowing I/O with JOptionPane

Slide24: 

Don’t forget System.exit(0); When you write a program with a windowing interface, you always need to end the program with it, or the program will be running in tiring-room. You can insert the new line character ‘\n’ into the string used as Multi-Line output. Example1 example2 example 3 P116 Close the GUI program

Case Study--Vending Machine change: 

Algorithm to determine the number of coins in amount cents: 1.Read the amount into the variable amount. originalAmount=amount; 2.Set the variable quarters equal to the maximum number of quarters in amount. 3.Reset amount to the change left after giving out that many quarters. 4.Set the variable dimes equal to the maximum number of dimes in a mount. 5.Reset amount to the change left after giving out that many dimes. 6.Set the variable nickel equal to the maximum number of nickels in amount. 7.Reset amount to the change left after giving out that many nickels. Pennies=amount; 8.Output originalAmount and the numbers of each coin. P76 Display 2.5 P116 Display 2.15 Case Study--Vending Machine change 1 quarter= ¼ coin 2角5分硬币 1 dime=1/10 coin 1角硬币 1 nickel=1/20 coin 5分硬币 1 pennie 1 分硬币 Algorithm to determine the number of coins in amount cents: 1.Read the amount into the variable amount. originalAmount=amount; 2.Set the variable quarters equal to the maximum number of quarters in amount. 3.Reset amount to the change left after giving out that many quarters. 4.Set the variable dimes equal to the maximum number of dimes in a mount. 5.Reset amount to the change left after giving out that many dimes. 6.Set the variable nickel equal to the maximum number of nickels in amount. 7.Reset amount to the change left after giving out that many nickels. Pennies=amount; 8.Output originalAmount and the numbers of each coin. P76 Display 2.5 P116 Display 2.15

Chapter Summary: 

Chapter Summary A variable can be used to hold values, like numbers. The type of the variable must match the type of the value stored in the variable. Variables (and all other items in a program) should be given names that indicate how the variable is used. All variables should be initialized before the program uses their value. Parentheses in arithmetic expressions indicate the order in which the operations are performed. Your program should output a prompt line when the user is expected to enter data from the keyboard.

Slide27: 

You can have variables and constants of type String. You can use the plus sign to concatenate two strings. There are methods in the class String that can be used for string processing. You should define names for number constants in a program and use these names rather than writing out the nubmers within your program. Programs should be self-documenting to the extent possible. However, you should also insert comments to explain some points. Chapter Summary

Self-Test Questions: 

Self-Test Questions Give a Java assignment statement that will increase the value of the variable count by 3. The variable is of type int. What is the output produced by the following? char symbol; symbol=‘2’; System.out.println((int)symbol); What is the output produced by the following lines of program code? double result; result=(1/2)*2; System.out.println(“(1/2)*2 equals “+result); What is the output produced by the following? System.out.println(“abc\ndef”);

Slide29: 

5.Is the class SavitchIn part of the Java language. 6.What are the two kinds of comments in Java? 7.Give a java statement that will display a window on the screen with message I love you. 8.Give a Java statement that, when executed, will end the program. 9. Write a complete Java Program that will read in two values of type double and output the product of the two numbers. Use the class JOptionPane to do input and output using windows. 10. Suppose you use System.in.read() to input int,double variable etc. Does it work as your thought? Self-Test Questions