I have this Java lexical analyzer algorithm that prints out each assigned token to every symbol. The output should print out on each and every individual line without any space in between. But mine does have spaces. I have tried to use trim() method, even replaceAll() method, nothing seems to work. Here is my Java code:
import org.w3c.dom.ls.LSOutput;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Lexer {
public static void Tokenize(String fileName) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = reader.readLine()) != null) {
line = removeComments(line);
String[] tokens = tokenizeLine(line);
for (String token : tokens) {
System.out.println(token);
}
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
System.err.println("Error closing file: " + e.getMessage());
}
}
System.out.println("SYNTAX ERROR: INVALID IDENTIFIER NAME");
}
private static String removeComments(String line) {
// Remove inline comments
line = line.replaceAll("//.*", "");
// Remove block comments
Pattern pattern = Pattern.compile("/\\*.*?\\*/", Pattern.DOTALL);
Matcher matcher = pattern.matcher(line);
return matcher.replaceAll("");
}
private static String[] tokenizeLine(String line) {
String[] tokens = line.split("\\s+ |(?=[\\[\\](){}<>=,;+-/*%|&!])|(?<=[\\[\\](){}<>=,;+-/*%|&!])");
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i].replaceAll("\\s+", "");
if (token.matches("procedure")) {
tokens[i] = "PROC";
} else if (token.matches("int")) {
tokens[i] = "INT";
} else if (token.matches("[0-9]+")) {
// Integer constant
tokens[i] = "INT_CONST";
} else if (token.matches("[(]")) {
tokens[i] = "LP";
} else if (token.matches("[)]")) {
tokens[i] = "RP";
} else if (token.matches("\".*\"")) {
// String constant
tokens[i] = "STR_CONST";
} else if (token.matches("String") || token.matches("string")) {
// String keyword
tokens[i] = "STR";
} else if (token.matches("if")) {
tokens[i] = "IF";
} else if (token.matches("for")) {
tokens[i] = "FOR";
} else if (token.matches("while")) {
tokens[i] = "WHILE";
} else if (token.matches("return")) {
tokens[i] = "RETURN";
} else if (token.matches("[;]")) {
tokens[i] = "SEMI";
} else if (token.matches("do")) {
tokens[i] = "DO";
} else if (token.matches("break")) {
tokens[i] = "BREAK";
} else if (token.matches("end")) {
tokens[i] = "END";
} else if (token.matches("[a-zA-Z][a-zA-Z0-9]*")) {
// Identifier
tokens[i] = "IDENT";
} else if (token.matches("[=]")) {
tokens[i] = "ASSIGN";
} else if (token.matches("[<]")) {
tokens[i] = "LT";
} else if (token.matches("[>]")) {
tokens[i] = "RT";
} else if (token.matches("[++]")) {
tokens[i] = "INC";
} else if (token.matches("[{]")) {
tokens[i] = "RB";
} else if (token.matches("[}]")) {
tokens[i] = "LB";
} else if (token.matches("[*]")) {
tokens[i] = "MUL_OP";
} else if (token.matches("[/]")) {
tokens[i] = "DIV_OP";
} else if (token.matches("[>=]")) {
tokens[i] = "GE";
}
}
return tokens;
}
}
and here is my output.
LP
IDENT
RP
FOR
LP
IDENT
ASSIGN
INT_CONST
SEMI
IDENT
LT
IDENT
SEMI
IDENT
ASSIGN
IDENT
INC
INC
RP
RB
IDENT
ASSIGN
IDENT
MUL_OP
LP
IDENT
DIV_OP
INT_CONST
RP
SEMI
IF
LP
IDENT
RT
ASSIGN
INT_CONST
RP
BREAK
SEMI
LB
IDENT
SEMI
IDENT
IDENT
ASSIGN
STR_CONST
SEMI
SYNTAX ERROR: INVALID IDENTIFIER NAME``
Either remove the empty strings in your tokenizeLine from the returned array before returning, for example by changing the return statement from:
return tokens;
to
return Arrays.stream(tokens).filter(Predicate.not(String::isBlank)).toArray(String[]::new);
or just print the non empty strings in your loop by checking before printing
for (String token : tokens) {
if(!token.isBlank()) {
System.out.println(token);
}
}
Related
I need to get the values of the userparameters attribute. I use this code to connect to ldap, and with filters get the information I need. The problem is that userparameters contains values of several types, and you can not get them in the usual way, otherwise you will see this:
{userparameters=userParameters: PCtxCfgPresent????CtxCfgFlags1????CtxShadow????.CtxMaxDisconnectionTime????CtxMaxIdleTime????*CtxMinEncryptionLevel?
In this question in c #, the solution to my problem is described, IADsTSUserEx saves considerable time and makes the code less. Is there a similar solution on java? After much searching, I did not find anything. Thank you.
I finally managed to get my piece of Java code running to fulfill this need.
It's a direct port from this Powershell script : https://gist.github.com/HarmJ0y/08ee1824aa555598cff5efa4c5c96cf0
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.directory.Attribute;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.PagedResultsControl;
import javax.naming.ldap.PagedResultsResponseControl;
public class LDAP {
public static void main(String[] args) {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
InitialLdapContext ldapContext = null;
Hashtable ldapEnv = new Hashtable(11);
ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
ldapEnv.put(Context.PROVIDER_URL, "ldaps://HOST:636");
ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
ldapEnv.put(Context.SECURITY_PROTOCOL, "ssl");
ldapEnv.put(Context.SECURITY_PRINCIPAL, "ADMIN");
ldapEnv.put(Context.SECURITY_CREDENTIALS, "PASSWORD");
ldapEnv.put("java.naming.ldap.attributes.binary", "objectGUID");
byte[] cookie = null;
String baseName = "BASENAME";
try {
ldapContext = new InitialLdapContext(ldapEnv, new Control[] { new PagedResultsControl(1, Control.NONCRITICAL) });
SearchControls ctls = new SearchControls();
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
ctls.setCountLimit(1);
String[] attrs = new String[] { "objectGUID", "cn", "userParameters" };
ctls.setReturningAttributes(attrs);
NamingEnumeration<SearchResult> e = ldapContext.search(baseName, "(&(objectclass=user)(cn=USERCN))", ctls);
if (e.hasMore()) {
SearchResult sr = e.next();
Attribute attr = sr.getAttributes().get("cn");
if (attr.get() != null) {
NamingEnumeration<?> neAttr = attr.getAll();
while (neAttr.hasMoreElements()) {
String val = neAttr.next().toString();
System.out.println(val);
}
}
attr = sr.getAttributes().get("userParameters");
if (attr.get() != null) {
NamingEnumeration<?> neAttr = attr.getAll();
while (neAttr.hasMoreElements()) {
String v = neAttr.next().toString();
System.out.println("-------------");
byte[] val = v.getBytes(StandardCharsets.UTF_16LE);
ByteBuffer buffer = ByteBuffer.wrap(val);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.position(96);
char signature = buffer.getChar();
System.out.println("Signature : " + signature);
if (signature == 'P') {
int nbAttrs = (int) buffer.getChar();
System.out.println("nbAttrs : " + nbAttrs);
for (int i = 0; i < nbAttrs; i++) {
System.out.println("\n---- Attribute " + i + " ----");
int nameLength = (int) buffer.getChar();
System.out.println("nameLength : " + nameLength);
int valueLength = (int) buffer.getChar();
System.out.println("valueLength : " + valueLength);
int type = (int) buffer.getChar();
System.out.println("type : " + type);
byte[] attrNameTab = new byte[nameLength];
buffer.get(attrNameTab);
String attrName = new String(attrNameTab, StandardCharsets.UTF_16LE);
System.out.println("attrName : " + attrName);
byte[] attrValue = new byte[valueLength];
buffer.get(attrValue);
if (attrName.matches("CtxCfgPresent|CtxCfgFlags1|CtxCallBack|CtxKeyboardLayout|CtxMinEncryptionLevel|CtxNWLogonServer|CtxMaxConnectionTime|CtxMaxDisconnectionTime|CtxMaxIdleTime|CtxShadow")) {
String valueStr = "";
for (byte b : attrValue) {
valueStr += (char) b;
}
Integer valueInt = Integer.parseUnsignedInt(valueStr, 16);
System.out.println("attrValue : " + valueInt);
if (attrName.matches("CtxShadow")) {
switch (valueInt) {
case 0x0:
System.out.println(" -> Disable");
break;
case 0x1000000:
System.out.println(" -> EnableInputNotify");
break;
case 0x2000000:
System.out.println(" -> EnableInputNoNotify");
break;
case 0x3000000:
System.out.println(" -> EnableNoInputNotify");
break;
case 0x4000000:
System.out.println(" -> EnableNoInputNoNotify");
break;
}
} else if (attrName.matches("CtxCfgFlags1")) {
// this field is represented as a bitmask
for (CtxCfgFlagsBitValues en : CtxCfgFlagsBitValues.values()) {
if (en.isBit(valueInt)) {
System.out.println(" -> " + en.name());
}
}
} else if (attrName.matches("CtxMaxConnectionTime|CtxMaxDisconnectionTime|CtxMaxIdleTime")) {
for (CtxCfgFlagsTimeValues en : CtxCfgFlagsTimeValues.values()) {
if (en.getValue() == valueInt.intValue()) {
System.out.println(" -> " + en.name());
}
}
}
} else if (attrName.matches("CtxWFHomeDirDrive.*|CtxWFHomeDir.*|CtxWFHomeDrive.*|CtxInitialProgram.*|CtxWFProfilePath.*|CtxWorkDirectory.*|CtxCallbackNumber.*")) {
String str = new String(attrValue, StandardCharsets.US_ASCII);
String valueStr = convertHexToString(str);
valueStr = valueStr.substring(0, valueStr.length() - 1);
if (attrName.matches(".*W$")) {
// handle wide strings
valueStr = new String(new String(valueStr.getBytes(), StandardCharsets.US_ASCII).getBytes(),StandardCharsets.UTF_16LE);
valueStr = valueStr.substring(0, valueStr.length() - 1);
}
System.out.println("attrValue : " + valueStr);
}
}
}
}
}
Control[] controls = ldapContext.getResponseControls();
if (controls != null) {
for (int i = 0; i < controls.length; i++) {
if (controls[i] instanceof PagedResultsResponseControl) {
PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
cookie = prrc.getCookie();
} else {
// Handle other response controls (if any)
}
}
}
ldapContext.setRequestControls(new Control[] { new PagedResultsControl(1, cookie, Control.CRITICAL) });
}
while (cookie != null);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ldapContext != null) {
try {
ldapContext.close();
} catch (Exception e1) {
}
}
}
}
public static String convertHexToString(String hex) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hex.length() - 1; i += 2) {
// grab the hex in pairs
String output = hex.substring(i, (i + 2));
// convert hex to decimal
int decimal = Integer.parseInt(output, 16);
// convert the decimal to character
sb.append((char) decimal);
}
return sb.toString();
}
private static enum CtxCfgFlagsBitValues {
INHERITCALLBACK(0x08000000),
INHERITCALLBACKNUMBER(0x04000000),
INHERITSHADOW(0x02000000),
INHERITMAXSESSIONTIME(0x01000000),
INHERITMAXDISCONNECTIONTIME(0x00800000),
INHERITMAXIDLETIME(0x00400000),
INHERITAUTOCLIENT(0x00200000),
INHERITSECURITY(0x00100000),
PROMPTFORPASSWORD(0x00080000),
RESETBROKEN(0x00040000),
RECONNECTSAME(0x00020000),
LOGONDISABLED(0x00010000),
AUTOCLIENTDRIVES(0x00008000),
AUTOCLIENTLPTS(0x00004000),
FORCECLIENTLPTDEF(0x00002000),
DISABLEENCRYPTION(0x00001000),
HOMEDIRECTORYMAPROOT(0x00000800),
USEDEFAULTGINA(0x00000400),
DISABLECPM(0x00000200),
DISABLECDM(0x00000100),
DISABLECCM(0x00000080),
DISABLELPT(0x00000040),
DISABLECLIP(0x00000020),
DISABLEEXE(0x00000010),
WALLPAPERDISABLED(0x00000008),
DISABLECAM(0x00000004);
private int mask;
CtxCfgFlagsBitValues(int mask) {
this.mask = mask;
}
public boolean isBit(int val) {
return ((val & mask) == mask);
}
}
private static enum CtxCfgFlagsTimeValues {
ONE_MINUTE(1625948160),
FIVE_MINUTES(-527236096),
TEN_MINUTES(-1071183616),
FIFTEEN_MINUTES(-1598354176),
THIRTY_MINUTES(1081547520),
ONE_HOUR(-2131872256),
TWO_HOURS(14511360),
THREE_HOURS(-2134137856),
ONE_DAY(6039045),
TWO_DAYS(12078090);
private int value;
CtxCfgFlagsTimeValues(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
}
I have the following code to allow the special character :
public static String replacer1(StringBuffer outBuffer) {
String data = "";
StringBuffer tempBuffer = null;
try {
if (outBuffer != null) {
data = outBuffer.toString();
tempBuffer = new StringBuffer();
int incrementor = 0;
int dataLength = data.length();
while (incrementor < dataLength) {
char charecterAt = data.charAt(incrementor);
if (charecterAt == '%') {
tempBuffer.append("<percentage>");
} else if (charecterAt == '+') {
tempBuffer.append("<plus>");
}else if (charecterAt == '-') {
tempBuffer.append("<hyphen>");
} else if (charecterAt == '&') {
tempBuffer.append("<AMPERSAND>");
} else if (charecterAt == '_') {
tempBuffer.append("<UNDERSCORE>");
}
else {
tempBuffer.append(charecterAt);
}
incrementor++;
}
data = tempBuffer.toString();
data = URLDecoder.decode(data, "utf-8");
data = data.replaceAll("<percentage>", "%");
data = data.replaceAll("<plus>", "+");
data = data.replaceAll("<hyphen>", "-");
data = data.replaceAll("<AMPERSAND>", "&");
data = data.replaceAll("<UNDERSCORE>", "_");
//data = data.replaceAll("\"", "");
data = data.replaceAll("'", "");
data = data.trim();
}
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
all the special charcters are comming except '&'.
IS there any other way?
Please help
I have a .txt called readings, it has the following data in it:
-10,3NW,15cm,4:38
5,15SW,8mm,2:8
8,8ENE,2mm,:25
-5,0,7cm,1
-3,0,3mm
Where the first position represents the Temperature, speed, precipitation and time(hours and minutes)
I want to split the string with tokens = line.split(":"); only if the fourth token exists.
My code for splitting the string without doing any splits with the delimiter : is:
try {
input = new BufferedReader(new FileReader("readings.txt"));
line = input.readLine();
while (line != null ) {
tokens = line.split(",");
temperature = Integer.parseInt(tokens[0].trim());
tokens[1] = tokens[1].trim();
separation = firstNonNumericPosition(tokens[1]);
if (separation == 0 || (separation < 0 && Integer.parseInt(tokens[1]) != 0)) {
speed = -1;
} else {
if (separation < 0) {
speed = 0;
direction = "";
} else {
numeric = tokens[1].substring(0, separation);
speed = Integer.parseInt(numeric.trim());
direction = tokens[1].substring(separation).trim();
}
if (tokens.length > 2) {
tokens[2] = tokens[2].trim();
separation = firstNonNumericPosition(tokens[2]);
if (separation <= 0) {
precipitation = -1;
} else {
numeric = tokens[2].substring(0, separation);
precipitation = Integer.parseInt(numeric.trim());
unit = tokens[2].substring(separation).trim();
}
} else {
precipitation = 0;
unit = "";
}
}
if (speed < 0 || precipitation < 0) {
System.out.println("Error in input: " + line);
} else {
readings[size] = new Reading(temperature, speed, direction,
precipitation, unit.equalsIgnoreCase("cm"));
size++;
}
line = input.readLine();
}
input.close();
} catch (NumberFormatException ex) {
System.out.println(ex.getMessage());
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
} catch (ArrayIndexOutOfBoundsException ar){
System.out.println(ar.getMessage());
}
I tried using this logic but it gave an ArrayIndexOutOfBoundException of 3.
if(tokens.length > 3) {
tokens = line.split(":");
hours =Integer.parseInt(tokens[3].trim());
minutes =Integer.parseInt(tokens[4].trim());
}
How is it possible to split it if the fourth token exists?
These are just parts of my code, any further explanation on what the question means(in case I'm not clear enough) could be provided. Thanks in advance!
Use StringTokenizer class. Much easier to handle tokens.
StringTokenizer tokens = new StringTokenizer(line,":");
You can easily check :
string firstToken = tokens.nextToken(); //capture out first token
if(tokens.hasMoreTokens()){ //check if 2nd token is there
StringTokenizer subTokens = new StringTokenizer(firstToken, ",");
}
if(tokens.length > 3) {
tokens = line.split(":");
hours =Integer.parseInt(tokens[3].trim());
minutes =Integer.parseInt(tokens[4].trim());
}
I think you meant to write something like this:
if (tokens.length > 3) {
String[] time = tokens[3].split(":");
String hoursString = time[0];
if (hoursString.length() > 0) {
hours = Integer.parseInt(hoursString);
}
if (time.length > 1) {
minutes = Integer.parseInt(time[1]);
}
}
I have written a multithreaded application that analyzes rows in a database with regex and updates them appropriately. I am writing each row to a log file for logging purposes. I have noticed that the same row is being written to the log file several times...sometimes upwards of 15 times. Here are snippets of the code.
Setting up ThreadPoolExecuter:
private static BlockingQueue<Runnable> worksQueue = new ArrayBlockingQueue<Runnable>(blockingQueueSize);
private static ThreadPoolExecutor exec = new ThreadPoolExecutor(threadPoolSize, threadPoolSize, 10, TimeUnit.SECONDS, worksQueue);
In this part, I run a query, then go through the results:
rs = ps.executeQuery();
while (rs.next()) {
exec.execute(new UpdateMember(rs, conn, fileWriter));
if (worksQueue.size() == blockingQueueSize) {
//reach the maximum, stop refill
for (;;) {
Thread.yield();
//wait until the size of queue reached the minimum
if (worksQueue.size() == 0) {
//start refill
break;
}
}
}
}
UpdateMember (with only run and writeToLog methods showing):
public class UpdateMember implements Runnable {
ResultSet rs;
Connection conn;
FileWriter fw;
public UpdateMember(ResultSet rs, Connection conn, FileWriter fw) {
this.rs = rs;
this.conn = conn;
this.fw = fw;
}
#Override
public void run() {
try {
String regex = "((?<city>[a-zA-Z\\s\\.]+)\\s)?(?<provState>AB|ALB|Alta|alberta|BC|B\\.C\\.|British Columbia|LB|Labrador|MB|Man|Manitoba|N[BLTSU]|Nfld|NF|Newfoundland|NWT|Northwest Territories|Nova Scotia|New Brunswick|Nunavut|ON|ONT|Ontario|PE|PEI|Prince Edward Island|QC|PC|QUE|QU|Quebec|SK|Sask|Saskatchewan|YT|Yukon|Yukon Territories)(\\s(?<country>CA|CAN|CANADA))?$";
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
BigDecimal memrecno = rs.getBigDecimal(2);
String addressLineTwo = rs.getString(4);
String addressLineThree = rs.getString(5);
String addressLineFour = rs.getString(6);
BigDecimal attrrecno = rs.getBigDecimal(9);
String addressBeingParsed = "";
String city = null;
String province = null;
String country = null;
boolean usingAddressThree = false;
boolean usingAddressFour = false;
if (addressLineFour == null) {
if (addressLineThree == null) {
city = "Unknown";
}
else
{
addressBeingParsed = addressLineThree;
usingAddressThree = true;
}
}
else
{
addressBeingParsed = addressLineFour;
usingAddressFour = true;
}
if (usingAddressThree || usingAddressFour) {
Matcher matcher = pattern.matcher(addressBeingParsed);
// if matches are found
if (matcher.matches()) {
city = matcher.group("city");
province = matcher.group("provState");
country = matcher.group("country");
if (city == null || city.isEmpty()) {
// cities are alpha characters and spaces only
String cityRegex = "(?<city>^[a-zA-Z\\s\\.]+$)";
Pattern cityPattern = Pattern.compile(cityRegex, Pattern.CASE_INSENSITIVE);
if (usingAddressFour && (addressLineThree != null) && !addressLineThree.isEmpty()) {
Matcher cityMatcher = cityPattern.matcher(addressLineThree);
if (cityMatcher.matches()) {
city = cityMatcher.group("city");
}
else
{
city = "Unknown";
}
}
else if (usingAddressThree && (addressLineTwo != null) && !addressLineTwo.isEmpty()) {
Matcher cityMatcher = cityPattern.matcher(addressLineTwo);
if (cityMatcher.matches()) {
city = cityMatcher.group("city");
}
else
{
city = "Unknown";
}
}
else
{
city = "Unknown";
}
}
if (province != null && !province.isEmpty()) {
province = createProvinceCode(province);
}
}
else
{
city = "Unknown";
}
}
// update attributes in database
boolean success = updateRow(memrecno, attrrecno, city, province);
String logLine = memrecno.toString() + "|" + attrrecno.toString() + "|" + addressLineTwo + "|" + addressLineThree + "|" + addressLineFour + "|" + city + "|" + province + "|" + country + "|" + success + "|" + String.valueOf(Thread.currentThread().getId());
writeToLog(logLine);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private synchronized void writeToLog(String line) {
try {
fw.write(line + "\r\n");
fw.flush();
}
catch (IOException ex)
{
System.out.println("Error writing to log file. " + ex.getMessage());
}
}
}
I don't know if the threads are also calling the updateRow method multiple times, but I'm assuming they are and that's really bad.
Any ideas as to why it would be doing this?
I don't think ResultSet is thread safe. From your code, you should get the value first and then pass the value instead of rs into the thread.
I am trying to convert an expression from infix to postfix. I've tried debugging the code but I keep getting null pointer exception when the variable is popped. The input for which I get the error is :
(=> (NOT (award)) (badgrade))
The output after I get the error is (NOT award)
Please tell me if need to edit the Q to post lesser code/ add more comments/ provide any more information. Thanks!
public class toInfix1 {
Stack<String> symbol = new Stack<String>();
Stack<String> variable = new Stack<String>();
Stack<String> operator = new Stack<String>();
static String inputfile = "kb2.txt";
ArrayList<String> infix = new ArrayList<String>();
public void toPrefix1() {
try {
File f = new File(inputfile);
FileReader fr = new FileReader(f);
BufferedReader bf = new BufferedReader(fr);
String str;
String kb = "";
while ((str = bf.readLine()) != null) {
Pattern pattern = Pattern.compile("[(]|[)]|<=>|=>|\\w+|^\\s+");
Matcher m = pattern.matcher(str);
//int a = 0;
System.out.println("KB" + kb);
while (m.find()) {
String node1 = m.group();
System.out.println("Node1" + node1);
//If (
if (node1.equals("(")) {
symbol.push(node1);
} else if (node1.equals("OR") || node1.equals("AND")
|| node1.equals("NOT") || node1.equals("=>")
|| node1.equals("<=>")) {
operator.push(node1);
//If )
} else if (node1.equals(")")) {
//Pop symbol (
if(!variable.empty()&& !operator.empty() && !symbol.empty()){
String symbol1 = "", op = "";
if (symbol.peek() != null && !symbol.empty()) {
symbol1 = symbol.pop();
}
//Pop if operator AND OR => <=> (Binary)
if (operator.peek() != null && !operator.empty()) {
op = operator.pop();
if (op.equals("AND") || op.equals("OR")
|| op.equals("=>") || op.equals("<=>")) {
String var2 = "";
String var1 = "";
if (variable.peek() != null && !variable.empty()) {
var1 = variable.pop();
}//Error occurs in the following if condition
if (variable.peek() != null && !variable.empty()) {
var2 = variable.pop();
}
kb = "(" + var1 + op + var2 + ")";
variable.push(kb);
//Pop if operator NOT (Unary)
} else if (op.equals("NOT")) {
String var1 = "";
if (variable.peek() != null && !variable.empty()) {
var1 = variable.pop();
}
kb = "(" + op + var1 + ")";
variable.push(kb);
//No operator after popping )
}
}
}
//If there are no operators
} else {
variable.push(node1);
}
}
}
fr.close();
} catch (Exception e) {
System.err.println("Error thrown" + e.getMessage());
}
}
public static void main(String[] args) {
System.out.println("In new file");
toInfix1 inf1 = new toInfix1();
inf1.toPrefix1();
System.out.println("Completed");
}
}
I was trying to access an element which was null at variable.peek(). removing all peek conditions, will make the program work.