Java Java Connect.java

import java.sql.*;

   public class Connect
   {
       public static void main (String[] args)
       {
           Connection conn = null;
			   String userName = "Username";
               String password = "Password";
               String url = "jdbc:mysql://192.168.1.121/drupal?user=" + userName + "&password=" + password;
			   System.out.println(url);
           try
           {
               
               Class.forName ("com.mysql.jdbc.Driver").newInstance ();
               conn = DriverManager.getConnection (url);
               System.out.println ("Database connection established");
           }
           catch (Exception e)
           {
               System.err.println ("Cannot connect to database server");
           }
           finally
           {
               if (conn != null)
               {
                   try
                   {
                       conn.close ();
                       System.out.println ("Database connection terminated");
                   }
                   catch (Exception e) { /* ignore close errors */ }
               }
           }
       }
   }

Java android动画slidingown slideup

public void setLayoutAnim_slidedown(ViewGroup panel, Context ctx) {

		AnimationSet set = new AnimationSet(true);

		Animation animation = new TranslateAnimation(
				Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
				0.0f, Animation.RELATIVE_TO_SELF, -1.0f,
				Animation.RELATIVE_TO_SELF, 0.0f);
		animation.setDuration(800);
		animation.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
				// TODO Auto-generated method stub
				// MapContacts.this.mapviewgroup.setVisibility(View.VISIBLE);

			}

			@Override
			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationEnd(Animation animation) {

				// TODO Auto-generated method stub

			}
		});
		set.addAnimation(animation);

		LayoutAnimationController controller = new LayoutAnimationController(
				set, 0.25f);
		panel.setLayoutAnimation(controller);

	}

	public void setLayoutAnim_slideup(ViewGroup panel, Context ctx) {

		AnimationSet set = new AnimationSet(true);

		/*
		 * Animation animation = new AlphaAnimation(1.0f, 0.0f);
		 * animation.setDuration(200); set.addAnimation(animation);
		 */

		Animation animation = new TranslateAnimation(
				Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
				0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
				Animation.RELATIVE_TO_SELF, -1.0f);
		animation.setDuration(800);
		animation.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationEnd(Animation animation) {
				// MapContacts.this.mapviewgroup.setVisibility(View.INVISIBLE);
				// TODO Auto-generated method stub

			}
		});
		set.addAnimation(animation);

		LayoutAnimationController controller = new LayoutAnimationController(
				set, 0.25f);
		panel.setLayoutAnimation(controller);

	}

Java 通过FQL获取FB用户数据

<div id="fb-root"></div> 
  <script src="http://connect.facebook.net/en_US/all.js"></script> 
  <script type="text/javascript"> 
    FB.init({appId : '150545208302203', status : true, cookie : true});
    $(document).ready(function() {
  	  $('#facebook').bind('click', function() {
  			FB.login(function(login_response){
  				FB.api(
  				  {
  				    method: 'fql.query',
  				    query: 'SELECT first_name, last_name, sex, pic_big, birthday_date, email FROM user WHERE uid = ' + FB.getSession().uid
  				  },
  				  function(response) {
  		        var user = response[0];
  			      document.getElementById('UserFbId').value = FB.getSession().uid;
  			      document.getElementById('UserEmail').value = user.email;
  		        if(user.birthday_date != null) {
  		          user.birthday_date = user.birthday_date.split("/");
  		          if(user.birthday_date.length > 0) document.getElementById('UserDobMonth').value = user.birthday_date[0];
    			      if(user.birthday_date.length > 1) document.getElementById('UserDobDay').value = user.birthday_date[1];
    			      if(user.birthday_date.length > 2) document.getElementById('UserDobYear').value = user.birthday_date[2];
  			      }
  			      document.getElementById('UserName').value = user.first_name + ' ' + user.last_name;
  			      document.getElementById('UserFbThumbnail').value = user.pic_big;
  			      if(user.sex == 'male') {
  				      document.getElementById('UserGender').value = 'M';
  			      }
  			      else if(user.sex == 'female') {
  			        document.getElementById('UserGender').value = 'F';
  			      }
  			      document.getElementById('UserAddForm').submit();
  				  }
  				);
  			}, {perms:'publish_stream,email,user_birthday'});
    	});
  	});
  </script>

Java 使用JavaMail API和IMAP从Gmail解析数据

import java.util.List;
import java.util.Properties;
import java.util.Date;
import java.util.Locale;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import javax.mail.Session;
import javax.mail.MessagingException;
import javax.mail.Store;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.NoSuchProviderException;
import javax.mail.Address;
import javax.mail.internet.MimeMessage;
import java.text.SimpleDateFormat;

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

      String host = "imap.gmail.com";
      String username = "myusername";
      String password = "mypassword";

      SimpleDateFormat myFormatter = new SimpleDateFormat( "yyyy-MM-dd", Locale.US );

      Properties props = System.getProperties();
      props.setProperty( "mail.store.protocol", "imaps" );

      BufferedWriter myWriter = null;
      try {
          myWriter = new BufferedWriter( new FileWriter( "/home/diggler/Desktop/groovy_testing/BigBendHotSprings/BBHSHelpers.csv" ) );
          myWriter.write( "\"Sent Date\",\"Subject\",\"From\",\"E-Mail\",\"Phone Number\",\"Skills & Interests\",\"Comments\"\n" );
      }
      catch ( IOException myIOE ) {
          myIOE.printStackTrace();
      }

      try {

        Session mySession = Session.getDefaultInstance( props, null );
        Store myStore = mySession.getStore("imaps");
        myStore.connect( host, username, password );

        System.out.println( myStore );

        Folder inbox = myStore.getFolder("BBHS Helpers");
        inbox.open(Folder.READ_ONLY);
        Message messages[] = inbox.getMessages();
        System.out.println( messages.length );

        for ( Message message:messages ) {
            Address addys[] = message.getReplyTo();
            for ( Address addy:addys ) {
                //System.out.println( addy.toString() );
              if (  addy.toString().trim().equals( "alchemiculture <alchemiculture@culligan.dreamhost.com>" ) ) {
                 if ( message.getSubject().startsWith( "BigBendHotSprings.org Message from" ) ) {
                     String messageSubject =  message.getSubject();
                     String sentDate = myFormatter.format( message.getSentDate() );
                     MimeMessage myMimeMessage = (MimeMessage) message;
                   try {
                       // System.out.println( messageSubject );
                       // System.out.println( sentDate );
                      String messageContent = (String) myMimeMessage.getContent();
                      String messageContentLines[] = messageContent.split("\n");
                      String from = "";
                      String eMail = "";
                      String phoneNumber = "";
                      for ( String line:messageContentLines ) {
                         if ( line.startsWith( "From:" ) ) {
                            from = line.split(":")[1].trim();
                         }
                         if ( line.startsWith( "Email:" ) ) {
                            eMail = line.split(":")[1].trim();
                         }
                         if ( line.startsWith( "Phone:" ) ) {
                            phoneNumber = line.split(":")[1].trim();
                         }
                      }
                      String messageContentSplits[] = messageContent.split("Skills and Interests:");
                      String messageContentSplitsII[] = messageContentSplits[1].split("Comments:");
                      String skillsAndInterests = messageContentSplitsII[0].trim();
                      skillsAndInterests = skillsAndInterests.replaceAll( "\n", "" );
                      skillsAndInterests = skillsAndInterests.replaceAll( "\"", "" );
                      skillsAndInterests = skillsAndInterests.replaceAll( ",", "" );
                      String comments = messageContentSplitsII[1].trim();
                      comments = comments.replaceAll( "\n", "" );
                      comments = comments.replaceAll( "\"", "" );
                      comments = comments.replaceAll( ",", "" );

                      // System.out.println( skillsAndInterests );
                      // System.out.println( comments );

                      myWriter.write( "\"" + sentDate + "\",\"" + messageSubject + "\",\"" + from + "\",\"" + eMail + "\",\"" + phoneNumber + "\",\"" + s\
killsAndInterests + "\",\"" + comments + "\"\n" );

                   }
                   catch ( IOException myIOE ) {
                       myIOE.printStackTrace();
                   }
                 }
              }
            }
        }

      }
      catch ( NoSuchProviderException e ) {
e.printStackTrace();
      }
      catch ( MessagingException e ) {
          e.printStackTrace();
      }

      try {
          myWriter.close();
      }
      catch ( IOException myIOE ) {
          myIOE.printStackTrace();
      }

   }
}

Java 使用getText

<input type="HIDDEN" name="pname"
           value="<s:property value='%{getText(\'userDirectoryAddressParameterName\')}'/>">

Java Android获取IP地址

public String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return null;
}

Java cisp401 MyString.java

import java.util.ArrayList;

public class MyString{
	
	// ########## Data Objects ########## (
		private char[] theString, result;
//  )
	// ########## Constructors ########## (
		public MyString(){ // default
			theString = new char[] {'x'};
			result = new char[] {'x'};
		}
		public MyString(String s){ // parameterized
			theString = s.toCharArray();
			result = new char[] {'x'};
		}
		public MyString(char[] s){ // parameterized
			int length = s.length;
			theString = new char[length];
			for(int i=0; i<length; i++){
				theString[i] = s[i];
			}
			result = new char[] {'x'};
		}
		public MyString(MyString s){ // copy
			theString = s.contents();
			result = new char[] {'x'};
		}
//	)
	// ########## Accessors ########## (
		private char[] contents(){
			char[] s = theString;
			return s;
		}
		public int length(){
			return theString.length;
		}
		public String result(){
			return new String(result);
		}
		public String toString(){
			return new String(theString);
		}
		public char get(int n){
			return theString[n];
		}
//  )
	// ########## Mutators ########## (
		public MyString left(int n){
			int stringLength = theString.length;
			result = new char[n];
			if(n > stringLength){ 				// If the space is bigger than the string...
				for(int i=0; i<stringLength; i++){
					result[i] = theString[i];
				}
				for(int j=stringLength; j<n; j++){
					result[j] = ' ';
				}
			}
			if(n <= stringLength){ 				// If the space is the same size as the string or smaller...
				for(int i=0; i<n; i++){
					result[i] = theString[i];
				}
			}
			return new MyString(result);
		}
		public MyString right(int n){
			int stringLength = theString.length;
			int emptySpace = n - stringLength;
			result = new char[n];
			if(n > stringLength){ 				// If the space is bigger than the string...
				for(int j=0; j<emptySpace; j++){
					result[j] = ' ';
				}
				int count = 0;
				for(int i=emptySpace; i<n; i++){
					result[i] = theString[count];
					count++;
				}
			}
			if(n <= stringLength){ 				// If the space is the same size as the string or smaller...
				for(int j=0; j<n; j++){
					result[j] = theString[j];
				}
			}
			return new MyString(result);
		}
		public MyString mid(int n){
			int stringLength = theString.length;
			int emptySpace = n - stringLength;
			int leftPadding=0, rightPadding=0;
			result = new char[n];
			if(n > stringLength){ 				// If the space is bigger than the string...
				if ((emptySpace % 2) == 0){ // If the empty space size is even...
					leftPadding = (emptySpace / 2); // The left padding is equal to the right padding.
					rightPadding = leftPadding;
				}
				if ((emptySpace % 2) == 1){ // If the empty space size is odd...
					rightPadding = (emptySpace / 2) + 1; // The left padding is smaller than the right by 1 space.
					leftPadding = emptySpace / 2;
				}
				for(int i=0; i<leftPadding; i++){
					result[i] = ' ';
				}
				int count = 0;
				for(int j=leftPadding; j<(leftPadding + stringLength); j++){
					result[j] = theString[count];
					count++;
				}
				for(int k=(leftPadding + stringLength); k<n; k++){
					result[k] = ' ';
				}
			}
			if(n <= stringLength){ 				// If the space is the same size as the string or smaller...
				for(int j=0; j<n; j++){
					result[j] = theString[j];
				}
			}
			return new MyString(result);
		}
		public boolean has(String s){ // Determines whether or not a search term exists in our string (true or false).
			char[] searchString = s.toCharArray();
			int searchLength = searchString.length;
			int stringLength = theString.length;
			int foundAt = 0; // Location where a match is found...
			int charMatches = 0; // Counter for matching characters...
			boolean found = false; // To stop the test when a match is found...
			
			for(int i=0; i<stringLength; i++){ // For each letter in our string...
				if (searchLength > stringLength) { // If our search term is bigger than our main string itself...
					break; // Then obviously it will not be found, so prevent the CPU from wasting it's resources on the test...
				}
				if (theString[i] == searchString[0]) { // If a letter in our string matches the first letter of the search term...
					int k=i; // To count starting at our current position without messing up i.
					charMatches = 0; // For reset match count for each test. If not, some terms will not be found...
					for(int j=0; j<searchLength; j++){ // Then for each letter in the search term...
						if (k == stringLength) { // If k is equal to string length (if we have surpassed the boudary of our main string)...
							break; // Then end the for loop or else we get an error during runtime complaining about Array boundaries.
						}
						if (theString[k] == searchString[j]) { // If the letter we're at in our search term matches the corresponding letter in our main string...
							charMatches++; // Then count a character match.
						}
						k++; // Move to the next letter in our base string...
					}
					if (charMatches == searchLength) { // Finally, if the amount of matching letters equals the size of the search term...
						found = true; // Then we've found a matching sequence of characters!
						foundAt = i; // The match is at position i!
					}
				}
				if(found){break;} // We just want to find the first ocurrence for now, so break...
			}
			return found;
		}
		public int firstOcurrenceOf(String s, int n){ // Returns the position at which the search term is first encountered. The search begins at the desired starting point n.
			char[] searchString = s.toCharArray();
			int searchLength = searchString.length;
			int stringLength = theString.length;
			int start = n; // The location in in our string where we begin the search.
			int foundAt = 0; // Location where a match is found...
			int charMatches = 0; // Counter for matching characters...
			boolean found = false; // To stop the test when a match is found...
			
			for(int i=start; i<stringLength; i++){ // For each letter in our string...
				if (searchLength > stringLength || start >= stringLength) { // If our search term is bigger than our main string itself, or the starting point is outside the string's boundaries...
					break; // Then obviously our search term will not be found, so prevent the CPU from wasting it's resources on the test or encountering errors...
				}
				if (theString[i] == searchString[0]) { // If a letter in our string matches the first letter of the search term...
					int k=i; // To count starting at our current position without messing up i.
					charMatches = 0; // For reset match count for each test. If not, some terms will not be found...
					for(int j=0; j<searchLength; j++){ // Then for each letter in the search term...
						if (k == stringLength) { // If k is equal to string length (if we have surpassed the boudary of our main string)...
							break; // Then end the for loop or else we get an error during runtime complaining about Array boundaries.
						}
						if (theString[k] == searchString[j]) { // If the letter we're at in our search term matches the corresponding letter in our main string...
							charMatches++; // Then count a character match.
						}
						k++; // Move to the next letter in our base string...
					}
					if (charMatches == searchLength) { // Finally, if the amount of matching letters equals the size of the search term...
						found = true; // Then we've found a matching sequence of characters!
						foundAt = i; // The match is at position i!
					}
				}
				if(found){break;} // We just want to find the first ocurrence for now, so exit the loop...
			}
			return foundAt;
		}
		public int firstOcurrenceOf(String s){ // This is simply an overloaded version of the previous method so that if you leave off the "n" parameter, it defaults to 0.
			return firstOcurrenceOf(s, 0);
		}
		public int[] findAll(String s){ // Returns an array containing all the locations in our main string where a search term is found to begin.
			char[] searchString = s.toCharArray();
			int searchLength = searchString.length;
			int stringLength = theString.length;
			ArrayList<Integer> locations = new ArrayList<Integer>(); // Locations where a match is found...
			int foundAt[]; // The final array to output containing the locations of the ArrayList above...
			int charMatches = 0; // Counter for matching characters...
			
			boolean found = false; // To stop the test when a match is found...
			
			for(int i=0; i<stringLength; i++){ // For each letter in our string...
				if (searchLength > stringLength) { // If our search term is bigger than our main string itself...
					break; // Then obviously it will not be found, so prevent the CPU from wasting it's resources on the test...
				}
				if (theString[i] == searchString[0]) { // If a letter in our string matches the first letter of the search term...
					int k=i; // To count starting at our current position without messing up i.
					charMatches = 0; // For reset match count for each test. If not, some terms will not be found...
					for(int j=0; j<searchLength; j++){ // Then for each letter in the search term...
						if (k == stringLength) { // If k is equal to string length (if we have surpassed the boudary of our main string)...
							break; // Then end the for loop or else we get an error during runtime complaining about Array boundaries.
						}
						if (theString[k] == searchString[j]) { // If the letter we're at in our search term matches the corresponding letter in our main string...
							charMatches++; // Then count a character match.
						}
						k++; // Move to the next letter in our base string...
					}
					found = false; // Set to false for each test unless we find a matching term...
					if (charMatches == searchLength) { // Finally, if the amount of matching letters equals the size of the search term...
						found = true; // Then we've found a matching sequence of characters!
						locations.add(i); // The match is at position i. Add it to our ArrayList.
					}
				}
			}
			int termCount = locations.size();
			foundAt = new int[termCount];
			for (int h=0; h<termCount; h++) {
				foundAt[h] = locations.get(h);
			}
			return foundAt;
		}
		public MyString uppercase(){ // Turns the string to all uppercase.
			int stringLength = theString.length;
			result = new char[stringLength];
			for (int i=0; i<stringLength; i++) {
				if (theString[i] >= 97 && theString[i] <= 122) {
					result[i] = (char)(theString[i] - ('a' - 'A'));
				}
				else {
					result[i] = theString[i];
				}
			}
			return new MyString(result);
		}
		public MyString lowercase(){ // Turns the string to all lowercase.
			int stringLength = theString.length;
			result = new char[stringLength];
			for (int i=0; i<stringLength; i++) {
				if (theString[i] >= 65 && theString[i] <= 90) {
					result[i] = (char)(theString[i] + ('a' - 'A'));
				}
				else {
					result[i] = theString[i];
				}
			}
			return new MyString(result);
		}
		public MyString invert(){ // Inverts the string so it is spelled backwards.
			int stringLength = theString.length;
			result = new char[stringLength];
			for (int i=stringLength-1; i>=0; i--) {
				result[ (stringLength-1)-i ] = theString[i];
			}
			return new MyString(result);
		}
//  )
}

Java Planet enum的例子

public enum Planet {
  MERCURY (3.303e+23, 2.4397e6),
  VENUS   (4.869e+24, 6.0518e6),
  EARTH   (5.976e+24, 6.37814e6),
  MARS    (6.421e+23, 3.3972e6),
  JUPITER (1.9e+27,   7.1492e7),
  SATURN  (5.688e+26, 6.0268e7),
  URANUS  (8.686e+25, 2.5559e7),
  NEPTUNE (1.024e+26, 2.4746e7),
  PLUTO   (1.27e+22,  1.137e6);

  private final double mass;   // in kilograms
  private final double radius; // in meters
  Planet(double mass, double radius) {
      this.mass = mass;
      this.radius = radius;
  }
  public double mass()   { return mass; }
  public double radius() { return radius; }

  // universal gravitational constant  (m3 kg-1 s-2)
  public static final double G = 6.67300E-11;

  public double surfaceGravity() {
      return G * mass / (radius * radius);
  }
  public double surfaceWeight(double otherMass) {
      return otherMass * surfaceGravity();
  }
}

// Example usage (slight modification of Sun's example):
public static void main(String[] args) {
    Planet pEarth = Planet.EARTH;
    double earthRadius = pEarth.radius(); // Just threw it in to show usage

    // Argument passed in is earth Weight.  Calculate weight on each planet:
    double earthWeight = Double.parseDouble(args[0]);
    double mass = earthWeight/pEarth.surfaceGravity();
    for (Planet p : Planet.values())
       System.out.printf("Your weight on %s is %f%n",
                         p, p.surfaceWeight(mass));
}

Java Java2sAutoTextField:非严格默认设置

/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
import java.util.List;
import javax.swing.JTextField;
import javax.swing.text.*;

public class Java2sAutoTextField extends JTextField {
  class AutoDocument extends PlainDocument {

    public void replace(int i, int j, String s, AttributeSet attributeset)
        throws BadLocationException {
      super.remove(i, j);
      insertString(i, s, attributeset);
    }

    public void insertString(int i, String s, AttributeSet attributeset)
        throws BadLocationException {
      if (s == null || "".equals(s))
        return;
      String s1 = getText(0, i);
      String s2 = getMatch(s1 + s);
      int j = (i + s.length()) - 1;
      if (isStrict && s2 == null) {
        s2 = getMatch(s1);
        j--;
      } else if (!isStrict && s2 == null) {
        super.insertString(i, s, attributeset);
        return;
      }
      if (autoComboBox != null && s2 != null)
        autoComboBox.setSelectedValue(s2);
      super.remove(0, getLength());
      super.insertString(0, s2, attributeset);
      setSelectionStart(j + 1);
      setSelectionEnd(getLength());
    }

    public void remove(int i, int j) throws BadLocationException {
      int k = getSelectionStart();
      if (k > 0)
        k--;
      String s = getMatch(getText(0, k));
      if (!isStrict && s == null) {
        super.remove(i, j);
      } else {
        super.remove(0, getLength());
        super.insertString(0, s, null);
      }
      if (autoComboBox != null && s != null)
        autoComboBox.setSelectedValue(s);
      try {
        setSelectionStart(k);
        setSelectionEnd(getLength());
      } catch (Exception exception) {
      }
    }

  }

  public Java2sAutoTextField(List list) {
    isCaseSensitive = false;
    isStrict = false;
    autoComboBox = null;
    if (list == null) {
      throw new IllegalArgumentException("values can not be null");
    } else {
      dataList = list;
      init();
      return;
    }
  }

  Java2sAutoTextField(List list, Java2sAutoComboBox b) {
    isCaseSensitive = false;
    isStrict = false;
    autoComboBox = null;
    if (list == null) {
      throw new IllegalArgumentException("values can not be null");
    } else {
      dataList = list;
      autoComboBox = b;
      init();
      return;
    }
  }

  private void init() {
    setDocument(new AutoDocument());
    if (isStrict && dataList.size() > 0)
      setText(dataList.get(0).toString());
  }

  private String getMatch(String s) {
    for (int i = 0; i < dataList.size(); i++) {
      String s1 = dataList.get(i).toString();
      if (s1 != null) {
        if (!isCaseSensitive
            && s1.toLowerCase().startsWith(s.toLowerCase()))
          return s1;
        if (isCaseSensitive && s1.startsWith(s))
          return s1;
      }
    }

    return null;
  }

  public void replaceSelection(String s) {
    AutoDocument _lb = (AutoDocument) getDocument();
    if (_lb != null)
      try {
        int i = Math.min(getCaret().getDot(), getCaret().getMark());
        int j = Math.max(getCaret().getDot(), getCaret().getMark());
        _lb.replace(i, j - i, s, null);
      } catch (Exception exception) {
      }
  }

  public boolean isCaseSensitive() {
    return isCaseSensitive;
  }

  public void setCaseSensitive(boolean flag) {
    isCaseSensitive = flag;
  }

  public boolean isStrict() {
    return isStrict;
  }

  public void setStrict(boolean flag) {
    isStrict = flag;
  }

  public List getDataList() {
    return dataList;
  }

  public void setDataList(List list) {
    if (list == null) {
      throw new IllegalArgumentException("values can not be null");
    } else {
      dataList = list;
      return;
    }
  }

  private List dataList;

  private boolean isCaseSensitive;

  private boolean isStrict;

  private Java2sAutoComboBox autoComboBox;
}

Java 评估带括号的布尔表达式(使用堆栈)

// This program reads a reads and evaluates fully parenthesized Boolean
// expressions.  The purpose is to illustrate a fundamental use of stacks.


   import java.util.Stack;
   import java.util.Scanner;
   import java.util.regex.Pattern;

    public class KauffmanW7_LargeProgram05_EvalBoolean
   {
   
       public static void main(String[ ] args)
      {
         Scanner stdin = new Scanner(System.in);
         String expression;
         boolean answer;
      
         // Testing Expressions.
         expression = "(5>1)";
         answer = evaluate(expression);
         System.out.print("Test01: " + expression + " evaluated as ");
         if (answer == true) {
            System.out.println("true, which is correct.");
         } 
         else {
            System.out.println("false, which is WRONG.");
         }
         
         expression = "(5>=1)";
         answer = evaluate(expression);
         System.out.print("Test02: " + expression + " evaluated as ");
         if (answer == true) {
            System.out.println("true, which is correct.");
         } 
         else {
            System.out.println("false, which is WRONG.");
         }
         
         expression = "(5<1)";
         answer = evaluate(expression);
         System.out.print("Test03: " + expression + " evaluated as ");
         if (answer == true) {
            System.out.println("true, which is WRONG.");
         } 
         else {
            System.out.println("false, which is correct.");
         }
         
         expression = "(5<=1)";
         answer = evaluate(expression);
         System.out.print("Test04: " + expression + " evaluated as ");
         if (answer == true) {
            System.out.println("true, which is WRONG.");
         } 
         else {
            System.out.println("false, which is correct.");
         }
         
         expression = "(5==1)";
         answer = evaluate(expression);
         System.out.print("Test05: " + expression + " evaluated as ");
         if (answer == true) {
            System.out.println("true, which is WRONG.");
         } 
         else {
            System.out.println("false, which is correct.");
         }
         
         expression = "(5!=1)";
         answer = evaluate(expression);
         System.out.print("Test06: " + expression + " evaluated as ");
         if (answer == true) {
            System.out.println("true, which is correct.");
         } 
         else {
            System.out.println("false, which is WRONG.");
         }
         
         expression = "(10 > 5)";
         answer = evaluate(expression);
         System.out.print("Test07: " + expression + " evaluated as ");
         if (answer == true) {
            System.out.println("true, which is correct.");
         } 
         else {
            System.out.println("false, which is WRONG.");
         }
         
         expression = "(10 >= 5)";
         answer = evaluate(expression);
         System.out.print("Test08: " + expression + " evaluated as ");
         if (answer == true) {
            System.out.println("true, which is correct.");
         } 
         else {
            System.out.println("false, which is WRONG.");
         }
         
         expression = "(10 < 5)";
         answer = evaluate(expression);
         System.out.print("Test09: " + expression + " evaluated as ");
         if (answer == true) {
            System.out.println("true, which is WRONG.");
         } 
         else {
            System.out.println("false, which is correct.");
         }
         
         expression = "(10 <= 5)";
         answer = evaluate(expression);
         System.out.print("Test10: " + expression + " evaluated as ");
         if (answer == true) {
            System.out.println("true, which is WRONG.");
         } 
         else {
            System.out.println("false, which is correct.");
         }
         
         expression = "(10 == 5)";
         answer = evaluate(expression);
         System.out.print("Test11: " + expression + " evaluated as ");
         if (answer == true) {
            System.out.println("true, which is WRONG.");
         } 
         else {
            System.out.println("false, which is correct.");
         }
         
         expression = "(10 != 5)";
         answer = evaluate(expression);
         System.out.print("Test12: " + expression + " evaluated as ");
         if (answer == true) {
            System.out.println("true, which is correct.");
         } 
         else {
            System.out.println("false, which is WRONG.");
         }
         
         expression = "((10 > 5) && (10 > 15))";
         answer = evaluate(expression);
         System.out.print("Test13: " + expression + " evaluated as ");
         if (answer == true) {
            System.out.println("true, which is WRONG.");
         } 
         else {
            System.out.println("false, which is correct.");
         }
         
         expression = "((10 > 5) || (10 > 15))";
         answer = evaluate(expression);
         System.out.print("Test14: " + expression + " evaluated as ");
         if (answer == true) {
            System.out.println("true, which is correct.");
         } 
         else {
            System.out.println("false, which is WRONG.");
         }
         
         expression = "(((10 > 5) && (10 > 15)) || (20 > 15))";
         answer = evaluate(expression);
         System.out.print("Test15: " + expression + " evaluated as ");
         if (answer == true) {
            System.out.println("true, which is correct.");
         } 
         else {
            System.out.println("false, which is WRONG.");
         }
         
         expression = "(((10 > 5) || (10 > 15)) && (15 >= 20))";
         answer = evaluate(expression);
         System.out.print("Test16: " + expression + " evaluated as ");
         if (answer == true) {
            System.out.println("true, which is WRONG.");
         } 
         else {
            System.out.println("false, which is correct.");
         }
      
         expression = "(!(5<1))";
         answer = evaluate(expression);
         System.out.print("Test17: " + expression + " evaluated as ");
         if (answer == true) {
            System.out.println("true, which is correct.");
         } 
         else {
            System.out.println("false, which is WRONG.");
         }
      
         expression = "(!(5>1))";
         answer = evaluate(expression);
         System.out.print("Test18: " + expression + " evaluated as ");
         if (answer == true) {
            System.out.println("true, which is WRONG.");
         } 
         else {
            System.out.println("false, which is correct.");
         }
      
      
      
         answer = query(stdin, "\nWould you like to try some expressions of your own?");
         if (!answer) System.exit(0); 
         
      
      
         System.out.println("\nPlease type a Boolean expression made from");
         System.out.println("comparison between unsigned numbers, and the");
         System.out.println("operations && (AND) and || (OR).  The ");
         System.out.println("expression must be fully parenthesized.");
      
         do
         {
            System.out.print("Your expression: ");
            expression = stdin.nextLine( );
            try
            {
               answer = evaluate(expression);
               System.out.println("The value is " + answer);
            }
                catch (Exception e)
               {
                  System.out.println("Error." + e.toString( ));
               }
         }
         while (query(stdin, "Another string?"));
      
         System.out.println("All numbers are interesting.");
      }
   
     
       public static boolean query(Scanner input, String prompt)  {
         String answer;
      
         System.out.print(prompt + " [Y or N]: ");
         answer = input.nextLine( ).toUpperCase( );
         while (!answer.startsWith("Y") && !answer.startsWith("N"))
         {
            System.out.print("Invalid response. Please type Y or N: ");
            answer = input.nextLine( ).toUpperCase( );
         }
      
         return answer.startsWith("Y");
      }
        

       public static boolean evaluate(String s)    { 
      // Precondition: The string is a fully parenthesized Boolean expression
      // formed from non-negative numbers, parentheses, comparisons, and the three
      // logical operations: !(NOT, unary), && (AND, binary), and || (OR, binary).
      // Postcondition: The string has been evaluated and the value returned.
      // Exceptions: Can throw an NumberFormatException if the expression contains
      // characters other than digits, operations, parentheses and whitespace.
      // Can throw IllegalArgumentException if the input line is an
      // illegal expression, such as unbalanced parentheses or an unknown symbol.
      
      //  KEY  
      //****************
      //  >= G         *
      //  <= L         *
      //  != N         *
      //  || O         *
      //  && A         *
      //  == E         *
      //****************
      
         s = s.replace(">=","G");
         s = s.replace("<=","L");
         s = s.replace("!=","N");
         s = s.replace("||","O");
         s = s.replace("&&","A");
         s = s.replace("==","E");	
      //         System.out.println(s);		
         Scanner input = new Scanner(s);  
         Stack<Integer> numbers = new Stack<Integer>( );
         Stack<Character> operations = new Stack<Character>( );
         Stack<Boolean> booleans = new Stack<Boolean>( );
         String next;
         char first;
      
         while (input.hasNext( )) {
            if (input.hasNext(UNSIGNED_INT)) {
               next = input.findInLine(UNSIGNED_INT);
               numbers.push(new Integer(next));
            }
            else {
               next = input.findInLine(CHARACTER);
               first = next.charAt(0);
            
               switch (first) {
                  case '>': // Greater Than
                  case 'G': // >= Greater Than or Equal to.
                  case '<': // Less Than
                  case 'L': // Less Than or Equal to.
                  case 'E': // == Equal
                  case 'N': // != Not Equal
                  case '!': // Not
                  case 'A': // && And
                  case 'O': // || Or
                     operations.push(first);
                     break;
                  case ')': // Right parenthesis
                     evaluateStackTops(numbers, operations,booleans);
                     break;
                  case '(': // Left parenthesis
                     break;
                  default : // Illegal character
                     throw new IllegalArgumentException("Illegal character");
               }
            }
         }
         if (booleans.size( ) != 1)
            throw new IllegalArgumentException("Illegal input expression" );
      	
         return booleans.pop( );
      }

   
       public static boolean evalBoolean(int oper1, int oper2, char bool) {
         switch (bool) {
            case '>': // Greater Than
               return  (oper1 > oper2);
            case 'G': // >= Greater Than or Equal to.
               return (oper1 >= oper2);
            case '<': // Less Than
               return (oper1 < oper2);
            case 'L': // Less Than or Equal to.
               return (oper1 <= oper2);
            case 'E': // == Equal
               return (oper1 == oper2);
            case 'N': // != Not Equal
               return (oper1 != oper2);
            default :  // This statement should be unreachable since only the aforementioned values get sent to the method...
               throw new IllegalArgumentException("Illegal operation");
         }
      }
		
       public static void evaluateStackTops(Stack<Integer> numbers, Stack<Character> operations,Stack<Boolean> booleans) {      
         int operand1, operand2;
         boolean bool1,bool2;
         if (operations.size( ) < 1) 
            throw new IllegalArgumentException("Illegal expression (Operations Stack Underflow)");        
         char oper = operations.pop();
      	
         switch (oper) {         
            case '>': // Greater Than
            case 'G': // >= Greater Than or Equal to.
            case '<': // Less Than
            case 'L': // Less Than or Equal to.
            case 'E': // == Equal
            case 'N': // != Not Equal
               if (numbers.size( ) < 2) 
                  throw new IllegalArgumentException("Illegal expression (Numbers Stack Underflow)");        
               operand2 = numbers.pop( );
               operand1 = numbers.pop( ); 
               booleans.push(evalBoolean(operand1,operand2,oper));
               break;
         
            case '!':
               if (booleans.size( ) < 1) 
                  throw new IllegalArgumentException("Illegal expression (Booleans Stack Underflow)");        
               booleans.push (!(booleans.pop( )));
               break;
         	
            case 'A':
            case 'O':
               if (booleans.size( ) < 2) 
                  throw new IllegalArgumentException("Illegal expression (Booleans Stack Underflow)");        
               bool2 = booleans.pop( );
               bool1 = booleans.pop( ); 
               if (oper == 'A')
                  booleans.push ( (bool1 && bool2));
               else
                  booleans.push ( (bool1 || bool2));
               break;
            default : 
               throw new IllegalArgumentException("Illegal operation (Unknown Character)");
         }
      }
   
   // These patterns are from Appendix B of Data Structures and Other Objects.
   // They may be used in hasNext and findInLine to read certain patterns
   // from a Scanner.
      public static final Pattern CHARACTER = Pattern.compile("\\S.*?");  
      public static final Pattern UNSIGNED_INT = Pattern.compile("\\d+.*?");
   }