Arredontar nº em J2ME

4 respostas
L

Olá, sou novo no fórum e gostaria de saber se alguém pode me ajudar com o código abaixo ????
Gostaria de saber como arredondar o campo "Resultado:" para "24".
Exemplo: Peso:82, Altura:1.82, Resultado:24.755464315903875

Agradeço antecipadamente.

O código é o Seguinte:

package calculator;
import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.*;

public final class CalculatorMIDlet extends MIDlet implements CommandListener {

    private static final int NUM_SIZE=20;
    private final Command exitCmd  = new Command("Exit", Command.EXIT, 2);
    private final Command calcCmd = new Command("Calc", Command.SCREEN, 1);
    private final TextField t1 = new TextField("Peso:", "", NUM_SIZE, TextField.DECIMAL);
    private final TextField t2 = new TextField("Altura:", "", NUM_SIZE, TextField.DECIMAL);
    private final TextField tr = new TextField("Resultado:", "", NUM_SIZE, TextField.UNEDITABLE);
    private final ChoiceGroup cg = new ChoiceGroup("", ChoiceGroup.POPUP,
            new String[] {"add", "subtract", "multiply", "divide"}, null);
    private final Alert alert = new Alert("Error", "", null, AlertType.ERROR);
    private boolean isInitialized = false;

    protected void startApp() {
        if (isInitialized) {
            return;
        }
        Form f = new Form("Calculadora de IMC");
        f.append(t1);
        f.append("\n");
        f.append(t2);
        f.append("\n");
        f.append(tr);
        f.addCommand(exitCmd);
        f.addCommand(calcCmd);
        f.setCommandListener(this);
        Display.getDisplay(this).setCurrent(f);
        alert.addCommand(new Command("Back", Command.SCREEN, 1));
        isInitialized = true;
    }

    protected void destroyApp(boolean unconditional) {}
    protected void pauseApp() {}

    public void commandAction(Command c, Displayable d) {
        if (c == exitCmd) {
            destroyApp(false);
            notifyDestroyed();
            return;
        }
        double res = 0.0;
        double quad;

        try {
            double n1 = getNumber(t1, "First");
            double n2 = getNumber(t2, "Second");

            switch (cg.getSelectedIndex()) {
              case 0: quad = n2 * n2;  res = n1 / quad;  break;
              default:
            }
        } catch (NumberFormatException e) {
            return;
        } catch (ArithmeticException e) {
            alert.setString("Divide by zero.");
            Display.getDisplay(this).setCurrent(alert);
            return;
        }

      String res_str = Double.toString(res);

        if (res_str.length() > tr.getMaxSize()) {
            tr.setMaxSize(res_str.length());
        }
        tr.setString(res_str);
    }

    private double getNumber(TextField t, String type)
            throws NumberFormatException {
        String s = t.getString();

        if (s.length() == 0) {
            alert.setString("No " + type + " Argument");
            Display.getDisplay(this).setCurrent(alert);
            throw new NumberFormatException();
        }
        double n;

        try {
            n = Double.parseDouble(s);
        } catch (NumberFormatException e) {
            alert.setString(type + " argument is out of range.");
            Display.getDisplay(this).setCurrent(alert);
            throw e;
        }
        return n;
    }
} // end of class 'CalculatorMIDlet' definition

[size="11"][color="red"]* Editado: Lembre-se de utilizar BBCode em seus códigos - marcossousa[/color][/size] :joia:

4 Respostas

M

Opa,

você pode usar a classe DecimalFormat para retirar estas casas decimais.

DecimalFormat semDigito = new DecimalFormat("0"); String res_str = semDigito(res);

:okok:

W

Use as funções Math.ceil() ou Math.floor(). Dependendo do caso, eu faria um cast (int) que já resolvia.

Waocnek

L

Como faço para você usar a classe DecimalFormat???
Tenho que importar algo ???
Estou usando a IDE NetBeans 4.0;

De qualquer forma como usaria tb o Cast(int) ???

Absss

W

Eu não cheguei a procurar a respeito, mas não me recordo da classe DecimalFormat existir no Java ME. Procure depois no Javadoc. Usando o cast:

float peso = 82.0f; // o "f" é para que seja um float, não um double float altura = 1.82f; int indiceObesidade = (int) (peso / (altura * altura)); // O (int) vai fazer o resultado da expressão, que é um float, virar int

Sugiro estudar um pouco sobre cast também. É um assunto bem básico no Java, facilmente encontrado em qualquer tutorial na internet.

Waocnek

Criado 11 de junho de 2006
Ultima resposta 13 de jun. de 2006
Respostas 4
Participantes 3