Como crio uma calculadora com um só textfield? [RESOLVIDO]

4 respostas
edevenes

Boa noite,

Sou novo na programação e fazer uma calculadora básica é moleza, o que não estou conseguindo é fazer uma com uma entrada, que armazene na memória o 1º numero digitado e depois venha fazer a operação com o 2º digitado e o resultado dos mesmos venha fazer mais uma operação com outro numero e assim por diante, tudo em uma só entrada, como uma calculadora verdadeira.

até agora fiz isso…

arquivo principal calculadora.java

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;


public class calculadora extends MIDlet {
	
	private Form form;

	public calculadora() {
		
		form = new Form("Calculadora");
		TextField n = new TextField("", "", 10, TextField.NUMERIC);
		form.append(n);
		
		Command s = new Command("Sair", Command.EXIT,1);
		form.addCommand(s);
		Command soma = new Command("Soma", Command.OK,1);
		form.addCommand(soma);
		Command subtrai =  new Command("Subtrai", Command.OK,1);
		form.addCommand(subtrai);
		Command multiplica =  new Command("Multiplica", Command.OK,1);
		form.addCommand(multiplica);
		Command divide =  new Command("Divide", Command.OK,1);
		form.addCommand(divide);
		Command result =  new Command("Resultado", Command.OK,1);
		form.addCommand(result);
		form.setCommandListener(new calcula(this));
		
	}

	protected void destroyApp(boolean b){
		

	}

	protected void pauseApp() {
		

	}

	protected void startApp(){
		
		Display d = Display.getDisplay(this);
		d.setCurrent(form);

	}

}

agora o calcula.java

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;


public class calcula implements CommandListener {
	
	private calculadora calcu;
	private int num2;
	
	public calcula(calculadora cal) {
		
		calcu = cal;
		
	}

	public int getNum2() {
		return num2;
	}

	public void setNum2(int num2) {
		this.num2 = num2;
	}

	public void commandAction(Command c, Displayable d) {
		

		if (c.getLabel().equals("Sair")) {
			calcu.destroyApp(false);
			calcu.notifyDestroyed();
			
		} else if (c.getLabel().equals("Soma")){
			
			Form f = (Form) d;
			TextField a = (TextField) f.get(0);
			String aa = a.getString();
			int num1 = Integer.parseInt(aa);
			num2 = num1;
			num1 = num2 + num2;
			String s = String.valueOf(num1);
			a.setString(s);
			
			
		} else if (c.getLabel().equals("Subtrai")){
			
			
			
		}else if (c.getLabel().equals("Multiplica")){
			
			
			
		}else if (c.getLabel().equals("Divide")){
			
			
			
		}else if (c.getLabel().equals("Resultado")){
			
			Form f = (Form) d;
			TextField a = (TextField) f.get(0);
			String aa = a.getString();
			a.setString(aa);
			
		}
		
	}

}

Se puderem me ajudar, ficarei grato!

4 Respostas

nakrak

Tem uma calculadora bem simples talvez ajude


http://servonoturno.blogspot.com/

edevenes

Só pra lembrar, é em J2ME
Intão, ele só tem opções de operações no cantinho da tela, e não botões.
Só quero saber onde eu crio as variáveis pra ficar na memória a operação e um dos numeros digitados!

I

Da uma olhada ai e ve se e isso q vc ta procurando...

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class Calculadora extends JFrame implements ActionListener
{
	JButton bL,b1,b2,b3,b4,b5,b6,b7,b8,b9,b0,bSomar,bSub,bMult,bDiv,bResult;
	JTextField tex;
	float num1, num2;
	char op;
	
	public static void main(String args[])
	{
		JFrame lay = new Calculadora();
		lay.setVisible(true);
		lay.setResizable(false);
	}
	
	public Calculadora()
	{
		super();
		setTitle("Calculadora");
		setBounds(200,100,225,215);
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);  
		
		tex = new JTextField(10); tex.setSize(205,30); tex.setLocation(10,15);
		tex.setEnabled(true); tex.addActionListener(this);
		
		bL = new JButton("C"); bL.setSize(50,30); bL.setLocation(10,140);
		bL.setEnabled(true); bL.addActionListener(this);
		
		b1 = new JButton("1"); b1.setSize(50,30); b1.setLocation(10,50);
		b1.setEnabled(true); b1.addActionListener(this);
		b2 = new JButton("2"); b2.setSize(50,30); b2.setLocation(60,50);
		b2.setEnabled(true); b2.addActionListener(this);
		b3 = new JButton("3"); b3.setSize(50,30); b3.setLocation(110,50);
		b3.setEnabled(true); b3.addActionListener(this);
		
		bDiv = new JButton("/"); bDiv.setSize(50,30); bDiv.setLocation(165,50);
		bDiv.setEnabled(true); bDiv.addActionListener(this);
		
		b4 = new JButton("4"); b4.setSize(50,30); b4.setLocation(10,80);
		b4.setEnabled(true); b4.addActionListener(this);
		b5 = new JButton("5"); b5.setSize(50,30); b5.setLocation(60,80);
		b5.setEnabled(true); b5.addActionListener(this);
		b6 = new JButton("6"); b6.setSize(50,30); b6.setLocation(110,80);
		b6.setEnabled(true); b6.addActionListener(this);
		
		bMult = new JButton("x"); bMult.setSize(50,30); bMult.setLocation(165,80);
		bMult.setEnabled(true); bMult.addActionListener(this);
		
		b7 = new JButton("7"); b7.setSize(50,30); b7.setLocation(10,110);
		b7.setEnabled(true); b7.addActionListener(this);
		b8 = new JButton("8"); b8.setSize(50,30); b8.setLocation(60,110);
		b8.setEnabled(true); b8.addActionListener(this);
		b9 = new JButton("9"); b9.setSize(50,30); b9.setLocation(110,110);
		b9.setEnabled(true); b9.addActionListener(this);
		
		bSub = new JButton("-"); bSub.setSize(50,30); bSub.setLocation(165,110);
		bSub.setEnabled(true); bSub.addActionListener(this);
		
		b0 = new JButton("0"); b0.setSize(50,30); b0.setLocation(60,140);
		b0.setEnabled(true); b0.addActionListener(this);
		bResult = new JButton("="); bResult.setSize(50,30); bResult.setLocation(110,140);
		bResult.setEnabled(true); bResult.addActionListener(this);
		
		bSomar = new JButton("+"); bSomar.setSize(50,30); bSomar.setLocation(165,140);
		bSomar.setEnabled(true); bSomar.addActionListener(this);
		
		getContentPane().setLayout(null);
		getContentPane().add(tex); getContentPane().add(bL);
        getContentPane().add(b1); getContentPane().add(b2); getContentPane().add(b3);
        getContentPane().add(bDiv);
        getContentPane().add(b4); getContentPane().add(b5); getContentPane().add(b6);
        getContentPane().add(bMult);
        getContentPane().add(b7); getContentPane().add(b8); getContentPane().add(b9);
        getContentPane().add(bSub);
        getContentPane().add(b0); getContentPane().add(bResult); getContentPane().add(bSomar);
	}
	
	public void actionPerformed(ActionEvent e)
	{
	 try
	 {	
		Object obj = e.getSource();
		
		if (obj == bL){ tex.setText(""); }
		
		if (obj == b1){ String num = tex.getText(); tex.setText(num + "1"); }
		if (obj == b2){ String num = tex.getText(); tex.setText(num + "2"); }
		if (obj == b3){ String num = tex.getText(); tex.setText(num + "3"); }
		if (obj == b4){ String num = tex.getText(); tex.setText(num + "4"); }
		if (obj == b5){ String num = tex.getText(); tex.setText(num + "5"); }
		if (obj == b6){ String num = tex.getText(); tex.setText(num + "6"); }
		if (obj == b7){ String num = tex.getText(); tex.setText(num + "7"); }
		if (obj == b8){ String num = tex.getText(); tex.setText(num + "8"); }
		if (obj == b9){ String num = tex.getText(); tex.setText(num + "9"); }
		if (obj == b0){ String num = tex.getText(); tex.setText(num + "0"); }
		
		if (obj == bSomar){num1=Float.parseFloat(tex.getText()); op='+' ; tex.setText(""); }
		if (obj == bSub)  {num1=Float.parseFloat(tex.getText()); op='-' ; tex.setText(""); }
		if (obj == bMult) {num1=Float.parseFloat(tex.getText()); op='*' ; tex.setText(""); }
		if (obj == bDiv)  {num1=Float.parseFloat(tex.getText()); op='/' ; tex.setText(""); }
		
		if (obj == bResult) Calcula();
	 }
	
	 catch (Exception ex) 
	 {  
         JOptionPane.showMessageDialog(null, "Verifique os números digitados.");  
     } 
	 
	}
	
	public void Calcula()
	{
	  try
	  {
		float resultado;
		
		num2 = Float.parseFloat(tex.getText());
		
		switch(op)
		{
			case '+': { resultado = num1+num2; break; }
			case '-': { resultado = num1-num2; break; }
			case '*': { resultado = num1*num2; break; }
			case '/': { resultado = num1/num2; break; }
			default : { resultado = 0; break; }
		}
		
		tex.setText(resultado + "");
	  }
		
	   catch (Exception e) 
       {  
          JOptionPane.showMessageDialog(null, "Verifique os números digitados.");  
	   } 
	}
}
edevenes

Aqui esta o que eu queria… vou deixar aqui pra ngm fica se batendo ai, 50 e poucas visualizações e ngm sabia, caramba eim!
vamo estuda povo!

calculadora.java

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;


public class calculadora extends MIDlet {
	
	private Form form;
	private int n1 = 0;
	private int op;

	public int getN1() {
		return n1;
	}

	public void setN1(int n1) {
		this.n1 = n1;
	}

	public int getOp() {
		return op;
	}

	public void setOp(int op) {
		this.op = op;
	}

	public calculadora() {
		
		form = new Form("Calculadora");
		TextField n = new TextField("", "", 10, TextField.NUMERIC);
		form.append(n);
		
		Command s = new Command("Sair", Command.EXIT,1);
		form.addCommand(s);
		Command soma = new Command("Soma", Command.OK,1);
		form.addCommand(soma);
		Command subtrai =  new Command("Subtrai", Command.OK,1);
		form.addCommand(subtrai);
		Command multiplica =  new Command("Multiplica", Command.OK,1);
		form.addCommand(multiplica);
		Command divide =  new Command("Divide", Command.OK,1);
		form.addCommand(divide);
		Command result =  new Command("Resultado", Command.OK,1);
		form.addCommand(result);
		form.setCommandListener(new calcula(this));
		
	}

	protected void destroyApp(boolean b){
		

	}

	protected void pauseApp() {
		

	}

	protected void startApp(){
		
		Display d = Display.getDisplay(this);
		d.setCurrent(form);

	}

}

aqui o segundo arquivo: calcula.java

import javax.microedition.lcdui.Alert;
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;


public class calcula implements CommandListener {
	
	private calculadora calcu;
	
	public calcula(calculadora cal) {
		
		calcu = cal;
		
	}

	public void commandAction(Command c, Displayable d) {
		
		if (c.getLabel().equals("Sair")) {
			calcu.destroyApp(false);
			calcu.notifyDestroyed();
			
		}
		
		Form f = (Form) d;
		TextField a = (TextField) f.get(0);
		
		
		if (c.getLabel().equals("Soma")){
			
			calcu.setOp(1);
			
		} else if (c.getLabel().equals("Subtrai")){
			
			calcu.setOp(2);
			
		}else if (c.getLabel().equals("Multiplica")){
			
			calcu.setOp(3);
			
		}else if (c.getLabel().equals("Divide")){
			
			calcu.setOp(4);
			
		}else if (c.getLabel().equals("Resultado")){
			
			calcu.setOp(0);
			
		}
		
		
		
		if(a.equals("")){
			
			String msg = "Digite alguma coisa porra!";
			Alert msgs = new Alert("ERROR!");
			msgs.setString(msg);
			Display de = Display.getDisplay(calcu);
			de.setCurrent(msgs);
			
		}else{
			
			int num1 = 0;
			int num2 = 0;
			TextField saida = (TextField) f.get(0);
			System.out.println(calcu.getOp());
			
			if (calcu.getOp() == 0) {
				String saidaa = saida.getString();
				num1 = calcu.getN1();
				num2 = Integer.parseInt(saidaa);
				calcu.setN1(num2);
				
			} else if (calcu.getOp() == 1) {
				String saidaa = saida.getString();
				num1 = calcu.getN1();
				num2 = Integer.parseInt(saidaa);
				int res = num1 + num2;
				calcu.setN1(res);
				String ress = String.valueOf(res);
				saida.setString(ress);

			} else if (calcu.getOp() == 2) {
				String saidaa = saida.getString();
				num1 = calcu.getN1();
				num2 = Integer.parseInt(saidaa);
				int res = num1 - num2;
				calcu.setN1(res);
				String ress = String.valueOf(res);
				saida.setString(ress);
				
			} else if (calcu.getOp() == 3) {
				String saidaa = saida.getString();
				num1 = calcu.getN1();
				num2 = Integer.parseInt(saidaa);
				int res = num1 * num2;
				calcu.setN1(res);
				String ress = String.valueOf(res);
				saida.setString(ress);
				
			} else if (calcu.getOp() == 4) {
				String saidaa = saida.getString();
				num1 = calcu.getN1();
				num2 = Integer.parseInt(saidaa);
				
				if(num1 == 0 || num2 == 0){
					
					String msg = "Impossivel dividir por 0!";
					Alert msgs = new Alert("ERROR!");
					msgs.setString(msg);
					Display de = Display.getDisplay(calcu);
					de.setCurrent(msgs);
					
					int res = 1;
					calcu.setN1(res);
					String ress = String.valueOf(res);
					saida.setString(ress);
					
				}
				
				int res = num1 / num2;
				calcu.setN1(res);
				String ress = String.valueOf(res);
				saida.setString(ress);
			}
		}
		
	}

}

Então… resolvido!
Obrigado a todos que tentaram!

Criado 2 de novembro de 2009
Ultima resposta 3 de nov. de 2009
Respostas 4
Participantes 3