import javax.microedition.lcdui.*; import javax.microedition.midlet.*;
public class GhostDog extends MIDlet implements CommandListener { private Form mMainForm; private TextField tfA; private TextField tfB; private TextField tfC; Command cmdCalc; Command cmdExit; Form m2; public GhostDog() { mMainForm = new Form("x^2 Calc"); mMainForm.append(new StringItem(null, "Insert a, b and c")); tfA=new TextField("a:","",5,TextField.ANY); tfB=new TextField("b:","",5,TextField.ANY); tfC=new TextField("c:","",5,TextField.ANY); cmdCalc=new Command("Calc!", Command.ITEM,0); cmdExit=new Command("Exit", Command.SCREEN,1); mMainForm.append(tfA); mMainForm.append(tfB); mMainForm.append(tfC); mMainForm.addCommand(cmdCalc); mMainForm.addCommand(cmdExit); mMainForm.setCommandListener(this); } public void startApp() { Display.getDisplay(this).setCurrent(mMainForm); } public void pauseApp() {} public void destroyApp(boolean unconditional) {}
public double Abso(double x) { if (x<0) { return 0-x; } else return x; } public double Sqrt(double x) { double c = x; double t = c; double EPSILON = 1E-15; // relative error tolerance
while (Abso(t - c/t) > t*EPSILON) { t = (c/t + t) / 2.0; } return t; } public void commandAction(Command cm, Displayable s) { if (cm==cmdCalc) { double a=Double.parseDouble(tfA.getString()); double b=Double.parseDouble(tfB.getString()); double c=Double.parseDouble(tfC.getString()); double x1,x2; String sx1=new String(); String sx2=new String(); String done=new String(); if (((b*b)-(4*a*c))>0) { x1=(-b+Sqrt((b*b-(4*a*c))))/(2*a); x2=(-b-Sqrt((b*b-(4*a*c))))/(2*a); sx1="" + x1; sx2="" + x2; done="X1="+sx1+" X2="+sx2; } else if (((b*b)-(4*a*c))==0) { x1=-b/(2*a); sx1="" +x1; done="X="+sx1; } else done="Unsolvable."; m2=new Form("Answer:"); m2.append(new StringItem(null, done)); Display.getDisplay(this).setCurrent(m2); } else if (cm==cmdExit) { destroyApp(false); notifyDestroyed(); } } }
|