I have a question about the following code, the idea is that if given as input:
a + b + c + d + ... + z
Gives as output:
correct expression
If given as input:
a + b + c ++ b + b b...z
Gives as output:
wrong expression
The program works fine if it is given:
a+b
But there is an error when I enter it
a+b+c+d
Well, it gives me as output:
incorrect expression
When it is correct.
public class Ejercicio5sep {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
LinkedList pila = new LinkedList();
int correcto = 0;
System.out.println("Cuantos elementos quiere introducirle a la pila?");
int n = x.nextInt();
for (int i = 0; i < n; i++) {
System.out.println("introduzca su elemento");
String e = x.next();
pila.push(e);
}
if (pila.size() % 2 != 0) {
float d = (float) pila.size() / 2f + 0.5f;
for (int i = 0; i < pila.size() / 2; i++) {
String a = (String) pila.pop();
String b = (String) pila.pop();
if (false == a.equals("+") && b.equals("+")) {
correcto++;
}
}
String c = (String) pila.pop();
if (false == c.equals("+"))//(*)
{
correcto++;
}
//si input: a+b+c+d
System.out.println(correcto);//dice que correcto==2, entonces
//no hizo la instruccion (*), ?porque
if (correcto == d) {
System.out.println("La expresion es correta");
} else {
System.out.println("La expresion no es correta");
}
} else {
System.out.println("expresion incorrecta :(");
}
Good morning, I propose an alternative that I think is better understood.
Concept
Notice the pattern of your correct solutions:
All these solutions have in common that the odd elements are an operation (+). Since you keep everything in a stack, we could check if the expression is correct or not, analyzing that the even elements are different from "+" and the odd ones are equal to "+".
Code
This way of setting up the algorithm saves you from having to analyze the entire expression if it is incorrect, since as soon as it finds something incorrect, it stops searching.
I hope it helps you and is easy to understand.