Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: java me how to: input - math operation - output

  1. #1
    Junior Member
    Join Date
    Mar 2010
    Location
    Athens, Greece
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Exclamation java me how to: input - math operation - output

    OK, I have this trouble. I want to create an app, which performs this simple task.

    - Accepts numbers as an input from the phone keyboard
    - Makes some operations
    - Shows the results as an output

    So, my question is this: How do I create input, math operations and result output for a MIDlet??

    ( for example adding 2 integers etc. )

    Details:

    I did this quite easily in Java and ran the program via PC and command prompt ( using a class, main method and no GUI! ).

    1 
    2 
    3	import java.util.Scanner; // program uses class Scanner
    4
    5	public class Addition
    6 {
    7 // main method begins execution of Java application
    8	 public static void main( String args[] )
    9 {
    10	 // create Scanner to obtain input from command window
    11	 Scanner input = new Scanner( System.in );
    12
    13	 int number1; // first number to add
    14	 int number2; // second number to add
    15	 int sum; // sum of number1 and number2
    16
    17 System.out.print( "Enter first integer: " ); // prompt
    18	 number1 = input.nextInt(); // read first number from user
    19
    20 System.out.print( "Enter second integer: " ); // prompt
    21	 number2 = input.nextInt(); // read second number from user
    22
    23	 sum = number1 + number2; // add numbers
    24 
    25	 System.out.printf( "Sum is %d\n", sum ); // display sum
    26
    27 } // end method main
    28
    29} // end class Addition

    But what about Java ME? I think that I do not avoid a typical GUI this time.

    I use Java ME platform SDK 3.0. btw when I see this environment which is very similar to the netbeans I feel a bit lost and dizzy.

    The first thing I thought is to build the simplest of programms, printing a line of a text, and attempt to modify this into my needs.

    The platform provides this source for you ( HelloMIDlet.java )
    package hello;
     
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
     
    public class HelloMIDlet extends MIDlet implements CommandListener {
     
        private Command exitCommand; // The exit command
        private Display display;     // The display for this MIDlet
     
        public HelloMIDlet() {
            display = Display.getDisplay(this);
            exitCommand = new Command("Exit", Command.EXIT, 0);
        }
     
        public void startApp() {
     
            TextBox t = new TextBox("Hello", "Hello World!", 256, 0);
     
     
            t.addCommand(exitCommand);
            t.setCommandListener(this);
     
            display.setCurrent(t);
        }
     
        public void pauseApp() {
        }
     
        public void destroyApp(boolean unconditional) {
        }
     
        public void commandAction(Command c, Displayable s) {
            if (c == exitCommand) {
                destroyApp(false);
                notifyDestroyed();
            } 
        }
     
    }

    which is built and run fine in the cell phone.

    I assume that I leave the pauseApp and destroyApp methods untouched.

    So I have to modify the startApp method.

    I got the meaning of the arguments of the command
    TextBox t = new TextBox("Hello", "Hello World!", 256, 0);
    first = title of the textbox
    second = text which is printed
    third = number of chars allowed
    fourth = type constraints

    and... I stuck! I don't know what to do further.


    I would like some plain guidance as a beginning.

    Thank you in advance!


  2. #2
    Junior Member ordinarypeople's Avatar
    Join Date
    Apr 2010
    Posts
    11
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: java me how to: input - math operation - output

    there are lot of tutorial of java me in the internet, just try googling it...

    at first coding with j2me, make me feel a bit dizzy too, but somehow i manage it
    its not simple n easy as java se , cmiiw

    maybe this will help u

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
     
    package dodol;
     
    import javax.microedition.lcdui.Command;
    import javax.microedition.lcdui.CommandListener;
    import javax.microedition.lcdui.Display;
    import javax.microedition.lcdui.Displayable;
    import javax.microedition.lcdui.Form;
    import javax.microedition.lcdui.TextField;
    import javax.microedition.midlet.*;
     
    /**
     * @author OP
     */
     
    public class Midlet extends MIDlet implements CommandListener {
     
    //variable declaration
     
        public static int num1, num2, add;
        public static  Form form;
        public static TextField text1, text2;
        public static Command hitung, exit, back;
        public static Display display;
     
        public Midlet()
        {
                 display = Display.getDisplay(this); //display for displaying all output
     
        }
        public void startApp() {
            itung(); // sum function
     
        }
     
        public void pauseApp() {
        }
     
        public void destroyApp(boolean unconditional) {
        }
     
     
    public void itung()
    {
     
       //all constructor
        Midlet.form = new Form("hitung"); 
     
        Midlet.text1 = new TextField("number 1", null, 30,TextField.NUMERIC);
        Midlet.text2 = new TextField("number 2", null, 30,TextField.NUMERIC);
        Midlet.hitung = new Command("hitung", Command.OK, 2);
        Midlet.exit = new Command("exit", Command.EXIT, 1);
        Midlet.back = new Command("back", Command.OK, 1);
     
     
        Midlet.form.deleteAll(); //delete all component if exist 
        Midlet.form.append(text1);
        Midlet.form.append(text2);
     
     
        Midlet.form.addCommand(Midlet.hitung);
        Midlet.form.addCommand(Midlet.exit);
        Midlet.form.setCommandListener(this); //set command listener
        Midlet.display.setCurrent(form); //displaying output from form
    }
     
    public void komanhitung()
    {
        int a = Integer.parseInt(Midlet.text1.getString());
        int b = Integer.parseInt(Midlet.text2.getString());
     
        int temp = a + b;
        String temp2 = Integer.toString(temp);
     
        Midlet.form.deleteAll();
        Midlet.form.append("total of "+Midlet.text1.getString()+" + "+Midlet.text2.getString()+" = "+temp2);
     
        Midlet.form.addCommand(Midlet.back);
        Midlet.form.addCommand(Midlet.exit);
        Midlet.form.setCommandListener(this);
        Midlet.display.setCurrent(form);
    }
     
    //all event command in here
        public void commandAction(Command c, Displayable d) {
             if (c == exit){
                /*exit aplikasi*/
                destroyApp(true);
    	    notifyDestroyed();
             }
             else if (c == hitung)
             {
              komanhitung();
             }
             else if (c == back)
             {
             itung();
             }else
            throw new UnsupportedOperationException("Not supported yet.");
        }
     
    }
    ow sorry for my bad english
    Last edited by ordinarypeople; April 4th, 2010 at 11:47 AM.
    Uncaught exception: MYBRAIN.lang.NullPointerException 0.

  3. #3
    Junior Member
    Join Date
    Mar 2010
    Location
    Athens, Greece
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: java me how to: input - math operation - output

    ordinarypeople, thanks for your post!

    I did a lot of searching over the net, but didn't find something exact for my need.

    So I decided to study java ( again ) and midlets almost from scratch! Class by class ( display, displayable, form, command etc. ) and method by method.

    The studying goes well, I managed to get comfortable with the j2me platform and the samples I create from now on usually run fine!

    I haven't solved my trouble yet, but I think I get close. I won't give way to temptation of using your code for now and I 'll keep it in mind if I stick again.

    Thanks a lot anyway!

  4. #4
    Junior Member
    Join Date
    Mar 2010
    Location
    Athens, Greece
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Thumbs up Re: java me how to: input - math operation - output

    finally! I found a solution to my trouble.

    I provide a piece of code:

     
    // This is a sample app which deals with monetary values, money
    // so all variables are of integer type ( a basic rule to avoid the unpredictable, fatal rounding of floats' fractional part )
    //they are used in pairs  to create a price - integer part ( int ) . fractional part ( int ) --->( edit ) WRONG! *
    // * ---> It prints incorrectly the less than 10 cents. ( eg. 100 euros and 5 cents = 100.5 --> error )
    // FIX: String pointZero = numC < 10 ? ".0" : "." ; ----> 100 euros and 5 cents --> numE + pointZero + numC
     
     
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
     
    /*
     * @author Lifer
     */
     
    public class TheClass extends MIDlet implements CommandListener
    {
     
    	Form theForm = new Form ( "TheClass" );	// create a Form that contains Items 
                                                                             // for entering the fund information
    									// initialize the variable at its declaration because
                                                                            // it has no dependencies from constructor parameters
     
    	// all input here
    	TextField priceE = new TextField( "Mixed Price\nEuros:", "", 7, TextField.NUMERIC );	 // numeric, no need of mixed string type
    	TextField priceC = new TextField( "Cents:", "00", 2, TextField.NUMERIC );
     
    	TextField vat = new TextField( "Value Added Tax ( 0 - 100%): ", "", 3, TextField.NUMERIC );
     
     
    		// creation of 2 buttons. one for calculation and one for exit
    		static final Command calcCommand = new Command ("Calc", Command.OK, 1 );		
    		static final Command exitCommand = new Command ("Exit", Command.EXIT, 1 );
     
    	Display display = Display.getDisplay( this );	  // addition of a variable storing the Display instance for application
     
    	public TheClass ()		// constructor. it contains all the variables created above
    	{
     
    		theForm.append ( priceE );
    		theForm.append ( priceC );
    		theForm.append ( vat );
     
    			theForm.addCommand ( calcCommand );
    			theForm.addCommand ( exitCommand );
    			theForm.setCommandListener ( this );
     
    	}
     
    	// create method calc which does all the work
    	public void calc ()
    	{
    		Alert alert = new Alert ("Calc");
     
    		int price2E = Integer.parseInt( priceE.getString() );	// for example 100 euros
    		int price2C = Integer.parseInt( priceC.getString() );	// and 50 cents
    		int price = price2E * 100 + price2C;				// stored in "price" as an integer: 10050
     
    		int vat2 = Integer.parseInt( vat.getString() );		// stores the tax, eg 21%
     
    		int tax_free = price * 100 / ( 100 + vat2 );	// instead of dividing with 21% ( 0.21 ) and messing
    										// messing with floats, I "divide" via multiply ( * 100 / 121 )
     
    		int tax_freeE = tax_free / 100;		// integer part of tax free price ( euros )
    		int tax_freeC = tax_free % 100;		// fractional part ( cents )
     
                   String tax_freeP = tax_freeC < 10 ? ".0" : "." ;   // EDIT2: fix less-than-10-cents presentation error
     
     
    				  alert.setString ( "tax free price: " + tax_freeE + tax_freeP + tax_freeC + " Euros" );	// all output here 
                             // edit1: avoid alert.setString ( "tax free price: " + tax_freeE +"." + tax_freeC ); --> false result when tax_freeC < 10
    				  alert.setTimeout ( Alert.FOREVER );	// the display alert screen stays forever, 
    				  display.setCurrent (alert);			// and not for limited time unless I press button 
     
    	}
     
     
    				// actions of our 2 buttons
    				public void commandAction (Command c, Displayable d)
    				{
    					if (c == exitCommand)
    					{
    						notifyDestroyed();
    					}
    					else if (c == calcCommand)
    					{
    						calc ();
    					}
    				}
     
    	// leave this part as it is
        public void startApp()
    	{
    		display.setCurrent ( theForm ); // only remember to add correctly the name of the Form variable
        }
     
        public void pauseApp()
            {}
     
        public void destroyApp(boolean unconditional)
    	{}
     
    }

    This is a sample code of the app i created. Nothing special for pros, yet of great value to me, as I started to become familiar with the MIDlets, their buttons, commands etc etc.

    I haven't compiled this piece, if there is sth wrong here, please comment. ( whoever might be interested )
    Last edited by Lifer; April 23rd, 2010 at 03:35 AM. Reason: to improve code

Similar Threads

  1. Output String Handling in Java
    By merry in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 21st, 2010, 09:59 PM
  2. Simple Input/Output program Acting weird
    By drexasaurus in forum What's Wrong With My Code?
    Replies: 0
    Last Post: February 19th, 2010, 02:15 PM
  3. Operation ==
    By meytalg in forum Java Theory & Questions
    Replies: 6
    Last Post: January 4th, 2010, 07:43 PM
  4. Math in Java?
    By [Kyle] in forum Java Theory & Questions
    Replies: 3
    Last Post: September 23rd, 2009, 12:21 PM
  5. Redirect error and output stream using java program
    By leenabora in forum File I/O & Other I/O Streams
    Replies: 5
    Last Post: June 16th, 2009, 04:12 AM