Advertisement
juxtine

calculette polo OK

Mar 18th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. package core;
  2.  
  3. import java.util.Scanner;
  4. import java.util.Stack;
  5.  
  6. public class NpiEvaluator {
  7. final static String[] ops={"+","-","*","/","mod","max","min"};//Liste des opérateurs
  8. public static void main(String[] arg){
  9. Scanner clavier=new Scanner(System.in);
  10. System.out.println("Entrez une expression NPI ou \"q\" pour quitter");
  11. System.out.print(">");
  12. String calc=clavier.nextLine();
  13. while(!calc.equals("q")){
  14. System.out.print("le résultat est : ");
  15. System.out.println(evaluate(calc));
  16. System.out.println("Entrez une expression NPI ou \"q\" pour quitter");
  17. System.out.print(">");
  18. calc=clavier.nextLine();
  19. }
  20. System.out.println("Au revoir :-)");
  21. }
  22.  
  23. public static int evaluate(String calc){
  24. Stack<String> op=new Stack<String>();
  25.  
  26.  
  27.  
  28. String[] tabOp=calc.split(" ");
  29. for(int i=0;i<tabOp.length;i++){
  30. if(isOperande(tabOp[i])){
  31. int op1=Integer.parseInt(op.pop());
  32. int op2=Integer.parseInt(op.pop());
  33. op.push(doOperande(tabOp[i], op1, op2));
  34. }else{
  35. op.push(tabOp[i]);
  36. }
  37. }
  38. return Integer.parseInt(op.pop());
  39. }
  40. public static boolean isOperande(String op){
  41. return isIn(op,ops);
  42. }
  43. public static boolean isIn(String what,String[] where){//Vérifie la présence d'une chaine dans un tableau de chaine
  44. for(int i=0;i<where.length;i++){
  45. if(where[i].equals(what))return true;
  46. }
  47. return false;
  48. }
  49. public static String doOperande(String op,int op1,int op2){
  50. if(op.equals("+")){
  51. return ""+(op1+op2);
  52. }else if(op.equals("-")){
  53. return ""+(op2-op1);
  54. }else if(op.equals("*")){
  55. return ""+op1*op2;
  56. }else if(op.equals("/")){
  57. return ""+op2/op1;
  58. }else if(op.equals("mod")){
  59. return ""+op2%op1;
  60. }else if(op.equals("max")){
  61. return ""+(op1>op2?op1:op2);
  62. }else if(op.equals("min")){
  63. return ""+(op1>op2?op2:op1);
  64. }
  65.  
  66. return "0";
  67. }
  68.  
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement