l ec. 05: s trings 0. 2015 s pring c ontent arrays [review] the for-each style for loop [review] ...

Post on 18-Jan-2016

214 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

1

LEC. 05: 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

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);

}

}無擴充性

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.

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

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

7

EXERCISE 1B

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

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

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>.

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

11

EXERCISE 1C

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

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")

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.

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 號櫃子

15

COMMONLY USED String SERVICES

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

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

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

19

EXERCISE 4

Print a string reversely.

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

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.

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];

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

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

25

EXERCISE 5

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

String command;

Scanner scn = new Scanner(System.in);

command = scn.next();

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 .

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

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

29

EXERCISE 6

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

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;

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

top related