Chapter2. Watch out:Here comes Java [3/27 revised]

Download Report

Transcript Chapter2. Watch out:Here comes Java [3/27 revised]

Great Ideas of CS with Java








Part 1 WWW & Computer programming in the language Java
Ch 1: The World Wide Web
Ch 2: Watch out: Here comes Java
Ch 3: Numerical computation & Function
Ch 4: Subroutines & Databases
Ch 5: Graphics
Ch 6: Simulation
Ch 7: Software engineering







Part 2 Understanding what a computer is and how it works
Ch 8: Machine architecture
Ch 9: Language translation
Ch 10: Virtual Environment for Computing
Ch 11: Security, Privavcy, and Wishful thinking
Ch 12: Computer Communication






Part 3 Advanced topics
Ch 13: Program Execution Time
Ch 14: Parallel Computation
Ch 15: Noncomputability
Ch 16: Artificial intelligence
1
SNU
IDB Lab.
Ch2. Watch Out: Here Comes Java
Copyright © SNU IDB Lab.
SNU
IDB Lab.
Table of Contents








Put some Action into Web Pages
Object Oriented Programming
Java Language Fundamental
Using Decisions to Solve Problems
Coding Decision Trees
Using Primitive Data Types
String and String Manipulation
More on Syntax
3
SNU
IDB Lab.
Simple Web Page with some Action
<html>
<head> <title>The Nobel Prizes</title> </head>
<body> <h1>Alfred Nobel’s Legacy</h1>
<p>Alfred Nobel, a nineteenth-century industrialist,
died in 1896 and left … </p>
<p> If you would like to read more ….</p>
<APPLET code = “StoryAdvice.class”> </APPLET>
</body>
</html>

HTML code can call a computer program (applet) that can be designed to
execute almost any process we can imagine
4
SNU
IDB Lab.
Two Ways of Using Java

Stand Alone (like most traditional programs)


Code: sampleprogram.java
Compile: javac sampleprogram.java



Java compiler generates sampleprogram.class
Execute: java sampleprogram
Inside Web as an Applet


Code: sampleprogram.java
Compile: javac sampleprogram.java


Java compiler generates sampleprogram.class
Embed into HTML code

<APPLET code = “sampleprogram.class”> </APPLET>
5
SNU
IDB Lab.
Table of Contents








Put some Action into Web Pages
Object Oriented Programming
Java Language Fundamental
Using Decisions to Solve Problems
Coding Decision Trees
Using Primitive Data Types
String and String Manipulation
More on Syntax
6
SNU
IDB Lab.
High-Level Programming Paradigms

Control-oriented Programming (before mid 80’s)




Real world problem  a set of functions
Data and functions are separately treated
Pascal, C
Object-oriented Programming (after mid 80’s)



Real world problem  a set of classes
Data and functions are encapsulated inside classes
C++, Java
7
SNU
IDB Lab.
Java vs. C
#include <stdio.h>
int power = 0; // 전원상태 0(off), 1(on)
int channel = 1; // 채널
int caption = 0; // 캡션상태 0(off), 1(on)
main()
{
power();
channel = 10;
channelUp();
printf("%d\n", channel);
displayCaption("Hello, World");
// 현재 캡션 기능이 꺼져 있어 글짜 안보임
}
caption = 1; // 캡션 기능을 켠다.
displayCaption("Hello, World"); // 보임
power()
{
if( power )
{ power = 0; }
else { power = 1; }
}
// 전원 off  on
// 전원 on  off
channelUp()
{ ++channel; }
channelDown()
{ --channel; }
displayCaption(char *text)
{
// 캡션 상태가 on 일 때만 text를 보여준다.
if( caption ) {
printf( "%s \n", text);
}
}
8
SNU
IDB Lab.
JAVA vs. C
CaptionTVTest class
TV class
class Tv {
boolean power = false; // 전원상태(on/off)
int channel;
// 채널
class CaptionTvTest {
public static void main(String args[]) {
void power()
{power = !power; }
void channelUp()
{++channel; }
void channelDown() {--channel;}
}
CaptionTv ctv = new CaptionTv();
ctv.power();
ctv.channel = 10;
ctv.channelUp();
CaptionTV class
System.out.println(ctv.channel);
class CaptionTv extends Tv {
boolean caption; // 캡션상태(on/off)
ctv.displayCaption("Hello, World");
// 캡션 기능이 꺼져 있어 보여지지 않는다.
void displayCaption(String text)
{
if (caption) {
// 캡션 상태가 on(true)일 때만 text를 보임
}
}
}
ctv.caption = true; // 캡션기능을 켠다.
ctv.displayCaption("Hello,World");
// 캡션을 화면에 보여 준다.
}
System.out.println(text);
}
9
SNU
IDB Lab.
Control Oriented Programming Paradigm


In traditional control-oriented programming, program describes what the
machine will do sequentially, grouping commonly used parts into “functions”.
Fortran, Pascal, C, and many more old programming languages
Start
statement
function myFunction(arg…)
** statements…
** invoke other functions…
invoke functions…
statements…
10
SNU
IDB Lab.
Sample C program
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int i, j, k, l;
for(i=0; i < argc; i++) {
func-abc();
func-def();
fprintf();
}
}
func-abc ( ) {
func-def ( )
……. }
{ ….. funct-xyx()
}
func-xyz ( ) { ………}
11
SNU
IDB Lab.
참고자료
C 언어 기초
SNU
IDB Lab.
참고slide
C 프로그래밍 언어

Dennis Richie




UNIX 운영 체제를 설계하면서 개발
프로그래머에게 편리한 도구로 설계
시스템 프로그래밍 언어로 사용
장점




실행 속도가 빠르다
이식성이 좋다
프로그램을 논리적인 작업 단위로 작성하고 이를 계층적으로 배치
고급언어의 특성과 저급 수준 언어의 특성을 동시에 가지고 있다
13
SNU
IDB Lab.
참고slide
프로그래밍 기초(C 언어)

C 언어에서의 함수 (function in C)


단위 작업을 수행하기 위한 명령문의 집합
예






사용자로부터 입력을 받는다.
입력에서 오류가 없는지 확인한다.
계산한다.
결과를 출력한다.
위의 명령문들을 따로 묶어 분리하고 거기에 이름을 붙인 것
기능 : 입력을 받아 계산을 하고 그 결과를 넘겨준다.
14
SNU
IDB Lab.
참고slide
프로그래밍 기초(C 언어)

C 프로그램

여러 함수의 모임
int sum(int a, int b) {…..}
double avg(int a, int b) {…..}
void main() { …..}
15
SNU
IDB Lab.
참고slide
프로그래밍 기초 (C 언어)

main()



C 프로그램 내에서 반드시 정의되어야 하는 특별한 함수
프로그램이 실행될 때 가장 먼저 실행되는 함수
main() 함수 내에서 다른 함수를 호출하는 식으로 프로그램이 실행된다.
#include <stdio.h>
main() {
printf(“Hello World”);
}
printf() 함수는 직접 작성할 필요없음
호출하여 사용하기만 하면 됨 (Library)
16
SNU
IDB Lab.
참고slide
사칙 연산을 수행하는 C 프로그램
#include <stdio.h>
main()
{
int add, sub, mul, div;
add = 4 + 2;
sub = 4 - 2;
mul = 4 * 2;
div = 4 / 2;
printf (“%d %d %d %d”, add, sub, mul, div);
}
<%d의 의미>
- %d는 형식 코드로서 이 위치에 변수 값을 출력한다.
- 출력하는 변수의 값은 정수임을 의미이다.
- 참고 ) 실수를 출력하기 위한 형식 코드는 %f
17
SNU
IDB Lab.
참고slide
변수 (Variable)

변수


값을 저장하기 위한 장소 (예 add-var = 4 + 2;)
변수 선언 (variable declaration)



변수를 사용하기 전에는 반드시 선언해야 한다.
선언할 때 변수가 저장하는 자료형(data type)을 밝혀야 한다.
int add-var;
 이 경우 add-var 라는 변수는 정수만을 저장할 수 있다.

자료형 (data type)

int, float, char,…...
18
SNU
IDB Lab.
참고slide
변수 예제
#include <stdio.h>
main()
{
int j;
float f;
char c;
j = 1;
f = 0.3;
c = ‘a’;
printf (“%d %f %c \n”, j, f, c);
}
줄바꿈 기호
19
SNU
IDB Lab.
참고slide
배열 (Array)

정수를 저장하는 변수를 100개 선언하려면??



int iarray[100];


필요한 변수 100개를 모두 선언한다.
배열 (Array)를 선언한다.
정수형 변수를 100개 선언한 것과 동일한 효과
float farray[100];

실수형 변수를 100개 선언한 것과 동일한 효과
20
SNU
IDB Lab.
참고slide
연산자 (operators)

주요 연산자




+, -, *, / : 4칙 연산자
% : 나머지를 구하는 연산자
++ : 변수의 값을 1 증가하는 연산자
-- : 변수의 값을 1 감소하는 연산자
21
SNU
IDB Lab.
참고slide
연산자 예제
#include <stdio.h>
main()
{
int a, b;
a = 5;
b = a % 3;
a++;
printf (“%d %d \n”, a, b);
}
22
출력되는 값은?
SNU
IDB Lab.
참고slide
흐름 제어 (Control Flow)

프로그램의 실행 순서를 제어하는 명령문

조건문



여러 선택 가능한 실행 순서 중에서 조건에 부합하는 문장을
선택하여 실행한다.
if문, if-else 문, switch문,….
반복문


조건이 참(true)인 동안 일단의 문장을 반복 실행한다.
for문, while문, ….
23
SNU
IDB Lab.
참고slide
조건문 (Conditional Statement)
#include <stdio.h>
- 조건식이 기술된다.
main()
- 조건식은 관계 연산자나 논
{
리 연산자로 구성된다.
int a;
a = 1;
if (a = = 1)
printf(“a = 1”);
else if (a = = 2) printf(“a = 2”);
a ++;
if (a = = 1)
printf(“a = 1”);
else if (a = = 2) printf(“a = 2”);
}
24
SNU
IDB Lab.
참고slide
조건문

관계 연산자


<, >, <=, >=, ==, !=
if (a != b) printf(“not equal”);


a와 b의 값이 같지 않다면 not equal을 출력한다.
논리 연산자



! (not), &&(and), ||(or)
if ( (a >=b) && (a >=c) ) printf(“a is Max”);
a가 b보다 크고 그리고 a 가 c보다 크면 a is Max가 출력된다.
25
SNU
IDB Lab.
참고slide
반복문 (Repeating Statement)
3. 실제 반복
되는 문장
for (j = 1; j <= 100; j++) sum = sum + j;
1. 초기값
4. 단계
2. 반복할 조건
- 조건이 만족되는
한 계속 반복된다.
26
SNU
IDB Lab.
참고slide
반복문 예제

1에서 100까지 더하는 문제
#include <stdio.h>
main()
{
int j, sum;
sum = 0;
for (j = 1; j <=100; j++)
sum = sum + j;
printf (“sum = %d”, sum);
}
27
SNU
IDB Lab.
참고slide
반복문 예제

1에서 100까지 더하는 문제
#include <stdio.h>
main()
{
int j, sum;
sum = 0;
j = 1;
while (j <= 100) {
sum = sum + j;
j++;
}
printf (“sum = %d”, sum);
}
28
SNU
IDB Lab.
참고slide
C 프로그램 예제
함수
void swap(int pts[], int i, int j )
{
인자
int tmp;
tmp = pts[i];
pts[i] = pts[j];
pts[j] = tmp;
#include <stdio.h>
인자
void main()
함수
함수 }
{
int i;
void sorting(int pts[], int n)
int points[5] = { 84, 82, 90, 89, 93};
{
for ( int i = 0; i < n; ++i ) {
for ( i = 0; i < 5; ++i )
for ( int j = i; j < n; ++j ) {
printf(“%d “, points[i]);
if( pts[i] > pts[j] )
swap(pts, i, j);
printf(“\n”);
}
sorting(points, 5);
}
for ( i = 0; i < 5; ++i )
}
printf(“%d “, points[i]);
}
29
SNU
IDB Lab.
Control-Oriented Programming:
Function-based structure
Main()
Function-A()
Function-X()
Function-E()
Function-B()
Function-C()
Function-F()
Function-T()
30
SNU
IDB Lab.
Problems of Control-Oriented Programming

Difficult to understand

Hundreds and thousands of functions and calls

Difficult to debug
Difficult to build a large program
Difficult to maintain the existing program

Solution (mid 80’s) Object-Oriented Programming


31
SNU
IDB Lab.
Object-Oriented Programming Paradigm(1)


Everything is an Object
Every object has its Class (Type)


Object has data part and function part




Class has instance variables and methods
Class has data members and function members
Computation is communication among Objects
There are many similar objects



홍길동 is an instance of “SNU-STUDENT” class
Inheritance is useful
Ex: Car, 2Door-Car, SUV, MiniVan, Truck…..
OO Programming is


Defining Classes
Defining Inheritance among Classes
32
SNU
IDB Lab.
Object-Oriented Programming Paradigm(2)


In object-oriented programming, program describes what
properties a class have, defines what the class will do.
C++, Java, and many more contemporary PLs
Class myClass
** properties…
** definition of methods…
** use other classes…
33
SNU
IDB Lab.
OO Programming paradigm (3)
Conceptual Understanding of Object-oriented Programming
An Instance of Bike Class
Bike Class
34
SNU
IDB Lab.
OOP Example (1)

Programming “Organ”  Building a class “Organ”
Public class Organ
{Data Keys, Stops, Other;
Public void PlayNote(P x)
{ … Java Code for PlayNote…};
Public void SetStop(P x)
{ … Java Code for SetStop…};
etc….
}
35
SNU
IDB Lab.
OOP Example (2)

Public class Lawn-Mower
{Data Location, Running, FuelLevel, OilLevel, ThrottleSetting;
Public void StartEngine()
{ … Java Code…};
Public void StopEngine()
{ … Java Code…};
Public void SetSpeed()
{ … Java Code…};
Public void GoForward()
{ … Java Code…};
Public void GoBackward()
{ … Java Code…};
Public void TurnLeft()
{ … Java Code…};
Public void TurnRight()
{ … Java Code…};
etc….
}
36
SNU
IDB Lab.
참고자료
Basic Concepts of OOP
SNU
IDB Lab.
참고slide
Object
An encapsulated software structure which usually
models an application domain entity
Object
=
Data + Operations
2000
deposit
code
withdraw
code
Bank Account object
SNU OOPSLA Lab.
38
SNU
IDB Lab.
참고slide
Related Terms
Instance variables
The variables(data) contained in an object are called
instance variables.
Method
An operations of an object is called method.
Message
A request to invoke an operation is called message.
SNU OOPSLA Lab.
39
SNU
IDB Lab.
참고slide
Example: File Object
open
close
read
write
file-1
Object-oriented view
file-1 open()
: Hey file-1, please open yourself.
file-1 read(ch) : Hey file-1, please give me the next char.
file-1 close()
SNU OOPSLA Lab.
: Hey file-1, close yourself.
40
SNU
IDB Lab.
참고slide
Class
An abstract data type which define the representation
and behavior of objects.
class
instantiations
instances
object
SNU OOPSLA Lab.
object
41
SNU
IDB Lab.
참고slide
Example: Rectangle
Define a Rectangle Class.
x
(0,0)
Class Rectangle
data
int x, y, h, w;
method
create(int x1, y1, h1, w1)
{ x=x1; y=y1; h=h1; w=w1; }
moveTo(int x1, y1)
{ x=x1; y=y1; self.display(); }
display()
{ drawRectangle(x, y, h, w); }
End Class
(x,y)
y
h
SNU OOPSLA Lab.
w
42
SNU
IDB Lab.
참고slide
Interface of Rectangle
class Rectangle {
operations
create(int x1, y1, h1, w1);
moveTo(int x1, y1);
display();
}
SNU OOPSLA Lab.
43
SNU
IDB Lab.
참고slide
Example: Using Rectangle
5
x
5
(5,5)
10
5
r1
r1
(10,15)
y
(25,10)
5
5
r2
#Import Rectangle
Rectangle r1, r2;
r1.create(5, 5, 10, 5);
r1.display();
r1.moveTo(25,10);
SNU OOPSLA Lab.
r2.create(10, 15, 5, 5);
r2.display();
44
SNU
IDB Lab.
참고slide
Inheritance
A mechanism which allows a new class to be
incrementally defined from an existing class.
Problem
What is a Zebra ?
“A Zebra is like a horse but has stripes”
Horse
inherit + stripes
Zebra
Inheritance avoid repetition and confusion!
SNU OOPSLA Lab.
45
SNU
IDB Lab.
참고slide
Example: Inheritance
Problem
Define a new class called Window, which
is a rectangle, but also resizable.
Rectangle
add “resize” method
Window
Class Window
inherit Rectangle
add operation
resize(int h1, w1)
{ h=h1; w=w1; display(); }
SNU OOPSLA Lab.
46
SNU
IDB Lab.
참고slide
Class Hierarchy
Rectangle
Window
ScrolledWindow
MenuWindow
Inheritance builds class hierarchies which
are reusable and opens the possibility of
application frameworks for domain reuse.
SNU OOPSLA Lab.
47
SNU
IDB Lab.
Table of Contents



Put some Action into Web Pages
Object Oriented Programming
Java Language Fundamental








Java Basic
"Hello World"
Another Applet: Use of Buttons
Using Decisions to Solve Problems
Coding Decision Trees
Using Primitive Data Types
String and String Manipulation
More on Syntax
48
SNU
IDB Lab.
Java Language




Simple and compact
Smaller than C/C++
Secured Programming in networked environments
However, for Practical Program





Use many predefined Classes
For effective use: experience
Will have to memorize very little of detail
Understand and Know how to use
The most prevalent, popular and dominant programming
language in the world!
49
SNU
IDB Lab.
Java Basic: Assignment Statement

variable = expression;



Note only one equal sign (=)
Note semicolon (;)
Ex) X = 3;
X = funcSample(3);
X = Y – Z;
50
SNU
IDB Lab.
Java Basic: Logical Expression

Expression with comparison operators




<, >, <=, >=
==, !=
Outcome true or false
Ex: if ( x > 3)
then
if ( x == 2) then
y=1
z=2
51
SNU
IDB Lab.
Java Basic: If-else Statements

If Statements
if (logical expression)
{
}

"true" actions
If - Else Statements
if (logical expression)
{
}
else
{
}
"true" actions
"false" actions
52
SNU
IDB Lab.
Java Basic: Using Braces {} (1/3)


Statements in {} is considered as one syntactical element.
For example: in “if – else” Statements,
if (logical expression)
{
"true" actions
}
else
{
"false" actions
}
53
SNU
IDB Lab.
Java Basic: Using Braces {} (2/3)

{} delimits visibility of a variable
{
int a;
{
int b;
b = a; // OK
}
a = b; // compile error. cannot see “b” here.
}
54
SNU
IDB Lab.
Java Basic: Using Braces {} (3/3)
55
SNU
IDB Lab.
Java Basic: defining class
Public class Organ /* class declaration */
{Data
Keys, Stops, Other; /* data declaration */
/* method declaration */
Public void PlayNote(P x);
{ … Java Code…}
Public void SetStop(P x);
{ … Java Code …}
etc….
}
-----------------------------suppose we have the above----------------Organ KimOrgan;
KimOrgan.playnote(“애국가”);
56
SNU
IDB Lab.
Java Construct: Method Invocation




Method is often called function or procedure
Invoking a method is also called "calling a function”
Naming a method causes a corresponding function to be carried out.
Parentheses are required for arguments
57
SNU
IDB Lab.
Java Program, Compile, and Run
** Compile:
javac helloworldapp.java ( generate helloworldapp.class)
** Program Run:
java helloworldapp
58
SNU
IDB Lab.
"Hello World" Applet Demo (1)
We want to see “Hello, World!” in the web browser: HelloWorld.java

// Program to write messages to an applet
import java.awt.*;
public class HelloWorld extends java.applet.Applet
{
TextField m1,m2;
public void init () {
m1 = new TextField(60);
m2 = new TextField(60);
m1.setText(" H e l l o W o r l d !");
m2.setText("This is a simple Java test.");
}
add(m1);
add(m2);
}
59
SNU
IDB Lab.
Java Facts in HelloWorld


import java.awt.*
 자바에서 제공해주고 있는 GUI 기초를 다루고 있는 패키지이다.
GUI 컴포넌트들(Button,Text Box, Text Field, 체크 박스 등)의 library
import java.applet.Applet




웹페이지에서 애플릿을 이용하려면 선언해야하는 문장.
init(): applet으로 사용되는 Java class에서의 시작 함수
new: 어떤 class에 속한 instance를 처음 생성할때 사용
add(): 화면에 적절히 배치하는 기능
60
SNU
IDB Lab.
Class TextField in java.awt.*

java (root: Object)  java.awt 
java.awt.Component
 java.awt.TextComponent
 java.awt.TextField
(저자가 임의로 만든 class)
A TextField object is a text component for the editing of a single line
of text.
Methods in TextField class




public String getText()


Returns the text that is presented by this text object
public void setText(String t)
 Sets the text in the text object with the string value in t
61
SNU
IDB Lab.
Subclasses and the Java Class Hierarchy
Every class in Java has a superclass except the highest class of all, object
The Class hierarchy is a very large tree extending down from object.
Checkbox
Choice
TextArea
TextComponent
TextField
List
Component
Button
Canvas
Object
Container
Label
Scrollbar
ABC
PQR
XYZ
62
SNU
IDB Lab.
"Hello World" Applet Demo (2)
HelloWorld.htm
<HTML>
<HEAD> <TITLE> The textfield demo program. </TITLE> </HEAD>
<BODY>
This tests the textfield capability.
<APPLET code="HelloWorld.class" WIDTH=750 HEIGHT=325> </APPLET>
</BODY>
</HTML>
63
SNU
IDB Lab.
Another Java Applet: Use of Buttons (1/4)

Interactive program




Dynamic user interaction
User clicks buttons and types numbers and charaters
Clicking on buttons can cause things to happen
Button Use Demo




TrafficLight.java
TrafficLight.html
Show Green, Red, Yello button on the screen
If the user clicks any button, trigger the action method by showing
the corresponding message (“stop”, “go”, “ready to stop”)
64
SNU
IDB Lab.
Another Java Applet: Use of Buttons (2/4)
import java.awt.*;
import java.awt.event.*;
public void actionPerformed(ActionEvent event)
{
Object cause = event.getSource();
public class TrafficLight extends java.applet.Applet
implements ActionListener
{
TextField m1, m2;
Button
b1, b2, b3;
public void init ()
{
m1 = new TextField(80);
m1.setText("What are you going to do when the light is:");
b1 = new Button("GREEN");
b2 = new Button("YELLOW");
b3 = new Button("RED");
m2 = new TextField(80);
add(m1) ;
add(b1) ;
add(b2) ;
add(b3) ;
add(m2) ;
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
}
}
}
if (cause == b1)
{
m2.setText("Keep on rolling.");
}
if (cause == b2)
{
m2.setText("Step on it! You can make it!");
}
if (cause == b3)
{
m2.setText("I suppose you'll have to stop.");
}
TrafficLight.java
65
SNU
IDB Lab.


















public class TrafficLight extends java.applet.Applet
implements ActionListener
{
TextField m1, m2;
Button
b1, b2, b3;
public void init ()
{
m1 = new TextField(80);
m1.setText("What are you going to do when the light is:");
b1 = new Button("GREEN");
b2 = new Button("YELLOW");
b3 = new Button("RED");
m2 = new TextField(80);
add(m1) ;
add(b1) ;
add(b2) ;
add(b3) ;
add(m2) ;
66
SNU
IDB Lab.
Another Java Applet: Use of Buttons (3/4)
Java Facts

import java.awt.* 와 import java.awt.event.* 의 차이



Java.awt.* 는 awt의 하위 클래스들만 다루게 된다. 즉 하위 클래스의 아래에
있는 클래스를 사용할 수는 없다.
Java.awt.*를 선언하면 event를 사용할 수는 있지만 event 하위 클래스를
사용할 수는 없다. 따라서 java.awt.event.*를 선언해야만 event 하위
클래스들을 사용할 수 있게 된다.
b1.addActionListener(this)


이 의미는 b1이라는 button 컴포넌트에 어떤 동작을 추가시키는 의미이다. b1버튼에
어떤 동작을 취하겠다라는 것을 선언해 준 것이다.
실제 동작은 다음 함수가 수행한다.
Public void actionPerformed(ActionEvent event) { …… }
 When an action is performed, actionPerformed method is invoked internally.
 ActionEvent event contains the cause and description of the action
 We can get the cause of the action from event.getSource()
67
SNU
IDB Lab.
Another Java Applet: Use of Buttons (4/4)
TrafficLight.htm
<HTML>
<HEAD> <TITLE> A button demo program. </TITLE> </HEAD>
<BODY>
This tests button action capability.
<APPLET code="TrafficLight.class" WIDTH=700 HEIGHT=325> </APPLET>
</BODY>
</HTML>
68
SNU
IDB Lab.
Another Interactive Java Program (1/3)
“Duplicate Three Times”

After receiving a string from a user, show the
same message three times in the screen.
69
SNU
IDB Lab.
Another Interactive Java Program (2/3)
“Duplicate Three Times”
DupThree.java
// Program to illustrate use of setText
import java.awt.*;
import java.awt.event.*;
public class DupThree extends java.applet.Applet
implements ActionListener
{
TextField m1, m2, m3, m4, m5;
Button b1;
String message;
}
public void init ()
{
m1 = new TextField(80);
m2 = new TextField(80);
m3 = new TextField(80);
m4 = new TextField(80);
m5 = new TextField(80);
b1 = new Button("button");
m1.setText("Please enter some text below, then press button");
70
}
add(m1);
add(m2);
add(b1);
add(m3);
add(m4);
add(m5);
b1.addActionListener(this);
public void actionPerformed(ActionEvent event)
{
message = m2.getText();
m3.setText(message);
m4.setText(message);
m5.setText(message);
}
SNU
IDB Lab.
Another Interactive Java Program (3/3)
“Duplicate Three Times”
DupThree.html
<HTML>
<HEAD> <TITLE> Applet Response Demo Program.</TITLE> </HEAD>
<BODY>
This demonstrates the TextField capabilities
<APPLET code="DupThree.class" WIDTH=700 HEIGHT=300> </APPLET>
</BODY>
</HTML>
71
SNU
IDB Lab.
Table of Contents








Put some action into web pages
Object Oriented Programming
Java Language Fundamental
Using Decisions to Solve Problems
Coding Decision Trees
Using Primitive Data Types
Strings and String Manipulation
More about Syntax
72
SNU
IDB Lab.
Using Decisions to Solve Problems (1/2)


Want to make programs seem “intelligent”
A Number Guessing Game: one person selects a number
between 1 and 100, and the other person tries to guess


AboveBelow.java
AboveBelow.html
73
SNU
IDB Lab.
//import awb.*;
import java.awt.*;
import java.awt.event.*;
public class AboveBelow extends java.applet.Applet
implements ActionListener
{
TextField m1, m2;
IntField i1;
Button b1, b2;
int secret, guess;
public void init ()
{
m1 = new TextField(80);
m1.setText("Enter number between 0 and 100 +
"below, then push SECRET");
i1 = new TextField(40);
m2 = new TextField(80);
b1 = new Button("SECRET");
b2 = new Button("GUESS");
add(m1);
add(b1);
add(i1);
add(b2);
add(m2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
Object cause = event.getSource();
if (cause == b1)
{
secret = Integer.parseInt(i1.getText());
i1.setText("");
m1.setText("Now, enter your guess below,”+
" then press GUESS");
}
if (cause == b2)
{
guess = Integer.parseInt(i1.getText());
if (guess == secret)
{
m2.setText("You've got it!");
}
if (guess < secret)
{
i1.setText("");
m2.setText("The number is greater than "+
guess);
}
if (guess > secret)
{
i1.setText("");
m2.setText("The number is less than "+guess);
}
}
} // The end of actionPerformed()
} // The end of Class AboveBelow
AboveBelow.java
74
SNU
IDB Lab.
Java Fact

AboveBelow program


처음에 사용자가 IntField에서 수를 입력하고 b1을 click하면 IntField의
수를 secret이라는 변수에 저장을 하고 IntField를 지운다.
그리고 사용자가 수를 입력해가면 secret 수와 맞는지 비교하고 맞출
때까지 진행하는 프로그램

Import awb.*  저자 패키지를 사용하기 위해 선언

IntField class (소스는 503 페이지의 appendix에 있음)




IntField i1;
// i1선언
i1 = new IntField(40) //
Secret = i1.getInt() 사용자가 입력한 수를 secret에 저장
i1.setInt();
 i1의 내용을 지움
75
SNU
IDB Lab.
AboveBelow.html
<HTML>
<HEAD> <TITLE> High/Low Response Demo Program.</TITLE> </HEAD>
<BODY> Demonstrate if and logic capability.
<APPLET code="AboveBelow.class" WIDTH=650 HEIGHT=300> </APPLET>
</BODY>
</HTML>
76
SNU
IDB Lab.
Using Decisions to Solve Problems (2/2)

How Many Guesses Should it Take?






For
For
For
For
For
range
range
range
range
range
1-100?
1-1000?
1-10,000?
1-100,000?
1-1,000,000?
Binary Search

Telephone book or dictionary
77
SNU
IDB Lab.
Table of Contents








Put some Action into Web Pages
Object Oriented Programming
Java Language Fundamental
Using Decisions to Solve Problems
Coding Decision Trees
Using Primitive Data Types
Strings and String Manipulation
More about Syntax
78
SNU
IDB Lab.
Coding Decision Trees (1/3)


Draw a decision tree
Vocabulary



tree, binary tree
node, edge, path, root, leaf
Generally useful for many applications



Search by Identification Keys
Classifying plants, animals, etc.
Medical Diagnosis
79
SNU
IDB Lab.
To Figure 2.3
Figure 2.2: User Interaction in Nobel Prize Home Page
80
SNU
IDB Lab.
Figure 2.3: Deeper Level User Interaction in Nobel Prize Home Page
81
SNU
IDB Lab.
Figure 2.4: Medical Advice Decision Tree
82
SNU
IDB Lab.
Figure 2.5: NIM game
83
SNU
IDB Lab.
Figure 2.6: Decision tree for 2nd player in the game of NIM
84
SNU
IDB Lab.
Coding Decision Trees (2/3)

Car Diagnosis Problem: Decision Tree

Can't get car's engine to run; what is the problem?
•yes
•is gas gauge on empty?
•no
•does engine crank?
•was car just running
and quit now?


•yes
•get gas
•no
•call tow truck
•yes
•check gas
•no
•check battery
CarD.java
CarD.html
85
SNU
IDB Lab.
import java.awt.*;
import java.awt.event.*;
if (location == 0)
{
location = 1;
mQuery.setText("Is the gas gauge on empty?");
}
else if (location == 1)
{
location = 3;
mAnswer.setText("Better find some gas.");
}
else if (location == 2)
{
location = 5;
mAnswer.setText("Maybe you should check the gas.");
}
public class CarD extends java.applet.Applet
implements ActionListener
{
TextField mQuery, mAnswer;
Button bYes, bNo;
int location;
public void init()
{
mQuery = new TextField(70);
mQuery.setText("Was your car just now running before“ +
" it quit?");
bYes = new Button("Yes");
bNo = new Button("No");
location = 0;
mAnswer = new TextField(70);
bYes.addActionListener(this);
bNo.addActionListener(this);
add(mQuery) ;
add(bYes) ;
add(bNo) ;
add(mAnswer) ;
}
public void actionPerformed(ActionEvent event)
{
Object cause = event.getSource();
if (cause == bYes)
{
CarD.java
}
86
}
}
if (cause == bNo)
{
if (location == 0)
{
location = 2;
mQuery.setText("Does the engine crank?");
}
else if (location == 1)
{
location = 4;
mAnswer.setText("Messy. Call a tow truck.");
}
else if (location == 2)
{
location = 6;
mAnswer.setText("Looks like a dead battery.");
}
}
SNU
IDB Lab.
Car Diagnosis Problem
CarD.html
<HTML>
<HEAD>
<TITLE> Car Diagnosis Problem.</TITLE>
</HEAD>
<BODY>
This demonstrates decision trees.
<APPLET code="CarD.class" WIDTH=600 HEIGHT=300>
</APPLET>
</BODY>
</HTML>
87
SNU
IDB Lab.
Coding Decision Trees (3/3)

Picking a Textbook Problem: Decision Tree
•yes
•(1) a programming focus
instead of theory?
•(0) do you wish a
mathematical approach?
•no


•(2) narrow focus instead
of overview of CS?
•yes
•(3) Oh! Pascal
by D. Cooper
•no
•(4) Algorithmics
by D. Harel
•yes
•no
•(5) Karel the Robot
by R. Pattis
•(6) Great Ideas in
CS
by A. Biermann
BookPick.java
BookPick.html
88
SNU
IDB Lab.
import java.awt.*;
import java.awt.event.*;
public class BookPick extends java.applet.Applet
implements ActionListener
{
TextField mQuery, mAnswer;
Button bYes, bNo;
int myLocation;
public void init()
{
mQuery = new TextField(70);
mQuery.setText("Do you wish a mathematical approach?");
bYes = new Button("Yes");
bNo = new Button("No");
myLocation = 0;
mAnswer = new TextField(70);
bYes.addActionListener(this);
bNo.addActionListener(this);
add(mQuery);
add(bYes);
add(bNo);
add(mAnswer);
}
public void actionPerformed(ActionEvent event)
{
Object cause = event.getSource();
if (myLocation == 0)
{
if (cause == bYes)
{
myLocation = 1;
mQuery.setText("A programming focus "+
instead of theory?");
}
}
}
if (cause == bNo)
{
myLocation = 2;
mQuery.setText("Narrow focus instead of overview of CS?");
}
}
else if (myLocation == 1)
{
if (cause == bYes)
{
myLocation = 3;
mAnswer.setText("I recommend 'Oh! Pascal' by D. Cooper.");
}
if (cause == bNo)
{
myLocation = 4;
mAnswer.setText("'Algorithmics' by D. Harel is a fine book.");
}
}
else if (myLocation == 2)
{
if (cause == bYes)
{
myLocation = 5;
mAnswer.setText("Try 'Karel the Robot' by R. Pattis.");
}
if (cause == bNo)
{
myLocation = 6;
mAnswer.setText("Enjoy A. Biermann's 'Great Ideas in CS'");
}
}
BookPick.java
89
SNU
IDB Lab.
“Picking a Book” Problem
BookPick.html
<HTML>
<HEAD>
<TITLE> Picking a Textbook Problem.</TITLE>
</HEAD>
<BODY>
This demonstrates decision trees.
<APPLET code="BookPick.class" WIDTH=600 HEIGHT=300>
</APPLET>
</BODY>
</HTML>
90
SNU
IDB Lab.
Table of Contents

Put some action into web pages
Object Oriented Programming
Java Language Fundamental
Using Decisions to Solve Problems
Coding Decision Trees
Using Primitive Data Types
Strings and String Manipulation

More about Syntax






91
SNU
IDB Lab.
Using Primitive Data Types: Integers (1)



Primitive data types does not require a NEW statement to
create
Primitive data types are not classes
Primitive data types must be declared and initialized (Java
sets to 0)


int noTotal = 0;
Other primitive types include: boolean, char, float
92
SNU
IDB Lab.
Using Primitive Data Types: Integers (2)

Example for counting integers



Count.java
Count.html
Example for calculating multiple tallies


Tallies.java
Tallies.html
93
SNU
IDB Lab.
// Program to demonstrate integer counting triggered by pushing a button
import java.awt.*;
import java.awt.event.*;
Count.java
public class Count extends java.applet.Applet implements ActionListener
{
TextField mQuery,mAnsStu, mAnsFac, mAnsSta, mTotal;
Button bCount;
int noTotal = 0;
public void init ()
{
mQuery = new TextField(80);
mQuery.setText("Keep track of attendance by pushing the button.");
bCount = new Button("Register");
mTotal = new TextField(40);
}
}
bCount.addActionListener(this);
add(mQuery) ;
add(bCount) ;
add(mTotal) ;
mTotal.setText("The total attendance is " + noTotal);
public void actionPerformed(ActionEvent event)
{
Object cause = event.getSource();
if (cause == bCount)
{
noTotal = noTotal + 1;
mTotal.setText("The total attendance is " + noTotal + " ");
}
}
94
SNU
IDB Lab.
Count Problem
Count.html
<HTML>
<HEAD>
<TITLE> Applet Response Demo Program.</TITLE>
</HEAD>
<BODY>
<APPLET code="Count.class" WIDTH=700 HEIGHT=200>
</APPLET>
</BODY>
</HTML>
95
SNU
IDB Lab.
import java.awt.*;
import java.awt.event.*;
public class Tallies extends java.applet.Applet implements ActionListener
{
TextField mQuery,mAnsStu, mAnsFac, mAnsSta, mTotal;
Button bStudents,bFaculty,bStaff;
int noStu=0, noFac=0, noSta=0, noTotal=0;
public void init ()
{
mQuery = new TextField(80);
mQuery.setText("Keep track of attendance by pushing the buttons.");
bStudents = new Button("Students");
bFaculty = new Button("Faculty");
bStaff = new Button("Staff");
mAnsStu = new TextField(12);
mAnsFac = new TextField(12);
mAnsSta = new TextField(12);
mTotal = new TextField(80);
bStudents.addActionListener(this);
bFaculty.addActionListener(this);
bStaff.addActionListener(this);
add(mQuery) ;
add(bStudents) ;
add(bFaculty) ;
add(bStaff) ;
add(mTotal) ;
add(mAnsStu) ;
add(mAnsFac) ;
add(mAnsSta) ;
mTotal.setText("The total attendance is " + noTotal +
" Subtotals are shown below.");
mAnsStu.setText(noStu + " students");
mAnsFac.setText(noFac + " faculty");
mAnsSta.setText(noSta + " staff");
}
96
public void actionPerformed(ActionEvent event)
{
Object cause = event.getSource();
if (cause == bStudents)
{
noStu = noStu + 1;
noTotal = noTotal + 1;
mTotal.setText("The total attendance is " +
noTotal +
" Subtotals are shown below.");
mAnsStu.setText(noStu + " students");
}
if (cause == bFaculty)
{
noFac = noFac + 1;
noTotal = noTotal + 1;
mTotal.setText("The total attendance is " +
noTotal +
" Subtotals are shown below.");
mAnsFac.setText(noFac + " faculty");
}
if (cause == bStaff)
{
noSta = noSta + 1;
noTotal = noTotal + 1;
mTotal.setText("The total attendance is " +
noTotal +
" Subtotals are shown below.");
mAnsSta.setText(noSta + " staff");
}
}
}
Tallies.java
SNU
IDB Lab.
Tally Problem
Tallies.html
<HTML>
<HEAD>
<TITLE> Applet Response Demo Program.</TITLE>
</HEAD>
<BODY>
<APPLET code="Tallies.class" WIDTH=700 HEIGHT=200>
</APPLET>
</BODY>
</HTML>
97
SNU
IDB Lab.
Table of Contents

Put some action into web pages
Object Oriented Programming
Java Language Fundamental
Using Decisions to Solve Problems
Coding Decision Trees
Using Primitive Data Types
Strings and String Manipulation

More about Syntax






98
SNU
IDB Lab.
String class

String Declaration:



String Constant


String message;
String xyz;
"Good Morning World!"
String Assignment

message = "It's Friday";
99
SNU
IDB Lab.
Methods in String class (1/2)

Most important ones are: length(), indexOf(), substring()


Note that character positions start at zero!
int word.length()


int word.indexOf(String st)



Returns the length of the string word as an integer
Returns position of start of first match of st in word
Returns -1 if there is no match
string word.substring(int start, int end)



Returns a String that is part of word
start is position in word of first char of the substring
end is position in word of first char after the substring
100
SNU
IDB Lab.
Methods in string class (2/2)

If word contains "Good Afternoon!"




word.length()
word.indexOf("tern")
word.indexOf("Tern")
word.substring(5, 8)
yields 15
yields 7
yields -1
yields "Aft"
101
SNU
IDB Lab.
Example using String Class

Getting String Data from the User


The TextField class has getText() method
Can use:


message = mg.getText();
where mg is a TextField and message is a String
Example for Some String Manipulation




User types in his first name, middle name, and last name.
And then push the button  show the full name, initial, length of
the name
StringPlay.java
StringPlay.html
102
SNU
IDB Lab.
import java.awt.*;
import java.awt.event.*;
public class StringPlay extends java.applet.Applet implements ActionListener
{
TextField mInstruct, mFirst,mMid, mLast, mFull, mInit,
gmFirst, gmMid, gmLast;
Button bEnter;
String sFirst, sMid, sLast, sInit, sFull;
int length;
public void init ()
{
mInstruct = new TextField(72);
mInstruct.setText("Please enter your full name in the fields below."
+ " Then click Enter.");
mFirst = new TextField(9);
mMid = new TextField(9);
mLast = new TextField(9);
mFirst.setText("First:");
mMid.setText("Middle:");
mLast.setText("Last:");
gmFirst = new TextField(60);
gmMid = new TextField(60);
gmLast = new TextField(60);
mFull = new TextField(72);
mInit = new TextField(72);
bEnter = new Button("Enter");
bEnter.addActionListener(this);
add(mInstruct) ;
add(mFirst) ;
add(gmFirst) ;
add(mMid) ;
add(gmMid) ;
add(mLast) ;
add(gmLast) ;
103
}
add(bEnter) ;
add(mFull) ;
add(mInit) ;
public void actionPerformed(ActionEvent event)
{
Object cause = event.getSource();
if (cause == bEnter)
{
sFirst = gmFirst.getText();
sMid = gmMid.getText();
sLast = gmLast.getText();
sFull = sFirst + " " + sMid + " " + sLast;
mFull.setText("Your full name is: " + sFull);
sInit = sFirst.substring(0,1) + sMid.substring(0,1) +
sLast.substring(0,1);
length = sFirst.length() + sMid.length() +
sLast.length();
mInit.setText("Your initials are: " + sInit +
". The number of characters in your name is " +
length);
}
}
}
StringPlay.java
SNU
IDB Lab.
String-Play Problem
StringPlay.html
<HTML>
<HEAD>
<TITLE> String Manipulation Program.</TITLE>
</HEAD>
<BODY>
<APPLET code="StringPlay.class" WIDTH=650 HEIGHT=300>
</APPLET>
</BODY>
</HTML>
104
SNU
IDB Lab.
String Exchange

An Algorithm: The String Exchange Problem



at start: x contains "milk" and y contains "juice"
how do we interchange contents?
Textfield sampletext;
need temp
string x, y, temp;
...
x = sampletext.getText();
y = sampletext.getText();
sampletext.setText(“Now” + x + " and " + y);
...
temp = x;
x = y;
y = temp;
...
sampletext.setText(“Now” + x + " and " + y );
...
105
SNU
IDB Lab.
Table of Contents








Put some action into web pages
Object Oriented Programming
Java Language Fundamental
Using Decisions to Solve Problems
Coding Decision Trees
Using Primitive Data Types
Strings and String Manipulation
More about Syntax
106
SNU
IDB Lab.
More about Syntax (1)

Compiler



1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
need to check the correctness of program syntax
need to understand the program
Grammar is a set of production rules
<name> any string of alphanumeric symbols that begins with a letter
<statement>  <name> = <expression>;
<statement>  <name> = new <class>(<arguments>);
<statement>  <name>.<method>(<arguments>); | <method>(<arguments>);
<arguments>  possibly empty list of <expression>s separated by commas
<expression>  <string-expression> | <int-expression> | <oth-expression>
<string-expression>  <string-expression> + <string-expression>
<string-expression>  <string>
<string>  " any sequence of characters "
<string>  <name>
107
SNU
IDB Lab.
More about Syntax (2)


Apply production rules with substitution multiple times as necessary
Statement Example

Want to check: person-name = firstname + " " + lastname;
EXAMPLE:
<statement>
<statement>
<statement>
<statement>
<statement>
<statement>
<statement>
<statement>
<statement>
<statement>
<statement>
<statement>
 <name> = <expression>;
 person-name = <expression>;
 person-name = <str expression>;
 person-name = <str expression> + <str expression>;
 person-name = <string> + <str expression>;
 person-name = <name> + <str expression>;
 person-name = firstname + <str expression>;
 person-name = firstname + <string> + <str expression>;
 person-name = firstname + " " + <str expression>;
 person-name = firstname + " " + <string>;
 person-name = firstname + " " + <name>;
 person-name = firstname + " " + lastname;
108
SNU
IDB Lab.
More about Syntax (3)

More Syntax
<method>  setText | getText | getInt | setInt | add | actionPerformed | init
<compound-statement>  { list of <statement>s }
<statement>  if (<bool-expression>)
<compound-statement>
<statement>  if (<bool-expression>) <compound-statement>
else <compound-statement>
See 78 page of the text book!
109
SNU
IDB Lab.
Table of Contents








Put some action into web pages
Object Oriented Programming
Java Language Fundamental
Using Decisions to Solve Problems
Coding Decision Trees
Using Primitive Data Types
Strings and String Manipulation
More about Syntax
110
SNU
IDB Lab.
Summary




참고자료: Control Oriented Programming, Basics of C , OOP
Basic Concepts of Object-oriented Paradigm
Program skeleton based on decision trees
Simple examples of Java code to describe the algorithm




class definition and type declaration
button-declaring and button-actuating code
applet display features
if-else branching forms
111
SNU
IDB Lab.
If you want to learn more about Java
and you are energetic… (But I don’t think so)

http://java.sun.com/docs/books/tutorial/index.html

http://www.javacoffeebreak.com/tutorials/

Of course, Many many 자바 books in 시중서점
112
SNU
IDB Lab.


Ch2: Here comes Java
Textbook Review Time
113
SNU
IDB Lab.