How to print only the value of an enum? - dart

enum Move { rock, paper, scissors }
var playerMove = Move.rock;
print('Player played :${playerMove.name}'); <--- this line here gives me an error
print('AI played :${aiMove.name}'); <--- this line works perfectly though
this is the error code:
Unhandled exception:
NoSuchMethodError: Class 'Move' has no instance getter 'name'.
Receiver: Instance of 'Move'
Tried calling: name
import 'dart:io';
import 'dart:math';
enum Move { rock, paper, scissors }
void main() {
while (true) {
final rng = Random();
stdout.write('Rock, paper, scissors (r,p,s): ');
final input = stdin.readLineSync();
if (input == 'r' || input == 'p' || input == 's') {
var playerMove;
if (input == 'r') {
playerMove = Move.rock;
} else if (input == 'p') {
playerMove = Move.paper;
} else {
playerMove = Move.scissors;
}
var random = rng.nextInt(3);
var aiMove = Move.values[random];
print('Input: $input');
print('Player played :${playerMove.name}');
print('AI played :${aiMove.name}');
if (playerMove == aiMove) {
print("It's a draw");
} else if (playerMove == Move.paper && aiMove == Move.rock ||
playerMove == Move.rock && aiMove == Move.scissors ||
playerMove == Move.scissors && aiMove == Move.paper) {
print('Player win');
} else {
print('You lose');
}
} else if (input == 'q') {
break;
} else {
print('Invalid input');
}
}
}

.name is an extension on enum. Dart extensions are static: they are compile-time syntactic sugar, and they therefore require that the object's type be known at compilation time.
You have code:
var playerMove;
if (input == 'r') {
playerMove = Move.rock;
}
...
var playerMove; does not specify a type for the variable, and there is no initializer to infer its type from. It therefore is implicitly declared as dynamic, and extensions on enum will not be applied to it.
You can fix it by specifying an explicit type:
Move playerMove;

Related

Handle properly number in Jetpack Compose

How can I properly handle number in text component in jetpack compose (with MVVM pattern)
Please note that the price can be null or have a value (maybe 0 btw)
I have a poor implementation for now, I changed the keyboard like this :
OutlinedTextField(
value = if (vm.viewState.collectAsState().value.price != null) vm.viewState.collectAsState().value.price.toString() else "",
onValueChange = { vm.onProductPriceChange(it) },
label = { Text(stringResource(id = R.string.price)) },
keyboardOptions = KeyboardOptions(
capitalization = KeyboardCapitalization.None,
autoCorrect = true,
keyboardType = KeyboardType.Number
),
)
and for onValueChange :
fun onProductPriceChange(it: Any) {
if (it.toString() == "") {
_viewState.value = _viewState.value.copy(price = null)
} else {
try
{
_viewState.value = _viewState.value.copy(price = it.toString().toDouble())
}
catch (e: NumberFormatException)
{ // dismiss the bad entries
}
}
}
there can be multiple bad output of the user for example write 22..0 (I dismissed them which is a workaround acceptable)
but there are bad behaviour, when you want to write 10, it will convert it to 10.0. it is not huge but it has backwards
when you delete number in the EditText, 10.0 will become 10.0 and then 100.0 and then 10.0 and finally 1.0. btw it is impossible to go back to the null value (for this case, I can consider 0.0 = no value)
I saw that VisualTransformation (https://medium.com/google-developer-experts/hands-on-jetpack-compose-visualtransformation-to-create-a-phone-number-formatter-99b0347fc4f6) could handle my case but the documentation seems complicated
class DoubleVisualTransformation : VisualTransformation {
override fun filter(str: AnnotatedString): TransformedText {
val strNullDouble = str.text.toBigDecimalOrNull()
var transformedString: String
if (str.text == "" || strNullDouble == null)
return TransformedText(AnnotatedString(""), OffsetMapping.Identity)
else if (strNullDouble.toDouble() % 1 == 0.0 && str.text.last() != '.')
transformedString = strNullDouble.toInt().toString()
else
transformedString = str.text
return TransformedText(
text = AnnotatedString(transformedString),
offsetMapping = object : OffsetMapping {
override fun originalToTransformed(offset: Int): Int {
return offset
}
override fun transformedToOriginal(offset: Int): Int {
return offset
}
}
)
}
}
how can I improve the behavior ?
What about not returning a double to your TextField but just the String?
fun onProductPriceChange(it: String) {
if (it == "") {
_viewState.value = _viewState.value.copy(price = null)
} else {
if (it.toDoubleOrNull() != null) {
_viewState.value = _viewState.value.copy(price = it)
}
}
}

Check if brackets are balanced in a string containing only brackets in Dart

Given a string s containing just the characters (, ), {, }, [ and ], determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Example 1:
Input: s = "()", Output: true
Example 2:
Input: s = "()[]{}", Output: true
Example 3:
Input: s = "(]", Output: false
isnt the most short answer but a readable:
void main() {
isValid(String s) {
var type1 = true;
var type2 = true;
var type3 = true;
var array = [];
for (var char in s.split('')) {
switch (char) {
case '(':
type1 = false;
array.add('type1');
break;
case ')':
type1 = array.isEmpty ? false : array.removeLast() == 'type1';
break;
case '[':
type2 = false;
array.add('type2');
break;
case ']':
type2 = array.isEmpty ? false : array.removeLast() == 'type2';
break;
case '{':
type3 = false;
array.add('type3');
break;
case '}':
type3 = array.isEmpty ? false : array.removeLast() == 'type3';
break;
default:
break;
}
}
return type1 && type2 && type3;
};
print(isValid('()[]{}')); //true
print(isValid('([])')); //true
print(isValid('([])]')); //false
print(isValid('([)]')); //false
}
Here are two different solutions in dart:
main() {
print(isValid("()[]{}")); // true
print(isValid("()[){}")); // false
print(isValid("{{)){")); // false
print(isValid("(){}()")); // true
print(isValid("[][]()")); // true
print(isValid("{{()([][{{{}}")); // false
print(isValid("{(({[[{([[[]]])}]]}))}")); // true
print("\n");
print("Soltion 2");
print(isValidSolution2("()[]{}")); // true
print(isValidSolution2("()[){}")); // false
print(isValidSolution2("{{)){")); // false
print(isValidSolution2("(){}()")); // true
print(isValidSolution2("[][]()")); // true
print(isValidSolution2("{{()([][{{{}}")); // false
print(isValidSolution2("{(({[[{([[[]]])}]]}))}")); // true
}
bool isValid(String s) {
List invalid_combo_strings = ["{]", "{)", "[}", "[)", "(}", "(]"];
List invalid_start_strings = ["}", "]", ")"];
List invalid_end_strings = ["{", "[", "("];
if (s.length % 2 != 0) {
return false;
}
if (invalid_start_strings.contains(s[0]) ||
invalid_end_strings.contains(s[s.length - 1])) {
return false;
}
return !invalid_combo_strings.any((v) => s.contains(v));
}
// solution2
isValidSolution2(String s) {
List openBrackets = ["{", "(", "["];
List closeBrackets = ["}", ")", "]"];
List validatorList = [];
if (s.isEmpty) {
return true;
}
for (String c in s.split('')) {
// add the first character if validator
// list is
// empty
if (validatorList.isNotEmpty && closeBrackets.contains(c)) {
if (openBrackets[closeBrackets.indexOf(c)] != validatorList.last) {
// at most one falsy condition defaulted it
return false;
} else {
validatorList.removeLast();
}
} else {
validatorList.add(c);
}
}
// print(validatorList);
return validatorList.isEmpty;
}
sequence = input("sequence: ")
def bracetCorrect(sequence):
while True:
if '()' in sequence:
sequence = sequence.replace('()','')
elif '[]' in sequence:
sequence = sequence.replace('[]','')
elif '{}' in sequence:
sequence = sequence.replace('{}','')
else:
return not sequence
**
I think it will help you:
**
void main() {
print(isValid("()[]{}(([[[]]]))"));
}
isValid(String str) {
var isValidSymbol = true;
var tmpStr = "";
if(str.length % 2 != 0) {
return false;
}
for(int i = 0; i < str.length; i++) {
var tmpChr = str[i];
if(tmpChr == "(" || tmpChr == "{" || tmpChr == "[") {
tmpStr += tmpChr;
} else {
if(tmpChr == ")" && tmpStr[tmpStr.length - 1] != "(") {
isValidSymbol = false;
} else if(tmpChr == "}" && tmpStr[tmpStr.length - 1] != "{") {
isValidSymbol = false;
} else if(tmpChr == "]" && tmpStr[tmpStr.length - 1] != "[" ) {
isValidSymbol = false;
} else {
tmpStr = tmpStr.substring(0, tmpStr.length - 1);
}
}
}
return isValidSymbol;
}
you may check this, but it's written in python
# Given a string s containing just the characters '(', ')', '{', '}', '[' and ']',
# determine if the input string is valid.
# An input string is valid if: Open brackets must be closed by the same type of brackets.
# Open brackets must be closed in the correct order.
import re
def isValid(s: str) -> bool:
if (s == ''):
return True
elif not ((s.count('(') - s.count(')')) == 0 and (s.count('[') - s.count(']')) == 0 and (s.count('{') - s.count('}')) == 0):
return False
else:
_result = [re.search(pattern, s)
for pattern in ['\((.)*\)', '\[(.)*\]', '\{(.)*\}']]
_result = ['' if _result[i] is None else _result[i].group()[1:-1]
for i in range(len(_result))]
return isValid(_result[0]) and isValid(_result[1]) and isValid(_result[2])
if __name__ == '__main__':
print(isValid('([]){'))
print(isValid('[]'))
print(isValid('(]'))
print(isValid('([)]'))
print(isValid('{[]}'))
print(isValid('({()}{[}])'))
void main() {
// Input: s = "()"
// Output: true
// Input: s = "()[]{}"
// Output: true
bool check = validParantheses('()[]{}{}]{');
print(check);
}
bool validParantheses(String paran) {
if (paran.length % 2 != 0) {
return false;
} else {
for (var i = 0; i < paran.length; i += 2) {
var firstChar = paran[i];
var secondChar = paran[i + 1];
var closingChar = returnClosingParan(firstChar);
if (closingChar != secondChar) {
return false;
}
}
return true;
}
}
returnClosingParan(paran) {
switch (paran) {
case '(':
return ")";
case '[':
return "]";
case '{':
return "}";
default:
return;
}
}

Hi, I am using Specflow and extentReport. How do I print the pending steps to my extent report?

I used the following code but the pending steps are not shown in the extent report. Is there a way to get the pending steps printed in the extent report?Thanks.
Code 1:
if (ScenarioContext.Current.ScenarioExecutionStatus.ToString() == "StepDefinitionPending")
{
if (stepType == "Given")
scenarioName.CreateNode<Given>(ScenarioStepContext.Current.StepInfo.Text).Skip("Step Definition Pending");
else if (stepType == "When")
scenarioName.CreateNode<When>(ScenarioStepContext.Current.StepInfo.Text).Skip("Step Definition Pending");
else if (stepType == "Then")
scenarioName.CreateNode<Then>(ScenarioStepContext.Current.StepInfo.Text).Skip("Step Definition Pending");
}
I also tried this code below, but is getting null pointer exception:
Code 2:
PropertyInfo pInfo = typeof(ScenarioContext).GetProperty("TestStatus", BindingFlags.Instance | BindingFlags.NonPublic);//Getting Null value in PropertyInfo
MethodInfo getter = pInfo.GetGetMethod(nonPublic: true);
object TestResult = getter.Invoke(ScenarioContext.Current, null);
if (TestResult.ToString() == "StepDefinitionPending")
{
if (stepType == "Given")
{
scenario.CreateNode<Given>(ScenarioStepContext.Current.StepInfo.Text).Skip("Step Definition Pending");
}
else if (stepType == "When")
{
scenario.CreateNode<When>(ScenarioStepContext.Current.StepInfo.Text).Skip("Step Definition Pending");
}
else if (stepType == "Then")
{
scenario.CreateNode<Then>(ScenarioStepContext.Current.StepInfo.Text).Skip("Step Definition Pending");
}
}
Try below code.
var pendingDef = ScenarioContext.Current.ScenarioExecutionStatus.ToString();
if (pendingDef == "StepDefinitionPending")
{
if (stepType == "Given")
scenario.CreateNode<Given>(ScenarioStepContext.Current.StepInfo.Text).Skip("Step Definition Pending");
else if (stepType == "When")
scenario.CreateNode<When>(ScenarioStepContext.Current.StepInfo.Text).Skip("Step Definition Pending");
else if (stepType == "Then")
scenario.CreateNode<Then>(ScenarioStepContext.Current.StepInfo.Text).Skip("Step Definition Pending");
}
Replace TestStatus with ScenarioExecutionStatus in your Hooks class:
PropertyInfo pInfo = typeof(ScenarioContext).GetProperty("ScenarioExecutionStatus",BindingFlags.Instance |BindingFlags.NonPublic);
MethodInfo getter = pInfo.GetGetMethod(nonPublic: true);
object TestResult = getter.Invoke(ScenarioContext.Current, null);
Because, Specflow has changed the internals of the class.

Including the max and offset criteria inside GORM criteriaBuilder returns an error

Can I make this code shorter?
if(count == null && from = null) {
creditAdviceList = CreditAdvice.findAll {
ilike('id', "%$idFilter%")
.....
ilike('statusCode', statusCodeFilter)
}
}
else if(count != null && from == null) {
creditAdviceList = CreditAdvice.findAll(max: count) {
ilike('id', "%$idFilter%")
.....
ilike('statusCode', statusCodeFilter)
}
}
else if(count == null && from != null) {
creditAdviceList = CreditAdvice.findAll(offset: from) {
ilike('id', "%$idFilter%")
.....
ilike('statusCode', statusCodeFilter)
}
}
else if(count != null && from != null) {
creditAdviceList = CreditAdvice.findAll(max: count, offset: from) {
ilike('id', "%$idFilter%")
.....
ilike('statusCode', statusCodeFilter)
}
}
You see, its a series if statement for each possible scenario. Imagine if one would to use also order and cache in the parameter- there will be basically 16 unique if statements!
I've tried this [more] shorter code:
creditAdviceList = CreditAdvice.findAll {
ilike('id', "%$idFilter%")
.....
ilike('statusCode', statusCodeFilter)
if(count != null) {
maxResults(count)
}
if(from != null) {
firstResult(from)
}
}
But it gives me an error:
...No signature of method: grails.gorm.DetachedCriteria.maxResults() is applicable for argument types: (java.lang.Integer)...
I tried to convert offset to int, Integer, String, etc. I also omit the if statement inside the criteria, but the same error message occur.
findAll with a closure passed is using a DetachedCriteria internally, which is not the same as the result you would get from createCriteria mentioned in the docs. If groovy would find "something close" enough, it would tell you in the error message. The easiest way to deal with your max/from demands would be with simply with a map (which is the first argument passed). E.g.:
def qcfg = [:]
if (count) {
qcfg.count = count
}
if (from) {
qcfg.offset = from
}
creditAdviceList = CreditAdvice.findAll(qcfg) { ... }
mix, match, extract, shorten as you see fit
As far as I see, the only difference is the pagination options. If my eyes are not tricking me, yes, you can:
Map paginationArgs = [max: count, offset: from].findAll {
it.value != null
}
List<CreditAdvice> creditAdviceList = CreditAdvice.findAll(paginationArgs) {
ilike('id', "%$idFilter%")
.....
ilike('statusCode', statusCodeFilter)
}
You can style it differently, but basically you can build the pagination arguments first, and pass them to the findAll. No duplicated code, clearer responsability of the conditions. To clarify, I'm adding all the options and then filtering them to exclude the ones that are null.

infix to postfix conversion program(java)

I was working on a infix to postfix program(using stacks) but after all those efforts, something went wrong somewhere.I am getting the output as infix without conversion, please check if my intopost method is correct or not.
//stack class also containing the intopostfix method
import java.util.*;
public class Stack
{ int i,j;
char postfix[];
char stack[];
int top;
String post;
public Stack(int n)
{
stack=new char[n];
top=-1;
}
public void push(char item)
{
if(top>=stack.length)
System.out.println("Stack overflow");
else
{
stack[++top]=item;
}
}
public char pop()
{
if(top==-1)
{ System.out.println("Stack underflow");
return 0;
}
else
return stack[top--];
}
boolean isAlpha(char ch)
{
if((ch>='a'&&ch<='z')||(ch>=0&&ch<='9'))
return true;
else
return false;
}
boolean isOperator(char ch)
{
if(ch=='+'||ch=='-'||ch=='*'||ch=='/')
return true;
else return false;
}
void intopost(String str)
{
postfix=new char[str.length()];
char ch;
j=0;
for(i=0;i<str.length();i++)
{
ch=str.charAt(i);
if(ch=='(')
push(ch);
else if(isAlpha(ch))
{
postfix[j++]=ch;
}
else if(isOperator(ch))
{
push (ch);
}
else if(ch==')')
{
while((pop())!='(')
{
postfix[j++]=pop();
}
}
}
}
void disp()
{
for(i=0;i<postfix.length;i++)
{
System.out.print(postfix[i]);
}
}
}
at first change the following line
if((ch>='a'&&ch<='z')||(ch>=0&&ch<='9'))
into
if((ch>='a'&&ch<='z')||(ch>='0' &&ch<='9'))
And then
else if(ch==')')
{
while((pop())!='(')
{
postfix[j++]=pop();
}
}
here you are calling the pop function twice. this causes your stack to underflow.
that should be called once.
and finally try the following
void intopost(String str)
{
postfix=new char[str.length()];
char ch;
j=0;
for(i=0;i<str.length();i++)
{
ch=str.charAt(i);
if(ch=='(')
push(ch);
else if(isAlpha(ch))
{
postfix[j++]=ch;
}
else if(isOperator(ch))
{
push (ch);
}
else if(ch==')')
{
char c = pop();
while(c!='(')
{
postfix[j++]=c;
c= pop();
}
}
}
}
Following program would do the job for you
import java.io.*;
class stack
{
char stack1[]=new char[20];
int top;
void push(char ch)
{
top++;
stack1[top]=ch;
}
char pop()
{
char ch;
ch=stack1[top];
top--;
return ch;
}
int pre(char ch)
{
switch(ch)
{
case '-':return 1;
case '+':return 1;
case '*':return 2;
case '/':return 2;
}
return 0;
}
boolean operator(char ch)
{
if(ch=='/'||ch=='*'||ch=='+'||ch=='-')
return true;
else
return false;
}
boolean isAlpha(char ch)
{
if(ch>='a'&&ch<='z'||ch>='0'&&ch=='9')
return true;
else
return false;
}
void postfix(String str)
{
char output[]=new char[str.length()];
char ch;
int p=0,i;
for(i=0;i<str.length();i++)
{
ch=str.charAt(i);
if(ch=='(')
{
push(ch);
}
else if(isAlpha(ch))
{
output[p++]=ch;
}
else if(operator(ch))
{
if(stack1[top]==0||(pre(ch)>pre(stack1[top]))||stack1[top]=='(')
{
push(ch);
}
}
else if(pre(ch)<=pre(stack1[top]))
{
output[p++]=pop();
push(ch);
}
else if(ch=='(')
{
while((ch=pop())!='(')
{
output[p++]=ch;
}
}
}
while(top!=0)
{
output[p++]=pop();
}
for(int j=0;j<str.length();j++)
{
System.out.print(output[j]);
}
}
}
class intopost
{
public static void main(String[] args)throws Exception
{
String s;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
stack b=new stack();
System.out.println("Enter input string");
s=br.readLine();
System.out.println("Input String:"+s);
System.out.println("Output String:");
b.postfix(s);
}
}
Output:
Enter input string
a+b*c
Input String:a+b*c
Output String:
abc*+
Enter input string
a+(b*c)/d
Input String:a+(b*c)/d
Output String:
abc*d/)(+
public class InfixToPostfix
{
private Stack stack;
private String infix;
private String output = "";
public InfixToPostfix(String input)
{
infix = input;
stack = new Stack(infix.length());
}
public String convertInfixToPostfix()
{
for(int index=0; index < infix.length(); index++)
{
char itemRead = infix.charAt(index);
switch(itemRead)
{
case '+':
case '-':
processOperator(itemRead, 1);
break;
case '*':
case '/':
processOperator(itemRead, 2);
break;
case '(':
stack.push(itemRead);
break;
case ')':
popStackTillOpenParenthesis();
break;
default:
output = output + itemRead;
break;
}
}
while( !stack.isEmpty() )
{
output = output + stack.pop();
}
return output;
}
public void processOperator(char infixOperator, int precedence)
{
while( !stack.isEmpty() )
{
char popedOpr = stack.pop();
if( popedOpr == '(' )
{
stack.push(popedOpr);
break;
}
else
{
int popedOprPrecedence;
if(popedOpr == '+' || popedOpr == '-')
popedOprPrecedence = 1;
else
popedOprPrecedence = 2;
if(popedOprPrecedence < precedence)
{
stack.push(popedOpr);
break;
}
else
output = output + popedOpr;
}
}
stack.push(infixOperator);
}
public void popStackTillOpenParenthesis()
{
while(!stack.isEmpty())
{
char popedOpr = stack.pop();
if( popedOpr == '(' )
break;
else
output = output + popedOpr;
}
}
}
Explanation of postfix notation, with algorithm and example is present at: http://www.thinkscholar.com/java/java-topics/infix-to-postfix/
http://www.thinkscholar.com/java/java-topics/infix-to-postfix/
Try this code
/**
* Checks if the input is operator or not
* #param c input to be checked
* #return true if operator
*/
private boolean isOperator(char c){
if(c == '+' || c == '-' || c == '*' || c =='/' || c == '^')
return true;
return false;
}
/**
* Checks if c2 has same or higher precedence than c1
* #param c1 first operator
* #param c2 second operator
* #return true if c2 has same or higher precedence
*/
private boolean checkPrecedence(char c1, char c2){
if((c2 == '+' || c2 == '-') && (c1 == '+' || c1 == '-'))
return true;
else if((c2 == '*' || c2 == '/') && (c1 == '+' || c1 == '-' || c1 == '*' || c1 == '/'))
return true;
else if((c2 == '^') && (c1 == '+' || c1 == '-' || c1 == '*' || c1 == '/'))
return true;
else
return false;
}
/**
* Converts infix expression to postfix
* #param infix infix expression to be converted
* #return postfix expression
*/
public String convert(String infix){
String postfix = ""; //equivalent postfix is empty initially
Stack<Character> s = new Stack<>(); //stack to hold symbols
s.push('#'); //symbol to denote end of stack
for(int i = 0; i < infix.length(); i++){
char inputSymbol = infix.charAt(i); //symbol to be processed
if(isOperator(inputSymbol)){ //if a operator
//repeatedly pops if stack top has same or higher precedence
while(checkPrecedence(inputSymbol, s.peek()))
postfix += s.pop();
s.push(inputSymbol);
}
else if(inputSymbol == '(')
s.push(inputSymbol); //push if left parenthesis
else if(inputSymbol == ')'){
//repeatedly pops if right parenthesis until left parenthesis is found
while(s.peek() != '(')
postfix += s.pop();
s.pop();
}
else
postfix += inputSymbol;
}
//pops all elements of stack left
while(s.peek() != '#'){
postfix += s.pop();
}
return postfix;
}
This is taken from my blog here. Visit to get the complete code and see the each step of conversion in detail . Also note that here both parenthesis and exponent are also considered and can convert any expression.
try this code, more efficient as here i am not making use of lots of methods in this, just the main method.
package inn;
import com.sun.org.apache.bcel.internal.generic.GOTO;
import java.util.Scanner;
/**
*
* #author MADMEN
*/
public class Half_Life {
public Half_Life()
{
// a+b*c
// a*b+c
// d/e*c+2
// d/e*(c+2)
// (a+b)*(c-d)
// (a+b-c)*d/f
// (a+b)*c-(d-e)^(f+g)
// (4+8)*(6-5)/((3-2)*(2+2))
//(300+23)*(43-21)/(84+7) -> 300 23+43 21-*84 7+/
}
public static void main(String[] args)
{
System.out.print("\n Enter Expression : ");
Scanner c=new Scanner(System.in);
String exp=c.next();
int sym_top=0,po_top=-1,p=0,p2=0;
int size=exp.length();
char a[]=exp.toCharArray();
char symbols[]=new char[size];
char pfix[]=new char[size];
symbols[sym_top]='$';
for(int i=0;i<size;i++)
{
char c1=a[i];
if(c1==')')
{
while(sym_top!=0)
{
if(symbols[sym_top]=='(')
break;
pfix[++po_top]=symbols[sym_top--];
}
sym_top--;
}
else if(c1=='(')
{
symbols[++sym_top]=c1;
}
else if(c1=='+' || c1=='-' || c1=='*' || c1=='/' || c1=='^')
{
switch(c1)
{
case '+':
case '-': p=2;
break;
case '*':
case '/': p=4;
break;
case '^': p=5;
break;
default: p=0;
}
if(sym_top<1)
{
symbols[++sym_top]=c1;
}
else
{
do
{
char c2=symbols[sym_top];
if(c2=='^')
{
p2=5;
}
else if(c2=='*' || c2=='/')
{
p2=4;
}
else if(c2=='+' || c2=='-')
{
p2=2;
}
else
{
p2=1;
}
if(p2>=p)
{
pfix[++po_top]=symbols[sym_top--];
}
if(p>p2 || symbols[sym_top]=='$')
{
symbols[++sym_top]=c1;
break;
}
}while(sym_top!=-1);
}
}
else
{
pfix[++po_top]=c1;
}
}
for(;sym_top>0;sym_top--)
{
pfix[++po_top]=symbols[sym_top];
}
System.out.print("\n Infix to Postfix expression : ");
for(int j=0;j<=po_top;j++)
{
System.out.print(pfix[j]);
}
System.out.println("\n");
}
}
check the extreme last brace.
you can ask for more Data Structures programs at : sankie2902#gmail.com

Resources