Ok so here is the code for my calculator I started with.
import java.awt.*;
import java.applet.*;
public class Calculator extends Applet
{
private Label calculatorL; //Sets the label
private boolean firstDigit = true; //Sets Boolean firstDigit to be true
private float savedValue = 0.0f;//Sets saved value to 0
private String operator = "="; //Sets Default operator
public void init ()
{
setLayout (new BorderLayout()); //Sets the layout
add ("North", calculatorL = new Label ("0", Label.RIGHT));
Panel calculatorPanel = new Panel(); //Adding a panel for the buttons
calculatorPanel.setLayout (new GridLayout (4, 4)); //Adding a 4 * 4 grid for the layout of the buttons
calculatorPanel.setBackground(Color.CYAN);
calculatorPanel.setForeground(Color.BLUE);
addButtons (calculatorPanel, "123-");
addButtons (calculatorPanel, "456*");
addButtons (calculatorPanel, "789/");
addButtons (calculatorPanel, ".0=+");
add("Center", calculatorPanel);
}
public boolean action (Event event, Object inputobject)
{
if (event.target instanceof Button)
{
String inputstring = (String)inputobject;
if ("0123456789.".indexOf (inputstring) != -1)
{
if (firstDigit)
{
firstDigit = false;
calculatorL.setText (inputstring);
}
else
{
calculatorL.setText(calculatorL.getText() + inputstring);
}
}
else
{
if(!firstDigit)
{
solve(calculatorL.getText());
firstDigit = true;
}
operator = inputstring;
}
return true;
}
return false;
}
public void solve (String valueToBeComputed)
{
float sValue = new Float (valueToBeComputed).floatValue();
char c = operator.charAt (0);
switch (c)
{
case '=': savedValue = sValue;
break;
case '+': savedValue += sValue;
break;
case '-': savedValue -= sValue;
break;
case '*': savedValue *= sValue;
break;
case '/': savedValue /= sValue;
break;
}
calculatorL.setText (Float.toString(savedValue));
}
public void addButtons (Panel panel, String labels)
{
int count = labels.length();
for (int i = 0; i<count; i ++)
{
panel.add (new Button (labels.substring(i,i+1)));
}
}
}
What I'm trying to do is transfer my solver code into its own separate class.
This is what I have so far
import java.awt.*;
public class Solver
{
private String operator = "="; //Sets Default operator
private float savedValue = 0.0f;//Sets saved value to 0
public void solve (String valueToBeComputed)
{
float sValue = new Float (valueToBeComputed).floatValue();
char c = operator.charAt (0);
switch (c)
{
case '=': savedValue = sValue;
break;
case '+': savedValue += sValue;
break;
case '-': savedValue -= sValue;
break;
case '*': savedValue *= sValue;
break;
case '/': savedValue /= sValue;
break;
}
calculatorL.setText (Float.toString(savedValue));
}
}
Really new to using/creating my own custom classes. Could use some help transfering and seting up the solver class.