31
LEC. 05: STRINGS 1

L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT Arrays [review] The For-Each Style for Loop [review] Strings Constructing Strings Operating on Strings

Embed Size (px)

Citation preview

Page 1: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

1

LEC. 05: STRINGS

Page 2: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

2

2015 SPRING CONTENT

Arrays [review] The For-Each Style for Loop [review] Strings

Constructing Strings Operating on Strings Arrays of Strings Using a String to Control a switch statement

Using Command-Line Arguments The Bitwise Operators [ 不測驗,列補充教材 ] The ? Operator

Page 3: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

3

EXERCISE 1A

計算英文全班 (5 人 ) 的平均分數class Ex1a{

public static void main(String args[]) {

float score1 = (float) 70.1;

float score2 = (float) 71.1;

float score3 = (float) 72.1;

float score4 = (float) 73.1;

float score5 = (float) 74.1;

float sum = (float) 0.0;

sum = score1 + score2 + score3 + score4 + score5;

System.out.println(sum/5);

}

}無擴充性

Page 4: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

4

ARRAYS

An array is a contiguous memory space with fixed size used to store a group of data with the same data type.

An array is the simplest and basic data structure used to store one or more logical-related data. An array can be used to store all the objects representing the

students of a department. An array can be used to store all the objects representing the

employees of a company.

Page 5: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

5

1. class app80

2. {

3. public static void main(String[] args)

4. {

5. // double a;

6. double a[] = new double[10];

7. //double[] a = new double[10];

8. a[0] = 43.0;

9. a[1] = 3.0;

10. a[2] = 4.0;

11. System.out.println(a[0] + " " + a[2]);

12. }

13. }

EXAMPLE OF ARRAY

43.0 4.0

Page 6: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

6

1. class app86

2. {

3. public static void main(String[] args)

4. {

5. double grades[] = {88, 99, 73, 56, 87, 64};

6. double sum=0, average;

7. for(int i=0; i<grades.length; i++)

8. sum += grades[i];

9. average = sum / grades.length;

10. System.out.println(average);

11. }

12. }

EXAMPLE OF ARRAY

Page 7: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

7

EXERCISE 1B

計算英文全班 (10 人 ) 的平均分數

Page 8: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

8

1. // Demonstrate an array overrun.

2. class ArrayErr {

3. public static void main(String args[]) {

4. int sample[] = new int[10];

5. int i;

6.

7. // generate an array overrun

8. for(i = 0; i < 100; i = i+1)

9. sample[i] = i;

10. }

11. }

OUT-OF-BOUND EXAMPLE

Page 9: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

9

FOR-EACH STYLE FOR-CONSTRUCT Beginning with J2 SDK v. 1.5, Java supports a new for-

each style for-construct, so called enhanced for-construct. The enhanced for-construct cycles through a collection of

objects, such as an array, in strictly sequential fashion, from start to finish.

Syntax form

for(<type> <itr-var> : <collection>) statement; The <type> specifies the type of <itr-variable> . The <itr-var> specifies the name of an iteration variable that will

receive the elements from <collection>, one at a time, from beginning to end.

The collection being cycled through is specified by <collection>.

Page 10: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

10

class ForEach {

public static void main(String args[]) {

int nums[] = { 11, 12, 13, 14, 15, 16 };

for( int i=0; i<nums.length; i++)

System.out.println(nums[i]);

for( int i : nums ) {

System.out.println(i);

}

}

}

EXAMPLE

111213141516111213141516

Page 11: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

11

EXERCISE 1C

計算英文全班 (10 人 ) 的平均分數

Page 12: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

12

STRINGS

A string is a sequence of zero or more characters. In Java Class Library, java.lang.String represents strings. Each string literal is automatically converted to a String

object in Java. In Java, each String literal is a single String object. In the following segment, both str1 and str2 point to the same

object. (only one String object is created)String str1, str2;

str1 = "Hello"; str2 = "Hello";

A String object can also be constructed by using String constructor. new String("Hello")

Page 13: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

13

STRINGS

Each String object created by using new operator is a individual object. In the following segment, both str1 and str2 point to different

object. (two String objects are created)String str1, str2;

str1 = new String("Hello"); str2 = new String("Hello");

String class is immutable and final. Java also provides another class StringBuffer which is

functionally identical to String class, but it is not immutable.

Page 14: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

14

class StringDemo {

public static void main(String args[]) {

// declare strings in various ways

String str1 = new String("Java strings are objects.");

String str2 = "They are constructed various ways.";

String str3 = new String(str2);

System.out.println(str1);

System.out.println(str2);

System.out.println(str3);

}

}

EXAMPLE

Java strings are objects.They are constructed various ways.They are constructed various ways.

放置物品 , 號碼牌 , 25 號櫃子

Page 15: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

15

COMMONLY USED String SERVICES

Page 16: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

16

class StrOps {

public static void main(String args[]) {

String str1 = "When it comes to Web programming, Java is #1.";

String str2 = new String(str1);

String str3 = "Java strings are powerful.";

int result, idx;

char ch;

System.out.println("Length of str1: " + str1.length());

EXAMPLE

Length of str1: 45

Page 17: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

17

// display str1, one char at a time.

for(int i=0; i < str1.length(); i++)

System.out.print(str1.charAt(i) + " ");

System.out.println();

if(str1.equals(str2))

System.out.println("str1 equals str2");

else

System.out.println("str1 does not equal str2");

result = str1.compareTo(str3);

if(result == 0)

System.out.println("str1 and str3 are equal");

else if(result < 0)

System.out.println("str1 is less than str3");

else

System.out.println("str1 is greater than str3");

str1 equals str2

W h e n i t c o m e s t o W e b p r o g r a m m i n g , J a v a i s # 1 .

str1 is greater than str3

Page 18: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

18

// assign a new string to str2

str2 = "One Two Three One";

idx = str2.indexOf("One");

System.out.println("Index of first occurence of One: " + idx);

idx = str2.lastIndexOf("One");

System.out.println("Index of last occurence of One: " + idx);

}

}Index of first occurence of One: 0Index of last occurence of One: 14

Page 19: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

19

EXERCISE 4

Print a string reversely.

Page 20: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

20

1. class SubStr {

2. public static void main(String args[]) {

3. String orgstr = "Java makes the Web move.";

4.

5. // construct a substring

6. String substr = orgstr.substring(5, 18);

7.

8. System.out.println("substr: " + substr);

9.

10. }

11. }

substr: makes the Web

SUB-STRING EXAMPLE

Page 21: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

21

ARRAYS OF STRINGS

Syntax form 1

<base-type> <array-name> = {<initializer-list>}; Syntax form 2

<array-name> = new <base-type>[]{<initializer-list>}; The initializers are separated by using comma. The length of an array is determined by the number of

initializers. In the form 2, the length cannot be specified.

Page 22: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

22

class StringDemo2 {

public static void main(String args[]) {

String str[] = new String[3];

str[0] = "Java strings are objects.";

str[1] = "They are constructed various ways.";

str[2] = str[1];

String anotherStr[] = {"aaa", "bbb", "ccc"};

System.out.println(str[0]);

System.out.println(str[1]);

System.out.println(str[2]);

System.out.println(anotherStr[0]);

System.out.println(anotherStr[1]);

System.out.println(anotherStr[2]);

}

}

EXAMPLE

Java strings are objects.They are constructed various ways.They are constructed various ways.aaaBbbccc

double a[] = new double[10];

Page 23: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

23

class StringArrays {

public static void main(String args[]) {

String strs[] = { "This", "is", "a", "test." };

System.out.println("Original array: ");

for( String s : strs )

System.out.println(s);

strs[1] = "was";

System.out.println("Modified array: ");

for( String s : strs )

System.out.println(s);

}

}

Original array:Thisisatest.Modified array:Thiswasatest.

EXAMPLE

Page 24: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

24

1. class StringSwitch {

2. public static void main(String args[]) {

3. String command = "cancel";

4. switch(command) {

5. case "connect":

6. System.out.println("Connecting");

7. break;

8. case "cancel":

9. System.out.println("Canceling");

10. break;

11. case "disconnect":

12. System.out.println("Disconnecting");

13. break;

14. default:

15. System.out.println("Command Error!");

16. break;

17. }

18. }

19. }

SWITCH STATEMENT EXAMPLE

Page 25: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

25

EXERCISE 5

續上例,從鍵盤讀入一個指令 Hint

String command;

Scanner scn = new Scanner(System.in);

command = scn.next();

Page 26: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

26

COMMAND-LINE ARGUMENTS A command-line arguments are the information that

directly follows the program’s name on the command line when it is executed by java.

The command-line arguments consist of zero or more strings separated by space.

JVM forms a 1-dimensional array with String base type in which each element is associated with an argument from left to right.

The 1-dimensional array containing arguments is passed to the main method so a program can access the arguments through the parameter of main method .

Page 27: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

27

1. class CLDemo {

2. public static void main(String args[]) {

3. System.out.println("There are " + args.length + " command-line arguments.");

4.

5. System.out.println("They are: ");

6. for(int i=0; i<args.length; i++)

7. System.out.println("arg[" + i + "]: " + args[i]);

8. }

9. }

D:\>java CLDemo aa bb cc ddThere are 4 command-line arguments.They are:arg[0]: aaarg[1]: bbarg[2]: ccarg[3]: dd

EXAMPLE

Page 28: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

28

class Average { public static void main(String args[]) { double sum = 0;

if(args.length > 0) { for(String s : args) { sum = sum + Integer.parseInt(s); // convert string to integer } System.out.println( sum/args.length ); } else System.out.println("No input data"); }}

D:\>java Average 10 20 30 4025.0

EXAMPLE

Page 29: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

29

EXERCISE 6

從命令列輸入四個浮點數,求平均值。 Hint:Double.parseDouble(s)

Page 30: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

30

? OPERATOR

The ? is called a ternary operator because it requires three operands.

Syntax form

<exp1> ? <exp2> : <exp3> <exp1> must be a boolean expression.

The result of ? operator depends on the result of <exp1>.

If <exp1> is true, the result is <exp2> ; otherwise, <exp3> . Example

max = (a > b) ? a : b;

Page 31: L EC. 05: S TRINGS 0. 2015 S PRING C ONTENT  Arrays [review]  The For-Each Style for Loop [review]  Strings  Constructing Strings  Operating on Strings

31

class NoZeroDiv2 {

public static void main(String args[]) {

int a = 2;

int b = 5;

int max = -1;

max = (a > b ? a : b );

System.out.println(max);

}

}

2 hr

EXAMPLE

5