⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 jan02_ericg.txt

📁 TechTips j2me的常用技巧. 网络功能
💻 TXT
📖 第 1 页 / 共 2 页
字号:
            removeCommand( cancelCommand );
            addCommand( exitCommand );
        }

        // Simple routine that iterates through the
        // response headers and looks for a Set-Cookie
        // header.  It then splits the header value
        // into parts and looks for a cookie value
        // with the name "JSESSIONID", which is what
        // a J2EE server will use for session tracking.
        // Adapt this code appropriately for other
        // kinds of cookies.

        String readCookie( HttpConnection conn )
                              throws IOException {
            String   key;
            String   value;
            String[] substrs;

            for( int i = 0;
                 ( key = conn.getHeaderFieldKey( i ) )
                                             != null;
                 ++i ){

                key = key.toLowerCase();

                if( key.equals( "set-cookie" ) ){
                    value = conn.getHeaderField( i );

                    while( value != null ){
                        substrs = split( value, ';' );
                        if( substrs[0].startsWith(
                                    "JSESSIONID=" ) ){
                            return substrs[0];
                        }

                        value = substrs[1];
                    }
                }
            }

            return null;
        }
    }
}

When run, this MIDlet displays the counter value received on each 
request. The value should increment by one on each request. If 
you remove the code that sets the Cookie header and rerun the 
application, you'll see that the value doesn't increment. That's 
because a new session is being created for each request. Note 
that the actual HTTP connections are always done on a separate 
thread to ensure that the user interface remains responsive.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
USING FIXED POINT ARITHMETIC IN THE CONNECTED LIMITED DEVICE 
CONFIGURATION

The Connected Limited Device Configuration (CLDC) defines the
most basic Java environment for very constrained devices. It does
this mostly by removing support for certain Java language
features right in the virtual machine (VM). One of the things
left out by the CLDC 1.0 specification is support for floating
point operations. In other words, the float and double 
primitive types, as well as java.lang.Float and java.lang.Double,
and any related operations, are not found in a CLDC-compliant
VM. The next generation of the CLDC, currently being defined
through the Java Community Process as JSR-139 
(see http://www.jcp.org/jsr/detail/139.jsp), might reintroduce
floating point support, but for now floating point support
is out. This also applies to any profiles built on top of the
CLDC, including the Mobile Information Device Profile.

The lack of floating point support can seem crippling at first,
especially for business applications. After all, how else can 
you represent non-integer values such as currency amounts? It's 
not nearly as bad as it seems, though, because there is a simple 
alternative: use fixed point numbers instead of floating point 
numbers.

To create a fixed point number, take an integer and fix an 
imaginary decimal point within it. For example, the integer 3000 
can represent any of the values 3000, 300.0, 30.00, 3.000, 
.3000, and so on. The number of digits to the right of the 
decimal point is the number's scale. The total number of digits 
on both sides of the decimal point is its precision. Both values 
are limited by the range of the underlying integer.

Consider an expense tracking application for US-based users. 
Although the application displays amounts in dollar units, 
internally it stores the amounts in penny units. In other words, 
1.56 dollars is stored as 156 pennies: a fixed point value with 
a scale of 2. Using CLDC-defined classes, you could write some
conversion routines:

// Routines to convert from pennies (ints)
// to dollars (strings) and back.

public class Converter {

    // Given an amount in pennies (an as int)
    // convert to dollar representation (as a string)

    public static String penniesToDollars( 
                                        int pennies ){
        StringBuffer buf = new StringBuffer();
        buf.append( pennies / 100 );
        buf.append( '.' );
        
        // Ensure always two digits
        
        int frac = Math.abs( pennies ) % 100;
        if( frac < 10 ){
            buf.append( '0' );
        }
        buf.append( frac );
        
        return buf.toString();
    }
    
    // Given an amount in dollars (as a string)
    // convert to pennies (as an int).  Truncates
    // the value after the decimal point to two digits
    // if necessary.
    
    public static int dollarsToPennies( 
                                      String dollars )
             throws NumberFormatException {
        int pos = dollars.indexOf( '.' );
        if( pos == -1 ){ // no pennies....
            return Integer.parseInt( dollars ) * 100;
        } else {
            String before = dollars.substring( 
                                             0, pos );
            int    val = 
                     Integer.parseInt( before ) * 100;
            String after = dollars.substring( pos+1 );
            int    len = after.length();

            if( len > 2 ){ // truncate to 2 digits
                after = after.substring( 0, 2 );
                len = 2;
            }

            if( len != 0 ){i
                int dec = Integer.parseInt( after );
                    
                if( len == 2 ){
                    val += dec;
                } else if( len == 1 ){
                    val += dec * 10;
                }
            }

            return val;
        }
    }
}

Whenever the user enters a dollar amount, convert it to pennies 
for internal storage and manipulation:

    int pennies = Converter.dollarsToPennies( "1.56" );
    // pennies now set to 156

Do the reverse to display the pennies as dollars:

    String dollars = Converter.penniesToDollars( 156 );
    // dollars now set to "1.56"
    
Here is a simple example of a MIDlet that uses the Converter 
class to convert a dollar-and-cents amount into pennies and back.
Two numeric input fields are used to prompt the user for the 
amount. The user first enters the dollars, followed by the cents. 
An alternative approach is to use a single unconstrained text 
field for the dollar-and-cents amount, but then it's harder
to enter numbers on MIDP devices that use keypads.

import java.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.io.*;

/**
 * A simple MIDlet that prompts for a monetary amount
 * in two parts and then converts the value to a fixed
 * point representation and back.
 */

public class FixedPointTest extends MIDlet {

    private Display display;
    private String  dollars;
    private String  cents;

    private Command exitCommand =
               new Command( "Exit", Command.EXIT, 1 );
    private Command okCommand =
               new Command( "OK", Command.OK, 1 );

    // Standard MIDlet stuff....

    public FixedPointTest(){
    }

    protected void destroyApp( boolean unconditional )
                    throws MIDletStateChangeException {
        exitMIDlet();
    }

    protected void pauseApp(){
    }

    protected void startApp()
                    throws MIDletStateChangeException {
        if( display == null ){
            initMIDlet();
        }
    }

    private void initMIDlet(){
        display = Display.getDisplay( this );
        display.setCurrent( new EnterDollars() );
    }

    public void exitMIDlet(){
        notifyDestroyed();
    }

    // Ask for dollar part of amount

    class EnterDollars extends TextBox
                       implements CommandListener {
        EnterDollars(){
            super( "Enter dollars:", "", 9, 
                    TextField.NUMERIC );

            addCommand( exitCommand );
            addCommand( okCommand );
            setCommandListener( this );
        }

        public void commandAction( Command c,
                                   Displayable d ){
            if( c == exitCommand ) exitMIDlet();
            dollars = getString();
            display.setCurrent( new EnterCents() );
        }
    }

    // Ask for cents part of amount

    class EnterCents extends TextBox
                     implements CommandListener {
        EnterCents(){
            super( "Enter cents:", "", 2, 
                    TextField.NUMERIC );

            addCommand( exitCommand );
            addCommand( okCommand );
            setCommandListener( this );
        }

        public void commandAction( Command c,
                                   Displayable d ){
            if( c == exitCommand ) exitMIDlet();
            cents = getString();
            display.setCurrent( new ShowConversion() );
        }
    }

    // Display the converted amounts

    class ShowConversion extends Form
                         implements CommandListener {
        ShowConversion(){
            super( "Result" );

            String val = dollars + "." + cents;

            try {
                StringBuffer buf = new StringBuffer();
                buf.append( "The amount: " );
                buf.append( val );
                buf.append( "\nconverts to: " );
    
                int amt = 
                   Converter.dollarsToPennies( val );
    
                buf.append( amt );
                buf.append( "\nand then back to: " );
                buf.append(
                   Converter.penniesToDollars( amt ) );
    
                text.setText( buf.toString() );
            }
            catch( NumberFormatException e ){
                text.setText( 
                           "Exception parsing value" );
            }

            append( text );

            addCommand( exitCommand );
            addCommand( okCommand );
            setCommandListener( this );
        }

        public void commandAction( Command c,
                                   Displayable d ){
            if( c == exitCommand ) exitMIDlet();
            display.setCurrent( new EnterDollars() );
        }

        private StringItem text = 
                           new StringItem( "", null );
    }
}
    
You can generalize the Converter code to deal with more than two 
digits after the decimal point. This could be useful if you need 
to calculate and display sales tax values or other amounts where 
it's important to be able to round up or down. The Converter code 
above simply truncates any digits in the fractional part beyond 
the first two digits.

Basic arithmetic operations with fixed point numbers are simple, 
providing both numbers use the same scale. Addition and 
subtraction is just a matter of adding or subtracting two 
integers. For example: 30.00 added to 20.00 is really just 
3000 + 2000 = 5000, that is, 50.00. Multiplication is more 
complicated because the scale of the result is twice the scale of 
the two operands. For example, 0.20 multiplied by 0.20 yields 
0.0400. After multiplication, then, you must adjust the scale of 
the result, rounding up or down as necessary. Similar comments 
apply to division.

As always, it's important to be aware of overflow issues when 
dealing with any kind of arithmetic. The extended range of the 
long data type (-9223372036854775808 to 9223372036854775807) is 
usually the best choice. However, for something like an expense 
tracking application, the range of the int data type (-2147483648 
to 2147483647) might be adequate if the scale is small enough and 
if numbers are only added or subtracted.

If you are porting an application that makes extensive use of 
floating point numbers, or if you're developing an application 
that requires trigonometric or logarithmic functions, the MathFP 
library could be of interest. Free for non-commercial use, the 
MathFP library defines a single class, net.jscience.math.MathFP, 
that exposes static methods for performing arithmetic with fixed 
pointer numbers of variable scale. See the jScience Technologies
web site (http://www.jscience.net) for further details and the
MathFP download.

.  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .

IMPORTANT: Please read our Terms of Use, Privacy, and Licensing
policies:
http://www.sun.com/share/text/termsofuse.html
http://www.sun.com/privacy/ 
http://developer.java.sun.com/berkeley_license.html

* FEEDBACK
  Comments? Send your feedback on the J2ME Tech Tips to: 
  
  jdc-webmaster@sun.com

* SUBSCRIBE/UNSUBSCRIBE
  - To subscribe, go to the subscriptions page,
    (http://developer.java.sun.com/subscription/), choose
    the newsletters you want to subscribe to and click "Update".
  - To unsubscribe, go to the subscriptions page,
    (http://developer.java.sun.com/subscription/), uncheck the
    appropriate checkbox, and click "Update".
  - To use our one-click unsubscribe facility, see the link at 
    the end of this email:
    
- ARCHIVES
You'll find the J2ME Tech Tips archives at:

http://java.sun.com/jdc/J2METechTips/index.html


- COPYRIGHT
Copyright 2002 Sun Microsystems, Inc. All rights reserved.
901 San Antonio Road, Palo Alto, California 94303 USA.

This document is protected by copyright. For more information, see:

http://java.sun.com/jdc/copyright.html

J2ME Tech Tips 
January 31, 2002

Sun, Sun Microsystems, Java, Java Developer Connection, J2ME, J2EE,
JavaServer Pages, and JSP are trademarks or registered trademarks 
of Sun Microsystems, Inc. in the United States and other countries.




⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -