1 תרגול 2 – מבוא לתכנות JAVA. היום בתרגול : 2 משתנים...

Preview:

Citation preview

1

JAVA – מבוא לתכנות 2תרגול

היום בתרגול:2

משתנים וטיפוסיםאופרטורים פונקציות מתמטיות מהמחלקהMathהמרת טיפוסיםתנאיםDebugger

משתנים וטיפוסים3

מהו משתנה?הוא יחידת מידע המאחסנת ערך ( variable) משתנה

במהלך ריצת התוכנית.

ניתן להשתמש במשתנים על מנת לשמור ערכים, ולקבלם מאוחר יותר בתוכנית. ניתן לבצע פעולות בשלב

חישוביות בעזרת משתנים.

. הטיפוס קובע אילו סוגי (type) טיפוסלכל משתנה יש ערכים המשתנה יכול להכיל.

הגדרת משתנים4

יש להכריז על שמו של המשתנה וטיפוסו.

int מטיפוס numלמשל זוהי הגדרה על משתנה בשם )מספר שלם(.

int num;

אפשר להגדיר מספר משתנים מאותו טיפוס בשורה אחת.

int num1, num2;

טווח הכרה של משתנה5

הוא האזור בתוכנית שבו ( scope) של משתנה טווח ההכרההמשתנה מוגדר וניתן להשתמש בו.

טווח ההכרה של משתנה תלוי בבלוק בו הוא מוגדר)בלוק מצוין ע"י סוגריים מסולסלים(.

טווח ההכרה של המשתנה מתחיל בשורה שבו המשתנהמוגדר ומסתיים בסוף הבלוק שבו נמצאת הגדרת

המשתנה.

פעולת השמה6

נותנת ערך למשתנה. (assignment) השמהפעולת

= הוא סימן פעולת השמה, משמאל שם המשתנה ומימין הערך.

פעולת השמה חייבת להופיע בתוך טווח ההכרה שלהמשתנה.

. num למשתנה 3למשל, הפקודה הבאה נותנת ערך

num = 3;

ניתן להגדיר את המשתנה ולבצע השמה בשורה אחת:

int num1 = 1;אין להשתמש במשתנה שלא קיבל ערך !

:דוגמה7

public class Example1 {public static void main(String[] args){ int num; num = 3;

int num1 = 1, num2; num2 = num1;

System.out.println("num = " + num); System.out.println("num1 = " + num1); System.out.println("num2 = " + num2);

}}

scope of num1 andnum2

scope of num•טבלת משתנים

הגדרה• שמות• סקופ•השמה•פלט•

טיפוסים8

טיפוס של משתנה קובע:אילו ערכים יכול המשתנה להכילמהן הפעולות שניתן לבצע על המשתנה

רקע הזיכרון במחשב הוא זיכרון בינארי(binary) .ביט (bit) 1 או 0- יחידת זיכרון בינארית. ביט יכול להיות . בתיםזיכרון המחשב נמדד ביחידות בסיסיות הנקראות

(bytes) .1 byte = 8 bit .משתנים מאוחסנים בזיכרון המחשב נשמרים בבתים

מספר הבתים שדורש אחסון של משתנה תלוי בטיפוסו. לצורך הבנה מלאה של הנושא עליכם לקרוא באופן

עצמאי על הנושא, התחלה טובה היא: Binary - Wikipedia.

טיפוסים פרימיטיביים 9

טיפוסים נומריים שלמים1.הטיפוסים נומריים מייצגים מספרים שלמים:

byte, short, int, longלמשל:

long longNum, longNum2;byte byteNum = 125;longNum = 1234567890;

. טיפוסים ממשיים2. double, floatהטיפוסים הממשיים הם

למשל:double doubleNum;doubleNum = 3.75;

טיפוסים פרימיטיביים 10

. טיפוסים לוגיים3. משתנים מטיפוס זה בעלי booleanהטיפוס הלוגי נקרא

.false או trueערך boolean indicator; indicator = true;

. תווים4 ,'a'. סימן בודד התחום בגרשיים בודדות )למשל, charתו:

'A'.)\' newline )למשל, backslashלפני סימן מיוחד יש תו

n', tab '\t' , backspace '\b')char capitalN;capitalN = 'N';

טבלת סיכום טיפוסים מספריים

ערכים bytesמספר ה טיפוס

27-1 עד 27- 1 byte

215-1 עד 215- 2 short

231-1 עד 231- 4 int

263-1 עד 263- 8 long

4 float

8 double

11

קבועים12

הוא יחידת מידע המאחסנת ערך במהלך (constant) קבועריצת התוכנית.

קבוע דומה למשתנה; ההבדל הוא שערכו של קבוע לאיכול להשתנות במהלך התוכנית מרגע שהקבוע קיבל את

ערכו הראשוני.:דוגמה

final int PASS_GRADE = 56;

int grade;

grade = PASS_GRADE;

אופרטורים13

על משתנים וערכים ניתן לבצע פעולות שונות, בהתאם לטיפוס.

אופרטורים מבצעים חישוב ומחזירים תוצאה.

אופרטורים אריתמטיים1.

על משתנים וערכים מטיפוסים נומריים וממשיים אפשר לבצע פעולות אריתמטיות:

1דוגמה 14

/* This program demonstrates addition and multiplication between integers. */

public class OperatorsExample1{public static void main(String[] args){

int a = 3, b = 5;int c;

c = a + b;System.out.println("c = "+ c);c = c * 2;System.out.println("c = "+ c);

}}c = 8c = 16

2דוגמה 15

התוכנית הבאה מדגימה את סדר הפעולות של הפעולות האריתמטיות:

public class OperatorsExample {public static void main(String[] args) {

int a = 18;int b = 42;int first = (a + b) * 2;int second = a + b * 2;System.out.println("first number is:" + first);System.out.println("second number is:" + second);

}}

first number is:120second number is:102

3דוגמה

16

import java.util.Scanner;/* This program accepts a 3-digit number from the user * reverses the digits and prints the result */public class Reverse {

public static void main(String[] args) {// Read a number from the user.Scanner sc = new Scanner(System.in);System.out.print("Enter a 3-digit number:");int num = sc.nextInt();// divide the number into ones, tens and hundreds.int ones = num % 10;int tens = (num % 100) / 10;int hundreds = num / 100;// calculate the reverse numberint reverseNum = (ones * 100) + (tens * 10) + hundreds;System.out.println("The reverse number is " + reverseNum);

}} Enter a 3-digit number:

The reverse number is 159

951

אופרטורים יחסיים אופרטורים המשווים בין שני מספרים ונותנים תשובה 6 יש Javaב

(.false או trueבוליאנית )

Operator Name Description

x < y Less than true if x is less than y, otherwise false.

x > y Greater than true if x is greater than y, otherwise false.

x <= y Less than or equal totrue if x is less than or equal to y, otherwise

false.

x >= y Greater than or equal

totrue if x is greater than or equal to y, otherwise

false.

x == y Equal true if x equals y, otherwise false.

x != y Not Equal true if x is not equal to y, otherwise false.

17

דוגמה

18

import java.util.Scanner;// This program compares two numbers with relational operatorspublic class RelationalOperators {

public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.print("Enter the first number:");int x = sc.nextInt();System.out.print("Enter the second number:");int y = sc.nextInt();System.out.println("x<y is " + (x < y));System.out.println("x>y is " + (x > y));System.out.println("x<=y is " + (x <= y));System.out.println("x>=y is " + (x >= y));System.out.println("x==y is " + (x == y));System.out.println("x!=y is " + (x != y));

}}

Enter the first number:10Enter the second number:20

x<y is truex>y is falsex<=y is truex>=y is falsex==y is falsex!=y is true

אופרטורים לוגייםאופרטורים לוגיים פועלים על ערכים מטיפוס לוגי )בוליאני(

(.false או trueוגם נותנים תשובה בוליאנית )Operat

orNam

eDescription

x && y And True if both x and y are true, otherwise false.

x || y OrTrue if at least one of x or y are true, otherwise

false.

! x Not True if x is false, otherwise false.

19

מתבצעת משמאל לימין.Or ו And* הערכת האופרטורים הלוגיים

דוגמה

20

import java.util.Scanner;// This program demonstrates logical operators.// It reads two integers from the user and checks if // they are larger than 10.public class LogicalOperators {

public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter the first number:"); int x = sc.nextInt(); System.out.print("Enter the second number:"); int y = sc.nextInt(); System.out.println("(y<10)&&(x<10) is " + ((y<10) && (x<10))); System.out.println("(y<10)||(x<10) is " + ((y<10) || (x<10))); boolean state; state = ((y < 10) || (x < 10)); System.out.println("state is " + state);}

}(y<10)&&(x<10) is false(y<10)||(x<10) is truestate is true

Enter the first number:10Enter the second number:9

Mathהמחלקה 21

מאגדת בתוכה פונקציות מתמטיות שימושיות Mathהמחלקה וקבועים.

Math.abs(x) ערך מוחלט של –x.Math.max(x1,x2), Math.min(x1, x2) המינימום –

.x2 ו x1והמקסימום )בהתאמה( בין Math.pow(x, y) מחשב את –x בחזקת y (xy).Math.sqrt(x) שורש ריבועי של –x.Math.random )( לא כולל 1 ל 0– מחזיר מספר אקראי בין(

1).Math.PI קבוע המייצג את הערך – (3.14159...)

דוגמה22

public class UseMath { public static void main(String[] args){

// This is an example of using Math methodsdouble x = Math.abs(-3);x = Math.pow(x, 2 );x = Math.max(x, Math.PI);System.out.println("max( (|-3|)^2 , Pi ) = " + x);x = Math.random();System.out.println("A random number between 0 and

1: "+ x);}

} max( (|-3|)^2 , Pi ) = 9.0A random number between 0 and 1: 0.9764623048094814

Java ומחלקות רבות נוספות כלולות בספריות Mathהמחלקה .Javaהכלולות בהתקנת

Java ומחלקות נוספות הכלולות ב Mathמידע מפורט על מחלקת ניתן למצוא בקישור

http://download.oracle.com/javase/6/docs/api/java/lang/Math.html

(Castingהמרת טיפוס )23

יש טיפוס ספציפי. Javaלכל משתנה ב ?מה קורה כאשר מערבים טיפוסים שונים בביטוי במקרים מסוימיםJava מטפלת בטיפוסים השונים

באופן אוטומטי ובפעמים אחרות אנחנו חייבים לבצע המרה מפורשת של טיפוס נתונים אחד לאחר.

המרות אוטומטיות1.כאשר מבצעים פעולה אריתמטית הערך המתקבל הינו בעל טיפוס מסוים. אם כך המרכיבים מאותו טיפוס אז הטיפוס המתקבל

בפעולה הינו זהה.long y, w;long z = w + y;

.long הינו מטיפוס w+yהערך של הביטוי

(Castingהמרת טיפוס )24

כאשר מרכיבי הביטוי הינם מטיפוסים שונים הביטוי ביותר.הכוללהמתקבל יהיה מהטיפוס של המרכיב

הסדר של טיפוסים המספרים מן הפחות כולל לכולל ביותר.byte, short, int, long, float, doubleהינו:

דוגמה האופרטור / עובד אחרת בהתאם לטיפוסים עליהם הוא

מופעל. 5.0/2 --> 2.5 5.0/2.0 --> 2.5 5/2.0 --> 2.5 5/2 --> 2

(Castingהמרת טיפוס )25

. המרות יזומות2ניתן לבצע המרת טיפוס ע"י שימוש בפעולת השמה.

הביטוי הימני עובר המרה לטיפוס של המשתנה המופיע בצד .שמאל של ההשמה

int i = 5;

double d;

d = i; // d is 5.0

המרה כזו אפשרית רק כאשר הטיפוס של המשתנה בצד מהטיפוס של הביטוי בצד ימין.כללי יותרשמאל

(Castingהמרת טיפוס )26

במקרה ההפוך, כאשר הטיפוס של המשתנה בצד שמאלכללי פחות מהטיפוס של הביטוי בצד ימין, נשתמש

.type cast : (<type>)באופרטור ה double d = 5.3;int i ;i = (int) d; // i is 5

שימוש נוסף באופרטור הtype cast הוא כאשר רוצים למנוע איבוד של חלק השבר בחלוקה של מספרים שלמים:

double d;int x = 5, y = 2 ;d = ((double) x)/y;d = (double) x/y;

if-elseמשפט 27

הוא מבנה בסיסי בשפה המאפשר לשלוט if-elseמשפט בזרימת התוכנית. למשפט זה יש שתי צורות:

if (<condition>){<statement>

}

if (<condition>){<statement>

} else {<alternative>

}

ifדוגמה ל-

28

import java.util.Scanner; public class Triangle { public static void main(String[] args) {

Scanner sc = new Scanner(System.in);System.out.print("Enter the first number:");double a = sc.nextInt();System.out.print("Enter the second number:");double b = sc.nextInt();System.out.print("Enter the third number:");double c = sc.nextInt();

 if ((a + b <= c) || (a + c <= b) || (b + c <= a)) { System.out.println("There is no triangle with these sides.");} else{ System.out.println("There is a triangle with these sides.");}

}}

Debugging

:לפעמים אנחנו לא מקבלים את התוצאות הצפויות(האמת שזה קורה כמעט תמיד, עד שאנחנו מתקנים את

הבעיות) :סוגים של בעיות

קומפילציה בעיית .טעות תחבירית שמונעת מהמהדר לפרש את הקוד.בד"כ המהדר מספק מידע על מיקום ומהות הטעות

שגיאת זמן ריצהבזמן הריצה מתקיימת שגיאהניתן לדעת בדיוק היכן ארעה שגיאה זו. תוך שימוש בdebugger .

שגיאה לוגית.התוכנית רצה היטב אך התשובה המתקבלת לא נכונה .מוצאים ע"י בדיקות המכסות את כל מחלקות השקילות

29

הפעולות הבסיסיות לפעולות :Eclipseהדיבוג ב

קביעת נקודות עצירה בתכנית(Set Breakpoints):לחיצה כפולה על העכבר משמאל לשורה.

הפעלת תכנית באמצעותDebugger הקישו :F11 קידום צעד צעד(step by step) הקישו :F6 קידום עד לנקודת העצירה הבאה (או עד הסוף): הקישו

F8 כניסה לתוך פונקציה: הקישוF5 יציאה מפונקציה: הקישוF7-יציאה מהdebugger – Ctrl+F2

30

The DebuggerCreate new project

• Create new project; name it Max3

• Create new class; name it Max3; mark the generation of main method option

• Copy/Paste the following code to the class

• The Scanner class provides possibility to read from command line user input

• nextInt method parse user input to int type after number and enter pressed

• Try to execute ones the program (enter user input in Console window, bottom of the screen)

public static void main(String[] args) {Scanner reader = new

Scanner(System.in);int a, b, c;// input variablesint max;// max value

System.out.println("Please enter three integers:");

a = reader.nextInt();b = reader.nextInt();c = reader.nextInt();

max = a;if (b > max)

max = b;if (c > max)

max = c;

System.out.println("The max value is: " + max);}

The DebuggerAdd breakpoints

• A breakpoint suspends the execution of a program at the location where the breakpoint is set.

• Double click in front of a = reader.nextInt();line of code, on place of the blue circle on the figure.

• You've just created a breakpoint.

• To delete it double-click on the blue circle.

• Create another breakpoint on theif (b > max)

line of code.

The DebuggerDebug the code

• Press the bug button on the button bar, or choose Run | Debug from the menu bar.

The DebuggerDebug the code

• The IDE will switch to Debug Perspective, view with different windows layout than in coding mode - this perspective more convenient for debugging tasks.

The DebuggerDebug the code

• The execution of the program paused on the first breakpointo on the blue circle appears blue arrowo current line marked with green

• The JVM still not executed the current line

The DebuggerDebug the code

• In the buttons bar and the Run menu you can see debug main actions toolso Resume - for resuming

program executiono Terminate - to kill the

programmo Step Into - to enter inside

logic, the method, of the current line (more of this after learning methods)

o Step Over - execute current line and go to next one

o Step Return - in case you inside some inner method, execute the whole method and pause execution after exit from the method

The DebuggerDebug the code

• On the top right window of the Debug perspective one of the existent tabs is Variables tab

• Click on this tab and remember what you see there (arg and reader variables)

The DebuggerDebug the code

• Press the Step Over button

• The JVM will execute the current line, so the execution means

reading user input from command line

• Enter 13 in the Console window and press enter

The DebuggerDebug the code

• Now pay attention what happened in the Variables tab - the new assigned variable a appears there with the assigned value, 13o You can also hover with mouse pointer over the a variable in

the code area and you also will see the current a's value, 13.

• In such a way you can always examine current state of your variables

The DebuggerDebug the code

• Now press the Resume button.

• After pressing Resume,debugger execute the code till the end of the application execution, or till some breakpoint will hit, or till some exception will raise. In our case it will be next breakpoint hit on the line of code: if (b > max) (of course before you should finish interaction with the program as user - enter second and third integers in Console window, 14 and 15 for example).

The DebuggerDebug the code

• Current state of the Variables

• As we can see b is bigger than max, so the expression inside the if evaluates to true, therefore, the then statement, max = b, should be executed.

• Let's press the Step Over button - the execution moved to the max = b line of code.

The DebuggerDebug the code

• Let's press again Step Over and will see the change of variable max in the Variables window after new assignment max = b;

• Eclipse automatically marked change in variable value with yellow color to pay our attention

The DebuggerDebug the code

• Now let's press the resume button and the application will run till the end and will terminated.

The console window:

Recommended