Is there still a bug in this code that can cause an infinite loop? Please explain if there is, Thank you
String username;
bool notValid = false;
do {
stdout.write('Masukkan nama Anda (min. 6 karakter): ');
username = stdin.readLineSync();
if (username.length < 6 ) {
notValid = true;
print('Username Anda tidak valid');
}
} while (notValid);
I think you have forgotten to set the notValid to false after the correct attempt.
example:
if (username.length < 6 ) {
notValid = true;
print('Username Anda tidak valid');
} else {
notValid = false;
}
Anyway, here is the full code with null safety.
import 'dart:io';
void main(List<String> arguments) {
String? username;
bool notValid = false;
do {
print(notValid);
stdout.write('Masukkan nama Anda (min. 6 karakter): ');
username = stdin.readLineSync();
if (username != null && username.length < 6) {
notValid = true;
print('Username Anda tidak valid');
} else {
notValid = false;
}
} while (notValid);
}
Related
I have some issue while using Trilib on iOS with LoadModelFromFilePickerAsync, although it runs well on Android, Unity Editor, and Mac.
Here code:
var assetLoaderOptions = AssetLoader.CreateDefaultLoaderOptions();
var filePickerAssetLoader = AssetLoaderFilePicker.Create();
filePickerAssetLoader.LoadModelFromFilePickerAsync("Load model",
onLoad,
onMaterialsLoad,
onProgress,
onBeginLoad,
onError,
null,
assetLoaderOptions);
private void onBeginLoad(bool x)
{
btnUploadModel3D.interactable = true;
if (x == true)
{
uiCoat.SetActive(true);
uiBFill.SetActive(true);
// txtPercent.text="0%";
}
else
{
// txtPercent.text="";
ReStore();
}
}
private void onError(IContextualizedError obj)
{
btnUploadModel3D.interactable = true;
ReStore();
warningFileFormat.enabled = true;
warningFileSize.enabled = false;
}
private void onProgress(AssetLoaderContext assetLoaderContext, float progress)
{
}
private void onMaterialsLoad(AssetLoaderContext x)
{
}
private void onLoad(AssetLoaderContext x)
{
string path = ModelManager.modelFilepath;
var fileInfo = new System.IO.FileInfo(path);
var lengthFile = fileInfo.Length / 1000000;
var modelName = getModelName(path);
string formatFile = ModelManager.modelExtension.ToUpper();
if (Array.IndexOf(arrFormatFile, formatFile) < 0)
{
ReStore();
warningFileSize.enabled = false;
warningFileFormat.enabled = true;
}
else
{
if (lengthFile > 100)
{
ReStore();
warningFileSize.enabled = true;
warningFileFormat.enabled = false;
}
else
{
x.RootGameObject.tag = "ModelClone";
x.RootGameObject.name = modelName;
warningFileFormat.enabled = false;
warningFileSize.enabled = false;
UploadModelToServer(File.ReadAllBytes(path), path);
DontDestroyOnLoad(x.RootGameObject);
}
}
}
I used the above code to select file with extension: .fbx, .zip, .obj, .glb from my iPhone. I selected a file with extension in that list, nothing happens though. There are no errors reported.
How can I fix it ? Thanks.
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;
}
}
I am working on telnet emulator in web using mvc with signalR, while sending and receiving telnet stream asynchronously while loop hangs the page if kept for long, does not finish. Tried many solution but no luck.
Below is code where it stuck while continuously looking for stream bytes.
/// <summary>
/// Wait for data from the telnet server and send it to the emulation.
/// </summary>
public async Task ReadLoop(string connectionId, BaseDecoder decoder, CancellationToken ct, string PanelId)
{
var client = Get(connectionId);
if (client == null) { return; }
string script = string.Empty;
if (string.IsNullOrWhiteSpace(panelScript))
{
panelScript = objAccn.ExecuteQueryPanelScript(Convert.ToInt32(PanelId)).ToString();
script = panelScript.Replace(#"\n", Environment.NewLine);
commands = Regex.Split(script, "\r\n");
}
string loginPrompt = null;
if (PanelId != "1")
loginPrompt = "login: ";
else
loginPrompt = "name?: ";
var login = commands[0];// WebConfigurationManager.AppSettings["login"];
if (!_panelCommands.ContainsKey(0))
_panelCommands.Add(0, true);
var passwordPrompt = WebConfigurationManager.AppSettings["passwordPrompt"];
var password = commands[1];//WebConfigurationManager.AppSettings["password"];
if (!_panelCommands.ContainsKey(1))
_panelCommands.Add(1, true);
var loginAuto = (!String.IsNullOrEmpty(loginPrompt) && !String.IsNullOrEmpty(login));
var passwordAuto = (!String.IsNullOrEmpty(passwordPrompt) && !String.IsNullOrEmpty(password));
var DefaultCommandsForm60 = false;
var DefaultCommandsForm50 = false;
var DefaultScreenm50 = false;
decoder.ScriptFunc = async (string str) =>
{
if (!String.IsNullOrEmpty(str))
{
if (loginAuto && str.EndsWith(loginPrompt, StringComparison.Ordinal))
{
await client.StreamWriter.WriteAsync(login + "\r\n");
loginAuto = false;
str = str.Remove(str.Length - loginPrompt.Length);
}
if (passwordAuto && str.EndsWith(passwordPrompt, StringComparison.Ordinal))
{
await client.StreamWriter.WriteAsync(password + "\r\n");
passwordAuto = false;
str = str.Remove(str.Length - passwordPrompt.Length);
if (PanelId != "1")
DefaultCommandsForm60 = true;
else
DefaultCommandsForm50 = true;
//System.Threading.Thread.Sleep(1500);
}
if (PanelId != "1")
{
if (DefaultCommandsForm60)
{
System.Threading.Thread.Sleep(1500);
await client.StreamWriter.WriteAsync(commands[2] + "\r\n");
if (commands.Length > 2)
{
System.Threading.Thread.Sleep(1500);
await client.StreamWriter.WriteAsync(commands[3] + "\r\n");
}
if (commands.Length > 3)
{
System.Threading.Thread.Sleep(1500);
await client.StreamWriter.WriteAsync(commands[4] + "\r\n");
}
DefaultCommandsForm60 = false;
}
}
else
{
if (DefaultCommandsForm50)
{
if (commands.Length > 1)
{
// System.Threading.Thread.Sleep(2500);
if (!_panelCommands.ContainsKey(3))
{
// System.Threading.Thread.Sleep(1500);
await client.StreamWriter.WriteAsync(commands[3] + "\r\n");
_panelCommands.Add(3, true);
}
else
{
if (commands.Length > 2)
{
if (!_panelCommands.ContainsKey(4))
{
// System.Threading.Thread.Sleep(1500);
await client.StreamWriter.WriteAsync(commands[3] + "\r\n");
_panelCommands.Add(4, true);
}
DefaultCommandsForm50 = false;
}
}
DefaultScreenm50 = true;
}
}
else
{
if (DefaultScreenm50)
if (str.EndsWith("$ "))
{
await client.StreamWriter.WriteAsync("Screen" + "\r\n");
str = str.Remove(str.Length - ("$ ").Length);
DefaultScreenm50 = false;
}
}
}
}
return str;
};
const int bufferSize = 4096;
//if (ns.CanRead)
//{
// byte[] readBuffer = new byte[1024];
// int numBytesRead = 0;
// do
// {
// numBytesRead = ns.Read(readBuffer, 0, readBuffer.Length);
// //var data = Encoding.UTF8.GetString(readBuffer);
// // ss= Encoding.GetEncoding(1252).GetString(readBuffer.ToArray());
// //sb.Append(readBuffer[0].ToString);
// sb.AppendFormat("{0}", Encoding.ASCII.GetString(readBuffer, 0, numBytesRead));
// sb.Replace(Convert.ToChar(24), ' ');
// sb.Replace(Convert.ToChar(255), ' ');
// sb.Replace('?', ' ');
// //sb.Replace(Environment.NewLine, "<br />").ToString();
// }
// while (ns.DataAvailable);
//}
//if (client._stream.CanRead)
//{
// do
// {
// var inBytes = await client.ReadAsync(bufferSize, ct);
// foreach (var b in inBytes)
// {
// await decoder.AddByte(b);
// }
// await decoder.Flush();
// } while (client.IsConnected );
////}
//Disconnect(connectionId);
//var readTask = client.ReadAsync(bufferSize, ct);
while (client.IsConnected && !ct.IsCancellationRequested)
{
if (client._stream.CanRead)
{
var inBytes = await client.ReadAsync(bufferSize, ct);
foreach (var b in inBytes)
{
await decoder.AddByte(b);
}
await decoder.Flush();
}
}
Disconnect(connectionId);
}
}
In above method here the part of code where it stuck and never comes to an end.
while (client.IsConnected && !ct.IsCancellationRequested)
{
if (client._stream.CanRead)
{
var inBytes = await client.ReadAsync(bufferSize, ct);
foreach (var b in inBytes)
{
await decoder.AddByte(b);
}
await decoder.Flush();
}
}
Disconnect(connectionId);
Any suggestion and help would be appreciable!
I am trying to get CCTextFieldTTF to work in cocos sharp with Xamarin for an android application. But can't get hold of this for the life of me. Could not find any documentation on cocos sharp API either. Does anyone know how to use this class to render a text area in an android application? The reason I am asking is in a xamarin forum I saw someone saying that this does not work in the API yet. Any help would be highly appreciated. Thanks in advance.
I have this working in android
Here is the sample code:
Create a node to track the textfield
CCTextField trackNode;
protected CCTextField TrackNode
{
get { return trackNode; }
set
{
if (value == null)
{
if (trackNode != null)
{
DetachListeners();
trackNode = value;
return;
}
}
if (trackNode != value)
{
DetachListeners();
}
trackNode = value;
AttachListeners();
}
}
//create the actual input textfield
var textField = new CCTextField(string.Empty, "Somefont", 25, CCLabelFormat.SystemFont);
textField.IsColorModifiedByOpacity = false;
textField.Color = new CCColor3B(Theme.TextWhite);
textField.BeginEditing += OnBeginEditing;
textField.EndEditing += OnEndEditing;
textField.Position = new CCPoint (0, 0);
textField.Dimensions = new CCSize(VisibleBoundsWorldspace.Size.Width - (160 * sx), vPadding);
textField.PlaceHolderTextColor = Theme.TextYellow;
textField.PlaceHolderText = Constants.TextHighScoreEnterNamePlaceholder;
textField.AutoEdit = true;
textField.HorizontalAlignment = CCTextAlignment.Center;
textField.VerticalAlignment = CCVerticalTextAlignment.Center;
TrackNode = textField;
TrackNode.Position = pos;
AddChild(textField);
// Register Touch Event
var touchListener = new CCEventListenerTouchOneByOne();
touchListener.OnTouchBegan = OnTouchBegan;
touchListener.OnTouchEnded = OnTouchEnded;
AddEventListener(touchListener);
// The events
bool OnTouchBegan(CCTouch pTouch, CCEvent touchEvent)
{
beginPosition = pTouch.Location;
return true;
}
void OnTouchEnded(CCTouch pTouch, CCEvent touchEvent)
{
if (trackNode == null)
{
return;
}
var endPos = pTouch.Location;
if (trackNode.BoundingBox.ContainsPoint(beginPosition) && trackNode.BoundingBox.ContainsPoint(endPos))
{
OnClickTrackNode(true);
}
else
{
OnClickTrackNode(false);
}
}
public void OnClickTrackNode(bool bClicked)
{
if (bClicked && TrackNode != null)
{
if (!isKeyboardShown)
{
isKeyboardShown = true;
TrackNode.Edit();
}
}
else
{
if (TrackNode != null)
{
TrackNode.EndEdit();
}
}
}
private void OnEndEditing(object sender, ref string text, ref bool canceled)
{
//((CCNode)sender).RunAction(scrollDown);
Console.WriteLine("OnEndEditing text {0}", text);
}
private void OnBeginEditing(object sender, ref string text, ref bool canceled)
{
//((CCNode)sender).RunAction(scrollUp);
Console.WriteLine("OnBeginEditing text {0}", text);
}
void AttachListeners()
{
// Attach our listeners.
var imeImplementation = trackNode.TextFieldIMEImplementation;
imeImplementation.KeyboardDidHide += OnKeyboardDidHide;
imeImplementation.KeyboardDidShow += OnKeyboardDidShow;
imeImplementation.KeyboardWillHide += OnKeyboardWillHide;
imeImplementation.KeyboardWillShow += OnKeyboardWillShow;
imeImplementation.InsertText += InsertText;
}
void DetachListeners()
{
if (TrackNode != null)
{
// Remember to remove our event listeners.
var imeImplementation = TrackNode.TextFieldIMEImplementation;
imeImplementation.KeyboardDidHide -= OnKeyboardDidHide;
imeImplementation.KeyboardDidShow -= OnKeyboardDidShow;
imeImplementation.KeyboardWillHide -= OnKeyboardWillHide;
imeImplementation.KeyboardWillShow -= OnKeyboardWillShow;
imeImplementation.InsertText -= InsertText;
}
}
This is all taken from the link below but needed a bit of additional work to get it working on each platform.
https://github.com/mono/cocos-sharp-samples/tree/master/TextField
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