| Ver tema anterior :: Ver siguiente tema |
| Autor | Mensaje |
|---|
mayrita
Registrado: 06 Oct 2012 Mensajes: 1
| Publicado: 06/10/2012 10:53 pm | | | Título: calculadora |
| en mi escuela me pidieron hacer una calculadora... pero de una forma muy extraña asi que no tengo idea de como hacerla... el usuario tiene que insertar un string con una operacion por ejemplo
5+5-5=
al momento de escribir el igual debe de saber el programa que termino el string y hacer la operacion deseada por el usuario que en este caso mostraria
respuesta 5.
podria alguien darme una idea de como hacer este programa?? un saludo y gracias |
|
| Volver arriba | |
 |
Sorancio

Registrado: 29 May 2009 Mensajes: 1157 Ubicación: España
| Publicado: 07/10/2012 6:10 am | | | Título: |
| Podrias mirar la clase Pattern, la clase String e intentar hacerte una clase para procesar la entrada. _________________ Mi página web (en inglés): |
|
| Volver arriba | |
 |
Masakre
Registrado: 06 Jun 2012 Mensajes: 245
| Publicado: 13/11/2012 11:13 am | | | Título: |
| ¿Podrías explicarnos un poco más, Soracio?  ¿Pattern permitiría detectar cuándo el usuario a presionado cierta tecla? (No solicita que ingrese algún dato, sólo se está pendiente de si el usuario presiona determinada tecla, lo que puede suceder en cualquier momento) |
|
| Volver arriba | |
 |
|
Sorancio

Registrado: 29 May 2009 Mensajes: 1157 Ubicación: España
| Publicado: 13/11/2012 2:11 pm | | | Título: |
| Pattern es una clase de Java que permite procesar cadenas de carácteres que tienen un patrón, como podría ser una operación aritmética. Esta clase, por supuesto, no trabaja con InputStream.
El ejercicio estaría resuelto así:
| Código: | package com.elrincondelc.java.samples;
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigDecimal; import java.util.Stack; import java.util.regex.Pattern;
public class Calculator { private BufferedReader reader; private Pattern pattern; public Calculator(InputStream is) { reader = new BufferedReader(new InputStreamReader(is)); pattern = Pattern.compile("(?<=op)|(?=op)".replace("op", "[-+*/()=]")); } /** * @return * @throws IOException */ public BigDecimal processInput() throws IOException { Stack<String> operatorStack = new Stack<String>(); Stack<BigDecimal> numberStack = new Stack<BigDecimal>(); boolean foundEquals = false; do { final String line = reader.readLine(); String[] data = pattern.split(line); for (String token : data) { if (token.trim().length() == 0) { continue; } if (token.equals("=")) { foundEquals = true; break; } final int opLevel = operatorLevel(token); if (opLevel != 0) { if (!operatorStack.isEmpty() && opLevel < operatorLevel(operatorStack.peek())) { BigDecimal first = numberStack.pop(); BigDecimal sec = numberStack.pop(); if (token.equals("+")) { numberStack.push(sec.add(first)); } else if (token.equals("-")) { numberStack.push(sec.subtract(first)); } else if (token.equals("*")) { numberStack.push(sec.multiply(first)); } else if (token.equals("/")) { numberStack.push(sec.divide(first)); } } else { operatorStack.push(token); } } else { try { BigDecimal dc = new BigDecimal(token); numberStack.push(dc); } catch (NumberFormatException e) { System.out.println("Could not process token. " + token + " is not a number."); throw e; } } } } while (reader.ready() && !foundEquals); while (numberStack.size() != 1) { BigDecimal first = numberStack.pop(); BigDecimal sec = numberStack.pop(); String op = operatorStack.pop(); if (op.equals("+")) { numberStack.push(sec.add(first)); } else if (op.equals("-")) { numberStack.push(sec.subtract(first)); } else if (op.equals("*")) { numberStack.push(sec.multiply(first)); } else if (op.equals("/")) { numberStack.push(sec.divide(first)); } } return numberStack.pop(); } private int operatorLevel(String str) { if (str.equals("*") || str.equals("/")) { return 2; } else if (str.equals("+") || str.equals("-")) { return 1; } return 0; } public static void main(String[] args) throws IOException { final Calculator C = new Calculator(System.in); BigDecimal v = C.processInput(); System.out.println(v); } }
|
He de decir que hay mejores formas de hacerlo, pero he ido a hacerlo rápido, no bien :). _________________ Mi página web (en inglés): |
|
| Volver arriba | |
 |
|
|