-
Notifications
You must be signed in to change notification settings - Fork 3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #4782 from espinoleandroo/main
Reto #28 - java
- Loading branch information
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
45 changes: 45 additions & 0 deletions
45
Retos/Reto #28 - EXPRESIÓN MATEMÁTICA [Media]/java/EspinoLeandroo.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
public class EspinoLeandroo { | ||
|
||
public static void main(String[] args) { | ||
String expression1 = "5 + 16 / 7 - 4"; | ||
String expression2 = "5 a 6"; | ||
|
||
System.out.println(validateMathExpression(expression1)); | ||
System.out.println(validateMathExpression(expression2)); | ||
} | ||
|
||
public static boolean validateMathExpression(String expression) { | ||
String[] tokens = expression.split("\\s+"); | ||
|
||
if (tokens.length % 2 == 0) { | ||
return false; | ||
} | ||
|
||
for (int i = 0; i < tokens.length; i++) { | ||
if (i % 2 == 0) { | ||
if (!isNumber(tokens[i])) { | ||
return false; | ||
} | ||
} else { | ||
if (!isOperation(tokens[i])) { | ||
return false; | ||
} | ||
} | ||
} | ||
|
||
return true; | ||
} | ||
|
||
private static boolean isNumber(String token) { | ||
try { | ||
Double.parseDouble(token); | ||
return true; | ||
} catch (NumberFormatException e) { | ||
return false; | ||
} | ||
} | ||
|
||
private static boolean isOperation(String token) { | ||
return token.matches("[+\\-*/%]"); | ||
} | ||
} |