Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package core;
- import java.util.Scanner;
- import java.util.Stack;
- public class NpiEvaluator {
- final static String[] ops={"+","-","*","/","mod","max","min"};//Liste des opérateurs
- public static void main(String[] arg){
- Scanner clavier=new Scanner(System.in);
- System.out.println("Entrez une expression NPI ou \"q\" pour quitter");
- System.out.print(">");
- String calc=clavier.nextLine();
- while(!calc.equals("q")){
- System.out.print("le résultat est : ");
- System.out.println(evaluate(calc));
- System.out.println("Entrez une expression NPI ou \"q\" pour quitter");
- System.out.print(">");
- calc=clavier.nextLine();
- }
- System.out.println("Au revoir :-)");
- }
- public static int evaluate(String calc){
- Stack<String> op=new Stack<String>();
- String[] tabOp=calc.split(" ");
- for(int i=0;i<tabOp.length;i++){
- if(isOperande(tabOp[i])){
- int op1=Integer.parseInt(op.pop());
- int op2=Integer.parseInt(op.pop());
- op.push(doOperande(tabOp[i], op1, op2));
- }else{
- op.push(tabOp[i]);
- }
- }
- return Integer.parseInt(op.pop());
- }
- public static boolean isOperande(String op){
- return isIn(op,ops);
- }
- public static boolean isIn(String what,String[] where){//Vérifie la présence d'une chaine dans un tableau de chaine
- for(int i=0;i<where.length;i++){
- if(where[i].equals(what))return true;
- }
- return false;
- }
- public static String doOperande(String op,int op1,int op2){
- if(op.equals("+")){
- return ""+(op1+op2);
- }else if(op.equals("-")){
- return ""+(op2-op1);
- }else if(op.equals("*")){
- return ""+op1*op2;
- }else if(op.equals("/")){
- return ""+op2/op1;
- }else if(op.equals("mod")){
- return ""+op2%op1;
- }else if(op.equals("max")){
- return ""+(op1>op2?op1:op2);
- }else if(op.equals("min")){
- return ""+(op1>op2?op2:op1);
- }
- return "0";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement