Chapter 3 Fundamental Programming Structures in Java

1. A simple Java Program

2. Comments

3. Data Types

4. Variables

5. Operators

6. String

7. Input and Output

8. Control Flow

9. Big Numbers

10. Arrays

 

1. A simple Java Program

1 public class Simple_Java{
2     public static void main(String[] args){
3         System.out.println("Hello World!");
4     }
5 } 

  Java is case sensitive(区分大小写的).If you made any mistake in capitalization(such as typing Main instead of main), the program will not run.

  The keyword public is called an access modifier(访问控制修饰符). these modifiers control the level of access other parts of program have to this code

  The keyword class reminds you that everything in a Java program lives inside a class.

  Following the keyword class is the name of the class.

  You need to make the file name for the source code the same as the name of the public class, with the extension .java appended.

  We are using the System.out object and calling its println method. Java uses the general syntax: Object.method(parameters)

  when you compile this source code, you end up with a file containing the bytecodes for this class. The Java compiler automatically name

the bytecode file Simple_Java.class and stores it in the same directory as the source file. Finally, launch the program by issuing the following command:

  java FirstSample

  To run a compiled program, the Java virtual machine always starts execution with the code in the main method in the class you indicate.

 

2. Comments

 

3. Data Types

  In Java, you use the keyword final to denote a constant.

  'A' is a char Type with value 65.It is differnet from "A", aString containing a single character.

  Java strings are sequences(序列) of Unicode characters.

  3.1 Substrings

    You can extract a substring from a larger string with the substring method of the String class.

     1 1 String greeting = "Hello"; 2 String s = greeting.Substring(0,3); 

    creates s string consisting of the characters "Hel"

  3.2 Concatenation

     1 System.out.println("The answer is" + answer); 

    use + to join(concatenate) two strings.

  3.3 Testing Strings for Equality

    to testc equal, use the equals method.

     1 s.equals(t); 

    to test whether two strings are idential(同一的) except for the upper/lowercase letter distinction, use the equalsIgnoreCase method

     1 "Hello".equalsIgnoreCase("hello"); 

    Attention !     

1  String greeting = "Hello"; //initialize greeting to a string
2  if (greeting == "Hello") . . .
3    // probably true
4  if (greeting.substrin(0,3) = "Hel" ...
5    // probably false

    If the virtual machine always arranges for equal strings to be shared, then you could use the == operator for testing equality. But only string

constants are shared, not strings that are the result of operations like + or substring. Therefore, never use == to compare strings lest you end up with a

program with the worst kind of bug—an intermittent one that seems to occur randomly.

    3.4 Empty and Null Strings

    The empty string "" is a string of length 0. You can test whether a string is empty by calling

     1 if(str.length() == 0 ) 2 if(str.equals("")) 

    3.5 Code Points and Code Units

    Java strings are implements as sequences of char values.

    the char data type is a code unit for representing Unicode code points in the UTF-16 encoding. 

    The length method yields the number of code units required for a given string in the UTF-16 encoding.

     1 String greeting = "Hello"; 2 int n = greeting.length(); 

    The call s.charAt(n) returns the code unit at position n,where n is between 0 and s.lenght()-1.   

     1 char first = greeting.charAt(0); // first is 'H' 

    to get at i th(第i个) code point , use the statement

     1 int index = greeting.offsetByCodePoints(0,i); 2 int cp = greeting.codePointAt(index); 

    3.6 string API(Application Programming Interface)   

char charAt(int index)
returns the code unit at the specified location. You probably don’t want to call this
method unless you are interested in low-level code units.
• int codePointAt(int index) 5.0
returns the code point that starts or ends at the specified location.
• int offsetByCodePoints(int startIndex, int cpCount) 5.0
returns the index of the code point that is cpCount code points away from the code
point at startIndex.
• int compareTo(String other)
returns a negative value if the string comes before other in dictionary order, a
positive value if the string comes after other in dictionary order, or 0 if the strings
are equal.
• boolean endsWith(String suffix)
returns true if the string ends with suffix.
• boolean equals(Object other)
returns true if the string equals other.
• boolean equalsIgnoreCase(String other)
returns true if the string equals other, except for upper/lowercase distinction.
• int indexOf(String str)
• int indexOf(String str, int fromIndex)
• int indexOf(int cp)
• int indexOf(int cp, int fromIndex)
returns the start of the first substring equal to the string str or the code point cp,
starting at index 0 or at fromIndex, or -1 if str does not occur in this string.
• int lastIndexOf(String str)
• int lastIndexOf(String str, int fromIndex)
• int lastindexOf(int cp)
• int lastindexOf(int cp, int fromIndex)
returns the start of the last substring equal to the string str or the code point cp,
starting at the end of the string or at fromIndex.
• int length()
returns the length of the string.
• int codePointCount(int startIndex, int endIndex) 5.0
returns the number of code points between startIndex and endIndex - 1. Unpaired
surrogates are counted as code points.
• String replace(CharSequence oldString, CharSequence newString)
returns a new string that is obtained by replacing all substrings matching oldString
in the string with the string newString. You can supply String or StringBuilder
objects for the CharSequence parameters.
• boolean startsWith(String prefix)
returns true if the string begins with prefix.
• String substring(int beginIndex)
• String substring(int beginIndex, int endIndex)
returns a new string consisting of all code units from beginIndex until the end of the
string or until endIndex - 1.
• String toLowerCase()
returns a new string containing all characters in the original string, with uppercase
characters converted to lowercase.
• String toUpperCase()
returns a new string containing all characters in the original string, with lowercase
characters converted to uppercase.
• String trim()
returns a new string by eliminating all leading and trailing spaces in the original
string.

    3.7 Building Strings

    Occasionally, you need to build up strings from shorter strings, such as keystrokes(按键) or words from a file. It would be inefficient(无效率) to use

string concatenation for this purpose. Every time you concatenate strings, a new String object is constructed. This is time-consuming and wastes memory.

Using the StringBuilder class avoids this problem.

    Follow these steps to build a string from many small pieces. First, construct an empty string builder:

     StringBuilder builder = new StringBuilder(); 

    Each time you need to add another part , call the append method 

     builder.append(ch); // appends a single character

     builder.append(str); // appends a string  

    When you are done building the string, call the toString method. You will get a String object with the character sequence contained in the builder. 

     String completedString = builder.toString();     

    3.8 StringBuffer

    StringBuffer, is slightly less efficient, but it allows multiple threads to add or remove characters. If all string editing happens in a single thread

(which is usually the case), you should use StringBuilder instead.   

    3.9 StringBuilder APIs  

• StringBuilder()
constructs an empty string builder.
• int length()
returns the number of code units of the builder or buffer.
• StringBuilder append(String str)
appends a string and returns this.
• StringBuilder append(char c)
appends a code unit and returns this.
• StringBuilder appendCodePoint(int cp)
appends a code point, converting it into one or two code units, and returns this.
• void setCharAt(int i, char c)
sets the ith code unit to c.
• StringBuilder insert(int offset, String str)
inserts a string at position offset and returns this.
• StringBuilder insert(int offset, char c)
inserts a code unit at position offset and returns this.
• StringBuilder delete(int startIndex, int endIndex)
deletes the code units with offsets startIndex to endIndex - 1 and returns this.
• String toString()
returns a string with the same data as the builder or buffer contents.

     

7. Input and Output

   7.1 Reading Input

    To read console input, you first construct a Scanner that is attached to System.in

     Scanner in = new Scanner(System.in); 

    Now you can use the various methods of the Scanner class to read input

     System.out.println("What is your name ?");

     String name = in.nextLine();  

    We use the nextLine method because the input might contain spaces

    Finally, note the line

     import java.util.*; 

     The Scanner class is not suitable for reading a password from a console since the input is plainly visible to anyone. Java SE 6 introduces a Console class for this purpose.

1 Console cons = System.console();
2 String username = cons.readLine("User name:");
3 char[] password = cons.readPassword("Password:");

    7.2 File Input and Output

    To read from a file , construct a Scanner object like this:

     Scanner in = new Scanner(Paths.get("myfile.txt")); 

    To write to a file, Construct a PrintWriter object.In the constructor, simply supply the file name:

     PrintWrite out = new PrintWriter("myfile.txt"); 

    As you just saw, you can access files just as easily as you can use System.in and System.out. There is just one catch: If you construct a

Scanner with a file that does not exist or a PrintWriter with a file name that cannot be created, an exception occurs. The Java compiler considers these

exceptions to be more serious than a “divide by zero” exception, You do this by tagging the main method with a throws clause, like this: 

public static void main(String[] args) throws Exception
{
      Scanner in = new Scanner(Paths.get("myfile.txt"));  
}

    Example: 

               

 1 import java.util.*;
 2 import java.nio.file.*;  //Paths所在包
 3 
 4 public class file_input{
 5     public static void main(String[] args)  {
 6         try{
 7             Scanner in = new Scanner(Paths.get("e:\\Java\\src\\File\\myfile.txt"));
 8             while(in.hasNext()){  //判断是否是最后一句
 9                 String word = in.nextLine();  //读取下一句
10                 System.out.println(word); 
11             }
12             
13         }
14         catch(Exception e){
15             System.out.println(e);
16         }        
17         finally{
18             System.out.println("Read Finished!");
19         }
20     }
21 }

        

 

8. Control Flow

9. Big Numbers

10. Arrays

  An array is a data structure that stores a collection of values of the same type. You access each individual value through an integer index. For

example, if a is an array of integers, then a[i] is the ith integer in the array.

  Define an array variables either as 

   int[] a; 

  or as

   int a[]; 

  To find the number of elements of an array, use  array.length.

  Once you create an array, you cannot change its size!!!

  10.1 The "for each" Loop

    for (variable :  collection) statement sets the given variable to each element of the collection and then executes the statement

    The collection expression must be an array or an object of a class that implements the Iterable interface, such as ArrayList.

     for(int element: a)   System.out.println(element); 

    Prints each element of the array a on a separate line.

    There is an even easier way to print all values of an array, using the toString method of the Arrays class. The call Arrays.toString(a) returns a

string containing the array elements, enclosed in brackets and separated by commas, such as "[2, 3, 5, 7, 11, 13]". To print the array, simply call

     Systems.out.println(Arrays.toString(a)); 

  10.2 Command-Line Parameters

  Every Java program has a main method with a String[] args parameter. This parameter indicates that the main method receives an array of strings

—namely, the arguments specified on the command line.

  10.3 Multidimensional Arrays

  To visit all elements of a two-dimensional array a, nest two loops, like this

   for (double[] row : a )     for (double value : row )     do something with value 

  To print out a quick-and-dirty list of the elements of a two-dimensional array, call

    System.out.println(Arrays.deepToString(a));  

  

posted @ 2014-09-21 12:49  Mirrorhanman  阅读(301)  评论(0编辑  收藏  举报