课堂例子验证

课堂例子验证:

1.// OtherCharMethods.java

// Demonstrate the non-static methods of class

// Character from the java.lang package.

import javax.swing.*;

public class OtherCharMethods {

   public static void main( String args[] )

   {

      Character c1, c2;

      c1 = new Character( 'A' );

      c2 = new Character( 'a' );

      String output =

         "c1 = " + c1.charValue() +

         " c2 = " + c2.toString() +

         " hash code for c1 = " + c1.hashCode() +

         " hash code for c2 = " + c2.hashCode();

      if (  c1.equals( c2 ) )

         output += " c1 and c2 are equal";

      else

         output += " c1 and c2 are not equal";

      JOptionPane.showMessageDialog( null, output,

         "Demonstrating Non-Static Character Methods",

         JOptionPane.INFORMATION_MESSAGE );

      System.exit( 0 );

   }

}

2.// StaticCharMethods.java

// Demonstrates the static character testing methods

// and case conversion methods of class Character

// from the java.lang package.

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class StaticCharMethods extends JFrame {

   private char c;

   //以下定义几个图形界面组件

   private JLabel prompt;

   private JTextField input;

   private JTextArea outputArea;

   public StaticCharMethods()

   {

    //super代表调用基类JFrame的构造方法,其结果是设置了窗口的标题栏

      super( "Static Character Methods" );

//getContentPane是基类提供的方法,它获取窗体中可存放图形控件的空白区域

//所有的可容纳其它图形控件的区域被称为----"容器",它有一个基类,称为Container

      Container container = getContentPane();

      //设置布局方式为流布局方式:即从左到右地放置控件,一行放不下,就移到下一行

      container.setLayout( new FlowLayout() );

      prompt =

         new JLabel( "Enter a character and press Enter" );

      container.add( prompt );  //将控件加入容器中

      input = new JTextField( 5 );

      //设定文本框对回车键响应

      input.addActionListener(

         new ActionListener() {

          //在下面的函数中定义要干的事

            public void actionPerformed( ActionEvent e )

            {  

               String s = e.getActionCommand();

                              c = s.charAt( 0 );

               buildOutput(); //构造输出结果

            }

         }

      );

      container.add( input );

      outputArea = new JTextArea( 10, 20 );

      container.add( outputArea );

      setSize( 300, 250 );  // set the window size

      show();               // show the window

   }

   public void buildOutput()

   {

      outputArea.setText(

          "is defined: " + Character.isDefined( c ) +

          " is digit: " + Character.isDigit( c ) + //是否数字

          " is Java letter: " +

          Character.isJavaIdentifierStart( c ) + //是否可作为标识符的第一个字符

          " is Java letter or digit: " +

          Character.isJavaIdentifierPart( c ) + //是否可作为标识符的字符

          " is letter: " + Character.isLetter( c ) +

          " is letter or digit: " +

          Character.isLetterOrDigit( c ) +

          " is lower case: " + Character.isLowerCase( c ) +

          " is upper case: " + Character.isUpperCase( c ) +

          " to upper case: " + Character.toUpperCase( c ) +

          " to lower case: " + Character.toLowerCase( c ) );

   }

//程序入口点

   public static void main( String args[] )

   {

      StaticCharMethods application = new StaticCharMethods();

      //只有加上这一句,才能实现单击窗口关闭按钮关闭程序

      application.addWindowListener(

         new WindowAdapter() {

            public void windowClosing( WindowEvent e )

            {

               System.exit( 0 ); //退出系统

            }

         }

      );

   }

}

3.// StringBufferAppend.java

// This program demonstrates the append

// methods of the StringBuffer class.

import javax.swing.*;

public class StringBufferAppend {

   public static void main( String args[] )

   {

      Object o = "hello"; 

      String s = "good bye";  

      char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };

      boolean b = true;

      char c = 'Z';

      int i = 7;

      long l = 10000000;

      float f = 2.5f;

      double d = 33.333;

      StringBuffer buf = new StringBuffer();

      buf.append( o );

      buf.append( "  " );

      buf.append( s );

      buf.append( "  " );

      buf.append( charArray );

      buf.append( "  " );

      buf.append( charArray, 0, 3 );

      buf.append( "  " );

      buf.append( b );

      buf.append( "  " );

      buf.append( c );

      buf.append( "  " );

      buf.append( i );

      buf.append( "  " );

      buf.append( l );

      buf.append( "  " );

      buf.append( f );

      buf.append( "  " );

      buf.append( d );

      JOptionPane.showMessageDialog( null,

         "buf = " + buf.toString(),

         "Demonstrating StringBuffer append Methods",

         JOptionPane.INFORMATION_MESSAGE );

      System.exit( 0 );

   }

}

4.

// StringBufferCapLen.java

// This program demonstrates the length and

// capacity methods of the StringBuffer class.

import javax.swing.*;

public class StringBufferCapLen {

   public static void main( String args[] )

   {

      StringBuffer buf =

         new StringBuffer( "Hello, how are you?" );

      //length:当前字符个数

      //capacity:不另外分配内存可以存放的字符个数

      

      String output = "buf = " + buf.toString() +

                      " length = " + buf.length() +

                      " capacity = " + buf.capacity();

                      

  //ensureCapacity:保证StringBuffer的最小容量

      buf.ensureCapacity( 75 );

      output += " New capacity = " + buf.capacity();

  

  //setLength:增大或减小StringBuffer的长度

      buf.setLength( 10 );

      output += " New length = " + buf.length() +

                " buf = " + buf.toString();

      JOptionPane.showMessageDialog( null, output,

         "StringBuffer length and capacity Methods",

         JOptionPane.INFORMATION_MESSAGE );

      System.exit( 0 );

   }

}

5.

//StringBufferChars.java

// The charAt, setCharAt, getChars, and reverse methods 

// of class StringBuffer.

import javax.swing.*;

public class StringBufferChars {

   public static void main( String args[] )

   {

      StringBuffer buf = new StringBuffer( "hello there" );

      String output = "buf = " + buf.toString() +

                      " Character at 0: " + buf.charAt( 0 ) +

                      " Character at 4: " + buf.charAt( 4 );

      char charArray[] = new char[ buf.length() ];

      buf.getChars( 0, buf.length(), charArray, 0 );

      //(起始下标,长度,字符数组名,起始下标)

      output += " The characters are: ";

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

         output += charArray[ i ];

      buf.setCharAt( 0, 'H' );

      buf.setCharAt( 6, 'T' );

      output += " buf = " + buf.toString();

  //reverse:倒转字串

      buf.reverse();

      output += " buf = " + buf.toString();

      JOptionPane.showMessageDialog( null, output,

         "Demonstrating StringBuffer Character Methods",

         JOptionPane.INFORMATION_MESSAGE );

      System.exit( 0 );

   }

}

6.

// StringBufferConstructors.java

// This program demonstrates the StringBuffer constructors.

import javax.swing.*;

public class StringBufferConstructors {

   public static void main( String args[] )

   {

      StringBuffer buf1, buf2, buf3;

   

      buf1 = new StringBuffer();

      buf2 = new StringBuffer( 10 );

      buf3 = new StringBuffer( "hello" );

      String output =

         "buf1 = " + """ + buf1.toString() + """ +

         " buf2 = " + """ + buf2.toString() + """ +

         " buf3 = " + """ + buf3.toString() + """;

      JOptionPane.showMessageDialog( null, output,

         "Demonstrating StringBuffer Class Constructors",

         JOptionPane.INFORMATION_MESSAGE );

      System.exit( 0 );

   }

}

7.

// StringBufferInsert.java

// This program demonstrates the insert and delete

// methods of class StringBuffer.

import javax.swing.*;

public class StringBufferInsert {

   public static void main( String args[] )

   {

      Object o = "hello";  

      String s = "good bye";  

      char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };

      boolean b = true;

      char c = 'K';

      int i = 7;

      long l = 10000000;

      float f = 2.5f;

      double d = 33.333;

      StringBuffer buf = new StringBuffer();

      buf.insert( 0, o );

      buf.insert( 0, "  " );

      buf.insert( 0, s );

      buf.insert( 0, "  " );

      buf.insert( 0, charArray );

      buf.insert( 0, "  " );

      buf.insert( 0, b );

      buf.insert( 0, "  " );

      buf.insert( 0, c );

      buf.insert( 0, "  " );

      buf.insert( 0, i );

      buf.insert( 0, "  " );

      buf.insert( 0, l );

      buf.insert( 0, "  " );

      buf.insert( 0, f );

      buf.insert( 0, "  " );

      buf.insert( 0, d );

      String output = "buf after inserts: " + buf.toString();

      buf.deleteCharAt( 10 );     // delete 5 in 2.5

      buf.delete( 2, 6 );         // delete .333 in 33.333

      output += " buf after deletes: " + buf.toString();

      JOptionPane.showMessageDialog( null, output,

         "Demonstrating StringBufferer Inserts and Deletes",

         JOptionPane.INFORMATION_MESSAGE );

      System.exit( 0 );

   }

}

8.

//  StringCompare

// This program demonstrates the methods equals, 

// equalsIgnoreCase, compareTo, and regionMatches 

// of the String class.

import javax.swing.JOptionPane;

public class StringCompare {

   public static void main( String args[] )

   {

      String s1, s2, s3, s4, output;

      s1 = new String( "hello" );

      s2 = new String( "good bye" );

      s3 = new String( "Happy Birthday" );

      s4 = new String( "happy birthday" );

      output = "s1 = " + s1 + " s2 = " + s2 +

               " s3 = " + s3 + " s4 = " + s4 + " ";

      //test for equality

      //equals用于比较两对象的内容是否相等.

      //自定义对象时需要重载此方法

      if ( s1.equals( "hello" ) )

         output += "s1 equals "hello" ";

      else

         output += "s1 does not equal "hello" "; 

      // test for equality with ==

      //比对引用.只有两个引用指向同一个对象,则结果为true

      if ( s1 == "hello" )

         output += "s1 == "hello" ";

      else

         output += "s1 does not == "hello" ";

      // test for equality--ignore case

      if ( s3.equalsIgnoreCase( s4 ) )

         output += "s3 equals s4 ";

      else

         output += "s3 does not equal s4 ";

      // test compareTo

      //使用字典法进行比较,返回0表两字串相等,小于返回负值,大于返回正值

      output +=

         " s1.compareTo( s2 ) is " + s1.compareTo( s2 ) +

         " s2.compareTo( s1 ) is " + s2.compareTo( s1 ) +

         " s1.compareTo( s1 ) is " + s1.compareTo( s1 ) +

         " s3.compareTo( s4 ) is " + s3.compareTo( s4 ) +

         " s4.compareTo( s3 ) is " + s4.compareTo( s3 ) +

         " ";

      // test regionMatches (case sensitive)

      //比较两字串中的某一部分是否相等

      //参数含义如下:

      //1.调用这个方法的字串中的起始下标

      //2.要比较的字串

      //3.要比较的字串的起始下标

      //4.要比较的字串比较的字符长度

      if ( s3.regionMatches( 0, s4, 0, 5 ) )

         output += "First 5 characters of s3 and s4 match ";

      else

         output +=

            "First 5 characters of s3 and s4 do not match ";

      // test regionMatches (ignore case)

      

      if ( s3.regionMatches( true, 0, s4, 0, 5 ) )

         output += "First 5 characters of s3 and s4 match";

      else

         output +=

            "First 5 characters of s3 and s4 do not match";

      JOptionPane.showMessageDialog( null, output,

         "Demonstrating String Class Constructors",

         JOptionPane.INFORMATION_MESSAGE );

      System.exit( 0 );

   }

}

/**************************************************************************

 * (C) Copyright 1999 by Deitel & Associates, Inc. and Prentice Hall.     *

 * All Rights Reserved.                                                   *

 *                                                                        *

 * DISCLAIMER: The authors and publisher of this book have used their     *

 * best efforts in preparing the book. These efforts include the          *

 * development, research, and testing of the theories and programs        *

 * to determine their effectiveness. The authors and publisher make       *

 * no warranty of any kind, expressed or implied, with regard to these    *

 * programs or to the documentation contained in these books. The authors *

 * and publisher shall not be liable in any event for incidental or       *

 * consequential damages in connection with, or arising out of, the       *

 * furnishing, performance, or use of these programs.                     *

 *************************************************************************/

9.

// StringConcat.java

// This program demonstrates the String class concat method.

// Note that the concat method returns a new String object. It

// does not modify the object that invoked the concat method.

import javax.swing.*;

public class StringConcat {

   public static void main( String args[] )

   {

      String s1 = new String( "Happy " ),

             s2 = new String( "Birthday" ),

             output;

      output = "s1 = " + s1 +

               " s2 = " + s2;

      output += " Result of s1.concat( s2 ) = " +

                s1.concat( s2 );

      output += " s1 after concatenation = " + s1;

      JOptionPane.showMessageDialog( null, output,

         "Demonstrating String Method concat",

         JOptionPane.INFORMATION_MESSAGE );

      System.exit( 0 );

   }

}

10.

// StringConstructors.java

// This program demonstrates the String class constructors.

import javax.swing.*;

public class StringConstructors {

   public static void main( String args[] )

   {

      char charArray[] = { 'b', 'i', 'r', 't', 'h', ' ',

                           'd', 'a', 'y' };

      byte byteArray[] = { (byte) 'n', (byte) 'e', (byte) 'w',

                           (byte) ' ', (byte) 'y', (byte) 'e',

                           (byte) 'a', (byte) 'r' };

      StringBuffer buffer;

      String s, s1, s2, s3, s4, s5, s6, s7, output;

      s = new String( "hello" );

      buffer = //分配缓冲区

         new StringBuffer( "Welcome to Java Programming!" );

      // use the String constructors

      s1 = new String(); //缺省构造函数

      s2 = new String( s ); //拷贝构造函数

      s3 = new String( charArray ); //以字符数组初始化字串

      s4 = new String( charArray, 6, 3 ); //从字符数组第6个元素起取3个字符

      s5 = new String( byteArray, 4, 4 ); //从字节数组第4个元素起取4个字节

      s6 = new String( byteArray );

      s7 = new String( buffer ); //从缓冲区中提取字符创建字串,注意,是复制

      output = "s1 = " + s1 +

               " s2 = " + s2 +

               " s3 = " + s3 +

               " s4 = " + s4 +

               " s5 = " + s5 +

               " s6 = " + s6 +

               " s7 = " + s7;

      JOptionPane.showMessageDialog( null, output,

         "Demonstrating String Class Constructors",

         JOptionPane.INFORMATION_MESSAGE );

      System.exit( 0 );

   }

}

11.

public class StringEquals {

    

/**

     * @param args the command line arguments

     */

    

public static void main(String[] args) {

        

String s1=new String("Hello");

        

String s2=new String("Hello");

        

System.out.println(s1==s2);

        

System.out.println(s1.equals(s2));

        

String s3="Hello";

        

String s4="Hello";

          

System.out.println(s3==s4);

        

System.out.println(s3.equals(s4));

        

    

}

}

12.

// StringHashCode.java

// This program demonstrates the method 

// hashCode of the String class.

import javax.swing.*;

public class StringHashCode {

   public static void main( String args[] )

   {

      String s1 = "hello",

             s2 = "Hello";

      String output =

         "The hash code for "" + s1 + "" is " +

         s1.hashCode() + 

         " The hash code for "" + s2 + "" is " +

         s2.hashCode();

      JOptionPane.showMessageDialog( null, output,

         "Demonstrating String Method hashCode",

         JOptionPane.INFORMATION_MESSAGE );

      System.exit( 0 );

   }

}

13.

//StringIndexMethods.java

// This program demonstrates the String 

// class index methods.

import javax.swing.*;

public class StringIndexMethods {

   public static void main( String args[] )

   {

      String letters = "abcdefghijklmabcdefghijklm";

      String output;

      // test indexOf to locate a character in a string

      output = "'c' is located at index " +

               letters.indexOf( 'c' );

      output += " 'a' is located at index " +

                letters.indexOf( 'a', 1 ); //2个参数是开始查找的起始下标

      output += " '$' is located at index " +

                letters.indexOf( '$' );

      // test lastIndexOf to find a character in a string

      output += " Last 'c' is located at index " +

                letters.lastIndexOf( 'c' );

      output += " Last 'a' is located at index " +

                letters.lastIndexOf( 'a', 25 );

      output += " Last '$' is located at index " +

                letters.lastIndexOf( '$' );

      // test indexOf to locate a substring in a string

      output += " "def" is located at index " +

                letters.indexOf( "def" );

      output += " "def" is located at index " +

                letters.indexOf( "def", 7 );

      output += " "hello" is located at index " +

                letters.indexOf( "hello" );

      // test lastIndexOf to find a substring in a string

      output += " Last "def" is located at index " +

                letters.lastIndexOf( "def" );

      output += " Last "def" is located at index " +

                letters.lastIndexOf( "def", 25 );

      output += " Last "hello" is located at index " +

                letters.lastIndexOf( "hello" );

      JOptionPane.showMessageDialog( null, output,

         "Demonstrating String Class "index" Methods",

         JOptionPane.INFORMATION_MESSAGE );

      System.exit( 0 );

   }

}

14.

//StringMisc.java

// This program demonstrates the length, charAt and getChars

// methods of the String class.

//

// Note: Method getChars requires a starting point

// and ending point in the String. The starting point is the

// actual subscript from which copying starts. The ending point

// is one past the subscript at which the copying ends.

import javax.swing.*;

public class StringMisc {

   public static void main( String args[] )

   {

      String s1, output;

      char charArray[];

      s1 = new String( "hello there" );

      charArray = new char[ 5 ];

      // output the string

      output = "s1: " + s1;

      // test the length method

      output += " Length of s1: " + s1.length();

      // loop through the characters in s1 and display reversed

      output += " The string reversed is: ";

      for ( int i = s1.length() - 1; i >= 0; i-- )

         output += s1.charAt( i ) + " ";

      // copy characters from string into char array

      //四个参数的含义

      //1.被拷贝字符在字串中的起始位置

      //2.被拷贝的最后一个字符在字串中的下标再加1

      //3.目标字符数组

      //4.拷贝的字符放在字符数组中的起始下标

      s1.getChars( 0, 5, charArray, 0 );

      output += " The character array is: ";

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

         output += charArray[ i ];

      JOptionPane.showMessageDialog( null, output,

         "Demonstrating String Class Constructors",

         JOptionPane.INFORMATION_MESSAGE );

      System.exit( 0 );

   }

}

15.

public class StringPool {

    

public static void main(String args[])

    {

        

String s0="Hello";

        

String s1="Hello";

        

String s2="He"+"llo";

        

System.out.println(s0==s1);//true

        

System.out.println(s0==s2);//true

        

System.out.println(new String("Hello")==new String("Hello"));//false

    

}

}

16.

// StringStartEnd.java

// This program demonstrates the methods startsWith and

// endsWith of the String class.

import javax.swing.*;

public class StringStartEnd {

   public static void main( String args[] )

   {

      String strings[] = { "started", "starting", 

                           "ended", "ending" };

      String output = "";

      // Test method startsWith

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

         if ( strings[ i ].startsWith( "st" ) )

            output += """ + strings[ i ] +

                      "" starts with "st" ";

      output += " ";

      // Test method startsWith starting from position

      // 2 of the string

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

         if ( strings[ i ].startsWith( "art", 2 ) ) 

            output += 

               """ + strings[ i ] +

               "" starts with "art" at position 2 ";

      output += " ";

      // Test method endsWith

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

         if ( strings[ i ].endsWith( "ed" ) )

            output += """ + strings[ i ] +

                      "" ends with "ed" ";

      JOptionPane.showMessageDialog( null, output,

         "Demonstrating String Class Comparisons",

         JOptionPane.INFORMATION_MESSAGE );

      System.exit( 0 );

   }

}

17.

// StringValueOf.java

// This program demonstrates the String class valueOf methods.

import javax.swing.*;

public class StringValueOf {

   public static void main( String args[] )

   {

      char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' };

      boolean b = true;

      char c = 'Z';

      int i = 7;

      long l = 10000000;

      float f = 2.5f;

      double d = 33.333;

      Object o = "hello";  // Assign to an Object reference

      String output;

      output = "char array = " + String.valueOf( charArray ) +

               " part of char array = " +

               String.valueOf( charArray, 3, 3 ) +

               " boolean = " + String.valueOf( b ) +

               " char = " + String.valueOf( c ) +

               " int = " + String.valueOf( i ) +

               " long = " + String.valueOf( l ) + 

               " float = " + String.valueOf( f ) + 

               " double = " + String.valueOf( d ) + 

               " Object = " + String.valueOf( o );

      JOptionPane.showMessageDialog( null, output,

         "Demonstrating String Class valueOf Methods",

         JOptionPane.INFORMATION_MESSAGE );

      System.exit( 0 );

   }

}

18.

// SubString.java

// This program demonstrates the

// String class substring methods.

import javax.swing.*;

public class SubString {

   public static void main( String args[] )

   {

      String letters = "abcdefghijklmabcdefghijklm";

      String output;

      // test substring methods

      output = "Substring from index 20 to end is " +

               """ + letters.substring( 20 ) + "" ";

      output += "Substring from index 0 up to 6 is " +

                """ + letters.substring( 0, 6 ) + """;

                //(起始下标,要拷贝子串的最后下标加1但不包括该下标)

      JOptionPane.showMessageDialog( null, output,

         "Demonstrating String Class Substring Methods",

         JOptionPane.INFORMATION_MESSAGE );

      System.exit( 0 );

   }

}

19.

public class Test {

/**

 * @param args

 */

public static void main(String[] args) {

String aString="abc";

String bString="abc";

bString=new String("abc");

System.out.println(aString==bString);

bString += "def";

System.out.println(bString);

}

}

20.

// TokenTest.java

// Testing the StringTokenizer class of the java.util package

import javax.swing.*;

import java.util.*;

import java.awt.*;

import java.awt.event.*;

public class TokenTest extends JFrame {

   private JLabel prompt;

   private JTextField input;

   private JTextArea output;

   public TokenTest()

   {

      super( "Testing Class StringTokenizer" );

      Container c = getContentPane();

      c.setLayout( new FlowLayout() );

      prompt =

         new JLabel( "Enter a sentence and press Enter" );

      c.add( prompt );

      input = new JTextField( 20 );

      input.addActionListener(

         new ActionListener() {

            public void actionPerformed( ActionEvent e )

            {      

               //获取用户输入的字串

               String stringToTokenize = e.getActionCommand();

               StringTokenizer tokens =

                  new StringTokenizer( stringToTokenize );

//使用缺省构造函数,定界符为:空格,换行符,TAB

               output.setText( "Number of elements: " +

                  tokens.countTokens() +

                  " The tokens are: " );

               while ( tokens.hasMoreTokens() )

                  output.append( tokens.nextToken() + " " );

            }

         }

      );

      c.add( input );

      output = new JTextArea( 10, 20 );

      output.setEditable( false );

      c.add( new JScrollPane( output ) );

      setSize( 275, 260 );  // set the window size

      show();               // show the window

   }

   public static void main( String args[] )

   {

      TokenTest app = new TokenTest();

      app.addWindowListener(

         new WindowAdapter() {

            public void windowClosing( WindowEvent e )

            {

               System.exit( 0 );

            }

         }

      );

   }

}

原文地址:https://www.cnblogs.com/Jasoon/p/4931697.html