Форум программистов, компьютерный форум, киберфорум
Java SE (J2SE)
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.89/9: Рейтинг темы: голосов - 9, средняя оценка - 4.89
2 / 2 / 2
Регистрация: 03.11.2013
Сообщений: 41

Из инфикс в постфикс

17.05.2015, 20:49. Показов 1997. Ответов 2
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Вообщем есть задание написать клас в котором будет выражение переводиться в reversed polish notation. Вроде все написал все работает, но есть два момента:
1) при использовании знака % как я понимаю нужно найти модуль числа, но оно не работает
2) также возникает проблема при использовании double (нецелых) чисел типа 2.3. Тут понимаю что нужно изменть чтобы вносились числа если есть "." разделитель как одно целое.....но как?
Вот мой код:
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import java.util.*;
 
public class Evaluator {
    private String expression;
    private String rpn;
    
    public Evaluator(String expression) {
        this.expression = expression;
    }
    
    public String Convert(){
        Stack <String> myStack = new Stack<String>();
        Queue<String> myQueue = new LinkedList<String>();
        
        String operands = "0123456789";
        String operators = "+-/*%^";
        
        String leftBracket = "(";
        String rightBracket = ")";
        
        
        for (int i=0; i<this.expression.length(); i++){
            String c = Character.toString(this.expression.charAt(i));
            if (operands.contains(c)){
                myQueue.add(c);
                System.out.println(myQueue);
            }
            else if (operators.contains(c)) {
                while(!myStack.isEmpty() && (precedence(myStack.peek()) > precedence(c))){
                    myQueue.add(myStack.pop());
                    
                }
                myStack.push(c);
                
                                
            }
            else if (leftBracket.contains(c)){
                myStack.push(c);
            }
            else if (rightBracket.contains(c)){
                if (myStack.peek().toString() != "("){
                    myQueue.add(myStack.pop());
                }
                else{
                    myStack.pop();
                }
            }           
        }
        
        while (!myStack.isEmpty()){
            if (!myStack.peek().equals(leftBracket)){
                myQueue.add(myStack.pop());
                System.out.println("123");
            }
            else{
                myStack.pop();
                System.out.println("456");
            }
        }
        
        return this.rpn = myQueue.toString();
    }
    public double Compute(){
        String operands = "0123456789";
        String operators = "+-/*%^";
        Stack <String> myStack = new Stack<String>();
        double result = 0;
            
        for (int i=0; i<this.rpn.length(); i++){
            String c = Character.toString(this.rpn.charAt(i));
                        
            if (operands.contains(c)){
                myStack.push(c);
            }
            else if (operators.contains(c)){
                double operand1 = Double.parseDouble(myStack.pop());
                double operand2 = Double.parseDouble(myStack.pop());
                       result = c.compareTo("+") == 0 ? operand1 + operand2:
                                c.compareTo("-") == 0 ? operand1 - operand2:
                                c.compareTo("*") == 0 ? operand1 * operand2:
                                c.compareTo("/") == 0 ? operand1 / operand2:
                                                        operand1 % operand2;
                myStack.push(Double.toString(result));              
            }
            
        }
        return result;
    }
    
    private static int precedence(String operator)
    {
        switch(operator){
            case "(": case ")": return 0;
            case "+": case "-": return 1;
            case "*": case "/": case "%": return 2;
            case "^": return 3;
            case "=": return 4;
        }
        return -1;
    }
}
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
17.05.2015, 20:49
Ответы с готовыми решениями:

Инфикс -> Постфикс
Здравствуйте! Уже неделю бьюсь над казалось бы простой задачей, нужно чтобы программа переводила инфиксную запись в постфиксную, то есть...

Инфикс -> Постфикс
Мне необходимо распарсить математическое выражение и перевести выражение в постфикс для последующего вычисления на стековой машине. Я...

постфикс и префикс в c++
Почему получилось в последнем выводе car3.vivod -1 #include &quot;stdafx.h&quot; #include&lt;iostream&gt; using namespace std; class Cars ...

2
2 / 2 / 2
Регистрация: 03.11.2013
Сообщений: 41
17.05.2015, 20:51  [ТС]
И вот клас который использует мой клас для подсчета
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
     
public class Calculator extends JFrame implements WindowListener,ActionListener {
 
        /* create text boxes */
        TextField Box1 = new TextField(60);
        TextField Box2 = new TextField(60);
        TextField Box3 = new TextField(60);
        String Row1 = " ";        
        String Row2 = " ";        
        String Row3 = " ";
        
        /* create some buttons */
        Button OpenP;
        Button CloseP;
        Button One;
        Button Two;
        Button Three;
        Button Four;
        Button Five;
        Button Six;
        Button Seven;
        Button Eight;
        Button Nine;
        Button Zero;
        Button Dot;
        Button Plus;
        Button Minus;
        Button Divide;
        Button Multiply;
        Button Mod;
        Button Equals;
        Button Exponent;
        
        /* add some labels */
        JLabel EMP = new JLabel    ("Input ");            
        JLabel RPN = new JLabel    ("RPN   ");        
        JLabel Result = new JLabel ("Result");
        
        boolean equalSet = false;
       
        public static void main(String[] args) {
                /* Create a new JFrame with this title */        
                Calculator myFrame = new Calculator("My Calculator");
                
                /* set the size of the frame in number of pixzels */        
                myFrame.setSize(370, 350);
                
                /* display the frame */        
                myFrame.setVisible(true);
        }
        
        /*****************************************************************/
        /* constructor for jframeTest                                    */        
        public Calculator (String title) {
 
                /* send the title to the super */
                super(title);          
                  
                /* this is the pattern that the button are laid out as */
                /* this is just linear */
                //setLayout(new FlowLayout());
                
                /* max number of rows of elements on a panel */
                /* then the number of columns ; 0 = any number */
                // setLayout(new GridLayout(0, 4));  
                 
                setLayout(null);  
                 
  
                addWindowListener(this);
                
                /* label each button with the task it will invoke*/
                OpenP = new Button("(");                          
                CloseP = new Button(")");                          
                One = new Button("1");                
                Two = new Button("2");                
                Three = new Button("3");                
                Four = new Button("4");                
                Five = new Button("5");                
                Six = new Button("6");                
                Seven = new Button("7");                
                Eight = new Button("8");                
                Nine = new Button("9");               
                Zero = new Button("0");                
                Plus = new Button("+");                
                Minus = new Button("-");                
                Divide = new Button("/");                
                Multiply = new Button("*"); 
                Mod = new Button("%");
                Equals = new Button("=");                
                Dot = new Button(".");
                Exponent = new Button("^");
                
                /* Top row of calculator */ 
                Seven.setBounds(0,0,50,50);
                Seven.setBackground(Color.WHITE);
                Eight.setBounds(51,0,50,50);                    
                Eight.setBackground(Color.WHITE);                 
                Nine.setBounds(102,0,50,50);  
                Nine.setBackground(Color.WHITE);
                OpenP.setBounds(173,0,50,50);
                OpenP.setBackground(Color.PINK);
                CloseP.setBounds(224,0,50,50);
                CloseP.setBackground(Color.PINK);
                Exponent.setBounds(275,0,50,50);                 
                Exponent.setBackground(Color.GREEN); 
                
                /* second row of calculator */
                Four.setBounds(0,51,50,50);
                Four.setBackground(Color.WHITE);
                Five.setBounds(51,51,50,50);   
                Five.setBackground(Color.WHITE);
                Six.setBounds(102,51,50,50);   
                Six.setBackground(Color.WHITE);   
                Multiply.setBounds(173,51,50,50); 
                Divide.setBounds(224,51,50,50); 
                Mod.setBounds(274,51,50,50);
                Multiply.setBackground(Color.YELLOW);
                Divide.setBackground(Color.YELLOW);
                Mod.setBackground(Color.YELLOW);
                                
                /* third row of calculator */
                One.setBounds(0,102,50,50);
                One.setBackground(Color.WHITE);  
                Two.setBounds(51,102,50,50);  
                Two.setBackground(Color.WHITE);      
                Three.setBounds(102,102,50,50); 
                Three.setBackground(Color.WHITE);  
                Plus.setBounds(173,102,50,50); 
                Minus.setBounds(224,102,50,50); 
                Equals.setBounds(275,102,50,50); 
                Plus.setBackground(Color.CYAN);
                Minus.setBackground(Color.CYAN);
                Equals.setBackground(Color.RED);
                
                /* fourth row of calculator */
                Zero.setBounds(0,153,100,50);                
                Zero.setBackground(Color.WHITE);  
                Dot.setBounds(102,153,50,50);                    
                Dot.setBackground(Color.WHITE);                                  
                
                /* display boxes */                                         
                EMP.setBounds(0,204,250,30);                          
                RPN.setBounds(0,235,250,30);                           
                Result.setBounds(0,270,250, 30);               
                Box1.setBounds(50,204,250,30);                          
                Box2.setBounds(50,235,250,30);                           
                Box3.setBounds(50,270,250, 30);               
                
                /* add each button to the frame */
                add(Seven);                
                add(Eight);
                add(Nine);                 
                add(OpenP);  
                add(CloseP);
 
                add(Four);                
                add(Five);                
                add(Six); 
                add(Multiply); 
                add(Mod);
                add(Divide);
          
                add(One);                
                add(Two);                
                add(Three);                
                add(Plus);                  
                add(Minus);
                                 
                add(Zero);                        
                add(Dot);
                add(Exponent);                      
                add(Equals);                    
 
                /* add the text boxes to the frame */
                add(Box1);                
                add(Box2);               
                add(Box3);
                add(EMP);                
                add(RPN);
                add(Result);
                
               
                One.addActionListener(this);                
                Two.addActionListener(this);                
                Three.addActionListener(this);                
                Four.addActionListener(this);               
                Five.addActionListener(this);                
                Six.addActionListener(this);                
                Seven.addActionListener(this);                
                Eight.addActionListener(this);                
                Nine.addActionListener(this);                
                Zero.addActionListener(this);                
                Plus.addActionListener(this);                
                Minus.addActionListener(this);                
                Multiply.addActionListener(this); 
                Mod.addActionListener(this);
                Divide.addActionListener(this);                
                Dot.addActionListener(this);                
                Exponent.addActionListener(this);                        
                OpenP.addActionListener(this);                      
                CloseP.addActionListener(this);                      
                Equals.addActionListener(this);                
        }
        
        /**************************************************/
        /* These are the action/events for a given button */
        /* Take action when the button is selected        */
        /* The button is identified by its action command */
        /* The action command is the label of the button   */
        public void actionPerformed(ActionEvent e) {
          Box2.setText(" ");      // clear the previous expression      
          Box3.setText(" ");      // clear the previous result
          
          /* Row1 is used to build a String to pass to the Evaluator as a constructor parameter.
           * Box1 is used to display the String asa it is being built
           */
          
          // put the numeric values in the queue (String)
          if ("1".equals(e.getActionCommand())) {
            Row1 += '1';                 
          
           } else if ("2".equals(e.getActionCommand())) {
            Row1 += '2';           
            
           } else if ("3".equals(e.getActionCommand())) {
            Row1 += '3';           
 
           } else if ("4".equals(e.getActionCommand())) {
            Row1 += '4';  
 
           } else if ("5".equals(e.getActionCommand())) {
            Row1 += '5';  
 
           } else if ("6".equals(e.getActionCommand())) {
            Row1 += '6';  
            
           } else if ("7".equals(e.getActionCommand())) {
            Row1 += '7';  
 
           } else if ("8".equals(e.getActionCommand())) {
            Row1 += '8';  
 
           } else if ("9".equals(e.getActionCommand())) {
            Row1 += '9';  
 
           } else if ("0".equals(e.getActionCommand())) {
            Row1 += '0';  
 
           } else if (".".equals(e.getActionCommand())) {
            Row1 += '.';  
 
           // In this next sections -- put operators in the queue (String)
           } else if ("^".equals(e.getActionCommand())) {
            Row1 += " ^ ";
                
           } else if ("+".equals(e.getActionCommand())) {
            Row1 += " + ";  
 
           } else if ("-".equals(e.getActionCommand())) {
            Row1 += " - ";  
 
           } else if ("*".equals(e.getActionCommand())) {
            Row1 += " * ";  
 
           } else if ("/".equals(e.getActionCommand())) {
            Row1 += " / ";  
 
           } else if ("%".equals(e.getActionCommand())) {
            Row1 += " % ";  
 
           } else if ("(".equals(e.getActionCommand())) {
            Row1 += " ( ";  
                   
           } else if (")".equals(e.getActionCommand())) {
            Row1 += " ) ";  
 
           // put the final item in the queue (String) to trigger the evaluation          
           } else if ("=".equals(e.getActionCommand())) {
            Row1 += " = ";
            equalSet = true;
           
            // instantiate a new Evaluator object
            Evaluator go = new Evaluator(Row1); 
            
            // convert to RPN and display it in box 2
            Box2.setText(go.Convert());
            
            // evaluate (compute) the result of the RPN and display in box 3  
            Box3.setText(Double.toString(go.Compute()));   
            //Row1 = " ";           
            
          } else {
            System.out.println(" Error encountered.  No button selected.");
          } 
          
          if (equalSet) {
              Box1.setText(Row1);
              Row1 = " ";
              equalSet = !equalSet;
          } else {
              Box1.setText(Row1);
          }
        }     
 
 
        /***************************************************************************/
        /* these are the events that are acting on the window                      */
        /* these are requireed in order to satisfy the overriding of the interface */
        /* events which are part of the WindowListener                             */
         
        /* Open the frame and report that it was completed in the textbox  */
        public void windowOpened(WindowEvent e) {
          System.out.println("Window event - openned window");
          Box1.setText("Ready to Calculate");
        }
        
        /* Activate the frame when it is maximized */
        public void windowActivated(WindowEvent e) {
          System.out.println("Window event - activated window");
          Box1.setText("Activated the window");
        }
        
        /* Minimize the frame */
        public void windowIconified(WindowEvent e) { 
          System.out.println("Window event - minimized the window");
          System.out.println("Shrink the window");
        }
          
        /* Maximize the frame */
        public void windowDeiconified(WindowEvent e) { 
          System.out.println("Window event - restored the window size");
          System.out.println("UnShrink the window");
        }
        /* Deactivae the frame when it is iconized */
        public void windowDeactivated(WindowEvent e) {
          System.out.println("Window event - deactivate the window");
          System.out.println("Deactivate the window"); 
        }
             
        /* all done , clean up and go home */
        public void windowClosing(WindowEvent e) {
          System.out.println("Window event - closing window");
          System.out.println("We are now leaving");
          dispose();
          System.exit(0);
        }
        
        /* Close the frame display */
        public void windowClosed(WindowEvent e) {
          /* does not appear because the window already closed */
          System.out.println("We are now gone");
        }
}
0
2 / 2 / 2
Регистрация: 03.11.2013
Сообщений: 41
18.05.2015, 08:34  [ТС]
Вообщем разобрался с модулем переписав часть кода и сейчас модуль числа работает правильно
Java
1
2
3
4
5
6
7
8
else if (operators.contains(c)){
                double operand1 = Double.parseDouble(myStack.pop());
                double operand2 = Double.parseDouble(myStack.pop());
                       result = c.compareTo("+") == 0 ? operand1 + operand2:
                                c.compareTo("-") == 0 ? operand1 - operand2:
                                c.compareTo("*") == 0 ? operand1 * operand2:
                                c.compareTo("/") == 0 ? operand1 / operand2:
                                                        operand1 % operand2;
на вот такой
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
else if (operators.contains(c)){
                double operand2 = Double.parseDouble(myStack.pop());
                double operand1 = Double.parseDouble(myStack.pop());
                if (c.equalsIgnoreCase("+")){
                    result = operand1 + operand2;
                }
                else if (c.equalsIgnoreCase("-")){
                    result = operand1 - operand2;
                }
                else if (c.equalsIgnoreCase("*")){
                    result = operand1 * operand2;
                }
                else if (c.equalsIgnoreCase("/")){
                    result = operand1 / operand2;
                }
                else if (c.equalsIgnoreCase("^")){
                    result = Math.pow(operand1, operand2);
                }
                else if (c.equalsIgnoreCase("%")){
                    result = operand1 % operand2;
                }
Добавлено через 2 минуты
Еще надо разобраться с double как сделать так чтобы при вводе числа например 2.3 оно внеслось как одно число а не 2 и 3.

Добавлено через 11 часов 7 минут
Итак вопрос остается открытым....что сделать чтобы при вводе например двухзначного числа 56(дл примера) програма записала в очередь его как одно число 56 а не два 5, 6? или 2.3 запишет 2, ., 3,.....
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
18.05.2015, 08:34
Помогаю со студенческими работами здесь

Префикс и постфикс
практически только начал изучать С# дошел до префиксов и постфиксов, я понял что это переменная +\- 1 и пишутся например ++а\а++ но не могу...

постфикс полей в таблицах БД
Привет ребята. Подскажите пожалуйста (извиняюсь если не там создала тему). В vs2010 есть Server Explorer у меня там содержится 20 таблиц и...

Постфикс списка на прологе
доброго времени суток :) как получить постфикс списка?смог сделать только префикс: prefix(_, ). prefix(, ) :-prefix(H1, H2). ...

Постфикс в префикс, используя цикл или рекурсию
Скажите пожалуйста можно ли сделать программку конвертер с постфикса в префикс используя только цикл или рекурсию, без стэка и без дерева?


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Новые блоги и статьи
SDL3 для Web (WebAssembly): Реализация движения на Box2D v3 - трение и коллизии с повёрнутыми стенами
8Observer8 20.02.2026
Содержание блога Box2D позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
«Знание-Сила»
zbw 12.02.2026
«Знание-Сила» «Время-Деньги» «Деньги -Пуля»
SDL3 для Web (WebAssembly): Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 12.02.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами и вызывать обработчики событий столкновения. . . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 11.02.2026
Содержание блога Библиотека SDL3 содержит встроенные инструменты для базовой работы с изображениями - без использования библиотеки SDL3_image. Пошагово создадим проект для загрузки изображения. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru