How do I retain values entered in a textfield for re-calculation?

How do I retain values entered in a textfield for re-calculation?  I am attempting to create a gas mileage calculator that will take in three values from a user entered in three different textfields.  I have setup 5 invalid response conditions that will display an error message and return focus to the textfield responsible for the invalid response.  I am trying to use the values entered  in the textfields that were correct to recalculate the mileage after the textfield where focus was returned has been edited.  It appears that currently, after focus has been returned and my edits to that textfield has been made, when I try to recalculate, the program does nothing.  It appears to have ended after focus was returned to the invalid textfield.  Also, is their a better way to handle the divide 0 condition?  It appears that the program is still continuing with the calculation with causes the program to end although the invalid response message is displayed.

Below is the code that I have:

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

public class GasMileageCalculator extends MIDlet implements CommandListener{
   
   private Display display;
   private Form form;
   
   private TextField beginMileageField;
   private TextField endMileageField;
   private TextField gallonsField;
   private TextField gasMileageField;
   
   final int COUNT = 4;
   private Item elements[] = new Item[COUNT];
   private String begin, end, gallons;
   private Command quit, calculate;
   
   public GasMileageCalculator()
   {
        display = Display.getDisplay(this);
         
        form = new Form("Singletary Gas Mileage");
           
        beginMileageField = new TextField("Enter Begin Mileage:", "", 20, TextField.NUMERIC);
        endMileageField = new TextField("Enter End Mileage:", "", 20, TextField.NUMERIC);
        gallonsField = new TextField("Enter Gallons:", "", 20, TextField.DECIMAL);
        gasMileageField = new TextField("Gas Mileage:", "", 20, TextField.DECIMAL);
             
        elements[0] = beginMileageField;
        elements[1] = endMileageField;
        elements[2] = gallonsField;
        elements[3] = gasMileageField;
       
        for(int itr = 0; itr < COUNT; itr++){
            form.append(elements[itr]);
        }
   
        quit = new Command("Quit", Command.EXIT, 1);
        calculate = new Command("Calculate", Command.SCREEN, 2);
        form.addCommand(quit);
        form.addCommand(calculate);        
        form.setCommandListener(this);
   }

   protected void startApp()throws MIDletStateChangeException{
      display.setCurrent(form);
   }

   protected void pauseApp(){
   }

   protected void destroyApp(boolean unconditional)throws MIDletStateChangeException{
   }

   public void commandAction(Command command, Displayable displayable)
   {

       double dA, dB, dC;
       double total;
       gasMileageField.setString("");    

            beginMileageField = (TextField)form.get(0);
            begin = beginMileageField.getString();
       
            endMileageField = (TextField)form.get(1);
            end = endMileageField.getString();
     
            gallonsField = (TextField)form.get(2);
            gallons = gallonsField.getString();

            dA = 0;
            dB = 0;
            dC = 0;
            total = 0;
 
            dA = Double.valueOf(begin).doubleValue();
            dB = Double.valueOf(end).doubleValue();
            dC = Double.valueOf(gallons).doubleValue();
           
            if (dB < dA){
                display.setCurrentItem(endMileageField);
                System.out.println ("Invalid response.  End mileage is less than begin mileage.");
            }
           
            else if (dA < 0){
                display.setCurrentItem(beginMileageField);
                System.out.println ("Invalid response.  Begin mileage is less 0.");
            }
           
            else if (dB < 0){
                display.setCurrentItem(endMileageField);
                System.out.println ("Invalid response.  End mileage is less than 0.");
            }
           
            else if (dC < 0){
                display.setCurrentItem(gallonsField);
                System.out.println ("Invalid response.  Gallons is less than 0.");
            }
           
            else if (dC == 0){
                display.setCurrentItem(gallonsField);
                System.out.println ("Invalid response.  Gallons equals 0.");
            }
           
       if (command == calculate){
           total = (dB - dA)/dC;
           
           //Format output to two decimal places
           double formattedTotal = (double)(int)((total)*100.0)/100.0;
           
           gasMileageField.setString(String.valueOf(formattedTotal));
        }
        try
        {
            if (command == quit){
                destroyApp(true);
                notifyDestroyed();
            }
        }
        catch (MIDletStateChangeException me){
        }
   }
}
NSingAsked:
Who is Participating?
 
robthewolfCommented:
A few comments, though I am not 100% that it will solve your problems.
What ever command is sent you will check the fields, this doesn't make sense if you want to quit.  Also you seem to run the calculation even if you have and error with the input data.  The quit part should either be at the top or you should have the following layout:
  public void commandAction(Command command, Displayable displayable)
   {
   
       if (command == calculate){
              <check your fields and if they are ok then do calculate>
       }

       else if (command == quit){
             <put the try catch in here not outside the if>    
       }
}

you either need to return from the method if there is an error or set and error value so you know not to attempt the calculation.

for divide by 0 i think you can use an exception, I am pretty sure there is a divide by 0 exception.

finally, and this might help your fields.  In the command method you use a mixture of fields and local variables.  Aside from the fact you can condense your code, its quite dangerous what you are doing as you are using a field in a place where it would be much safer to use a local variable.

in order to set dA you do this:

       double dA, dB, dC;

            beginMileageField = (TextField)form.get(0);
            begin = beginMileageField.getString();

            dA = 0;


            dA = Double.valueOf(begin).doubleValue();

when you could just do this:

double dA = Double.valueOf(((TextField)form.get(0)).getString()).doubleValue();

the point here is that you are not setting the fields to a new value, just the local variable dA.
If you think it is too complicated to have a line like that then thats fine but just change

            beginMileageField = (TextField)form.get(0);
            begin = beginMileageField.getString();

to
            TextField mileageField = (TextField)form.get(0);
            String begin = mileageField.getString();


good luck
0
 
robthewolfCommented:
This is a bad idea
else if (dC == 0){
the double dC could have a floating point error, so it will not exactly be 0.  You should truncate it or cast it to and int so that if it is meant to be 0 then the if statement will fire correctly.
0
 
NSingAuthor Commented:
I'm not sure if I know how to do what you have advised. Would the cast to int come before the if statement is reached?  Any ideas on retaining the other values in the textfields for recalculation?
0
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

 
robthewolfCommented:
you could probably just do this:
else if( ((int)dC) == 0) {

what it does is return the int value of dC to the equality statement.  

I havent had a chance to go through the code to find out what is happening for the textfields data
0
 
NSingAuthor Commented:
Thanks.  I'm still stuck on retaining the values in the textfields for recalculation.
0
 
NSingAuthor Commented:
Thanks it worked!  I also made the change related to the local variables.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.