Building a string recursively in Java - java

I am trying to build a string recursively but it isn't quite working
my code looks like this
public void UpdatePrintList(ArrayList<Node> closedList, ArrayList<Node> openList)
{
if(count <= iterations)
{
String line1 = "";
for(int i = 0; i < closedList.size(); i++)
{
if(i > 0)
{
line1 = line1 + "-";
}
line1 = line1 + closedList.get(i).GetMovement();
}
line1 = line1 + " " + closedList.get(closedList.size()-1).GetG() + " " + closedList.get(closedList.size()-1).GetHeuristic() + " " + closedList.get(closedList.size()-1).GetF();
printList.add(line1);
//*****************************************************************
String line2 = "OPEN ";
for(int i = 0; i < openList.size(); i++)
{
line2 = FindEarlierNode(openList.get(i), line2);
}
System.out.println(line2);
}
count++;
}
private String FindEarlierNode(Node varNode, String varString)
{
if(varNode.OpenedBy() == null)
{
varString += varNode.GetMovement() + "-";
}
else
{
FindEarlierNode(varNode.OpenedBy(), varString);
}
varString = varString + varNode.GetMovement() + "-";
return varString;
}
The strange thing is that I know that this if statement
if(varNode.OpenedBy() == null)
{
varString += varNode.GetMovement() + "-";
}
runs correctly, so the function does reach the earliest node. But it doesnt add to the string. The code runs but returns nothing. GetMovement just returns a one or two character string. The output should look like this:
OPEN S-R S-RD S-D
But instead it looks like this:
OPEN D-DL-L-
Can anyone help?

Managed to work it out. This gives me my desired output:
private String FindEarlierNode(Node varNode, String varString)
{
if(varNode.OpenedBy() != null)
{
varString = varString + varNode.GetMovement() + "-";
return FindEarlierNode(varNode.OpenedBy(), varString);
}
return varString += varNode.GetMovement() + " ";
}
thanks everyone.

Related

Remove some text between square brackets in Java 6

Would it be possible to change this:
[quote]user1 posted:
[quote]user2 posted:
Test1
[/quote]
Test2
[/quote]
Test3
to this:
Test3
Using Java 6?
ok, wrote some not regex solution.
String str ="[quote]user1 posted:[quote]user2 posted:Test1[/quote]Test2[/quote]Test3";
String startTag = "[quote]";
String endTag = "[/quote]";
String subStr;
int startTagIndex;
int endTagIndex;
while(str.contains(startTag) || str.contains(endTag)) {
startTagIndex = str.indexOf(startTag);
endTagIndex = str.indexOf(endTag) + endTag.length();
if(!str.contains(startTag)) {
startTagIndex = 0;
}
if(!str.contains(endTag)) {
endTagIndex = startTagIndex + startTag.length();
}
subStr = str.substring(startTagIndex, endTagIndex);;
str = str.replace(subStr, "");
}
I compiled this to Java 8. I don't believe I'm using any features not available in Java 6.
Edited: System.lineSeparator() was added in Java 1.7. I changed the line to
System.getProperty("line.separator").
public class RemoveQuotes {
public static void main(String[] args) {
String input = "[quote]user1 posted:\r\n" +
" [quote]user2 posted:\r\n" +
" Test1\r\n" +
" [/quote]\r\n" +
" Test2\r\n" +
"[/quote]\r\n" +
"Test3";
input = input.replace(System.getProperty("line.separator"), "");
String endQuote = "[/quote]";
int endPosition;
do {
int startPosition = input.indexOf("[quote]");
endPosition = input.lastIndexOf(endQuote);
if (endPosition >= 0) {
String output = input.substring(0, startPosition);
output += input.substring(endPosition + endQuote.length());
input = output;
}
} while (endPosition >= 0);
System.out.println(input);
}
}

Parse string containing javascript

I have a string:
2 + 2 = ${2 + 2}
This is a ${"string"}
This is an object: ${JSON.stringify({a: "B"})}
This should be "<something>": ${{
abc: "def",
cba: {
arr: [
"<something>"
]
}
}.cba.arr[0]}
This should ${"${also work}"}
And after parsing it I should get something like that:
2 + 2 = 4
This is a string
This is an object: {"a":"B"}
This should be "<something>": <something>
This should ${also work}
So I need help implementing it in Java, I simply need to get what is between ${ and }.
I tried using a regular expression: \${(.+?)} but it fails when string inside contains }
So after a bit of testing, I've ended up with this:
ScriptEngine scriptEngine = new ScriptEngineManager(null).getEngineByName("JavaScript");
String str = "2 + 2 = ${2 + 2}\n" +
"This is a ${\"string\"}\n" +
"This is an object: ${JSON.stringify({a: \"B\"})}\n" +
"This should be \"F\": ${var test = {\n" +
" a : {\n" +
" c : \"F\"\n" +
" }\n" +
"};\n" +
"test.a.c\n" +
"}\n" +
"This should ${\"${also work}\"}"; // String to be parsed
StringBuffer result = new StringBuffer();
boolean dollarSign = false;
int bracketsOpen = 0;
int beginIndex = -1;
int lastEndIndex = 0;
char[] chars = str.toCharArray();
for(int i = 0; i < chars.length; i++) { // i is for index
char c = chars[i];
if(dollarSign) {
if(c == '{') {
if(beginIndex == -1) {
beginIndex = i + 1;
}
bracketsOpen++;
} else if(c == '}') {
if(bracketsOpen > 0) {
bracketsOpen--;
}
if(bracketsOpen <= 0) {
int endIndex = i;
String evalResult = ""; // evalResult is the replacement value
try {
evalResult = scriptEngine.eval(str.substring(beginIndex, endIndex)).toString(); // Using script engine as an example; str.substring(beginIndex, endIndex) is used to get string between ${ and }
} catch (ScriptException e) {
e.printStackTrace();
}
result.append(str.substring(lastEndIndex, beginIndex - 2));
result.append(evalResult);
lastEndIndex = endIndex + 1;
dollarSign = false;
beginIndex = -1;
bracketsOpen = 0;
}
} else {
dollarSign = false;
}
} else {
if(c == '$') {
dollarSign = true;
}
}
}
result.append(str.substring(lastEndIndex));
System.out.println(result.toString());

Java Syntax Checker using java.util.stack

I have an assignment with regards to making a Java syntax checker. It is using java.util.stack, and what it's supposed to do is read from a file that's provided and then check for syntax errors. How it is supposed to do this is by adding a 'token' to the stack that has the character, line number, position in the line, whether it's unmatched or unexpected and the line itself.
The code for the function is as follows:
public static boolean check(String Filename, boolean ConsoleOutput) throws FileNotFoundException
{
mFileName = Filename;
mConsoleOutput = ConsoleOutput;
File mFile = new File("src/Kurien/tests/" + mFileName);
Scanner FileReader = new Scanner(mFile);
if(ConsoleOutput)
{
System.out.println("Processing " + "'" + mFileName + "'" + "\n" + "----------------------");
}
while (FileReader.hasNextLine())
{
mLineNumber++;
mLine = FileReader.nextLine();
for (int counter = 0; counter < mLine.length(); counter++)
{
mCharacter = mLine.charAt(counter);
if (mCharacter == '(')
{
mStack.push(new Token(mCharacter, mLineNumber, counter, ErrorDetail.Unmatched, mLine));
}
else if (mCharacter == '{')
{
mStack.push(new Token(mCharacter, mLineNumber, counter, ErrorDetail.Unmatched, mLine));
}
else if (mCharacter == ')')
{
if (mStack.isEmpty())
{
Error = true;
mStack.push(new Token(mCharacter, mLineNumber, counter, ErrorDetail.Unexpected, mLine));
}
else if (mStack.peek().equals('('))
{
mStack.pop();
}
else
{
Error = true;
mStack.push(new Token(mCharacter, mLineNumber, counter, ErrorDetail.Unexpected, mLine));
}
}
else if (mCharacter == '}')
{
if (mStack.isEmpty())
{
Error = true;
mStack.push(new Token(mCharacter, mLineNumber, counter, ErrorDetail.Unexpected, mLine));
}
else if (mStack.peek().equals('{'))
{
mStack.pop();
}
else
{
Error = true;
mStack.push(new Token(mCharacter, mLineNumber, counter, ErrorDetail.Unexpected,mLine));
}
}
}
}
if(!Error)
{
System.out.println("[SUCCESS]");
}
else
{
while(mStack.iterator().hasNext())
{
Token Temp = (Token)mStack.iterator().next();
if(Temp.mDetail == ErrorDetail.Unexpected)
{
System.out.println("[ERROR] " + Temp.mDetail.toString() + " closing token in file '" + mFileName + "'" + " line#" + Temp.mLineNumber);
System.out.println(mLine);
System.out.println(Spaces(Temp.mLine.length() - Temp.mPosition) + "^");
}
else if(Temp.mDetail == ErrorDetail.Unmatched)
{
System.out.println("[ERROR] + " + Temp.mDetail + "token in file '" + mFileName + "'" + "line#" + Temp.mLineNumber);
System.out.println(mLine);
System.out.println(Spaces(Temp.mLine.length() - Temp.mPosition) + "^");
}
}
}
return Error;
}
private static class Token
{
char mCharacter;
int mLineNumber;
int mPosition;
ErrorDetail mDetail;
String mLine;
Token(char Character, int LineNumber, int Position, ErrorDetail Detail, String Line)
{
mCharacter = Character;
mLineNumber = LineNumber;
mPosition = Position;
mDetail = Detail;
mLine = Line;
}
}
}
Now, the expected output for the first test case is as follows:
[ERROR] Unexpected closing token in file 'test1.txt' line#7:
}
^
However all I get is the following:
[ERROR] + Unmatchedtoken in file 'test1.txt'line#1
I know the formatting could be fine tuned, however there is clearly another problem here that I just can't quite put my finger on.

java.lang.ArrayIndexOutOfBoundsException :

I have a String = "abc model 123 abcd1862893007509396 abcd2862893007509404", if I provide space between abcd1 & number eg. abcd1 862893007509396 my code will work fine, but if there is no space like abcd1862893007509396, I will get java.lang.ArrayIndexOutOfBoundsException, please help ?:
PFB the code :
String text = "";
final String suppliedKeyword = "abc model 123 abcd1862893007509396 abcd2862893007509404";
String[] keywordarray = null;
String[] keywordarray2 = null;
String modelname = "";
String[] strIMEI = null;
if ( StringUtils.containsIgnoreCase( suppliedKeyword,"model")) {
keywordarray = suppliedKeyword.split("(?i)model");
if (StringUtils.containsIgnoreCase(keywordarray[1], "abcd")) {
keywordarray2 = keywordarray[1].split("(?i)abcd");
modelname = keywordarray2[0].trim();
if (keywordarray[1].trim().contains(" ")) {
strIMEI = keywordarray[1].split(" ");
for (int i = 0; i < strIMEI.length; i++) {
if (StringUtils.containsIgnoreCase(strIMEI[i],"abcd")) {
text = text + " " + strIMEI[i] + " "
+ strIMEI[i + 1];
System.out.println(text);
}
}
} else {
text = keywordarray2[1];
}
}
}
After looking at your code the only thing i can consider for cause of error is
if (StringUtils.containsIgnoreCase(strIMEI[i],"abcd")) {
text = text + " " + strIMEI[i] + " "
+ strIMEI[i + 1];
System.out.println(text);
}
You are trying to access strIMEI[i+1] which will throw an error if your last element in strIMEI contains "abcd".

Split 2 string and join

I have 2 string which I want to join as per my requirements. Say I have
String sa = {"as,asd,asdf"};
String qw = {"12,123,1234"};
String[] separated = ItemSumm.split(",");
String[] separateds = Itemumm.split(",");
StringBuffer sb = new StringBuffer();
for (int i = 0; i < separateds.length; i++)
{
if (separated.length == i + 1)
{
sb.append(separated[i] + "(" + separateds[i] + ")");
} else
{
sb.append(separated[i] + "(" + separateds[i] + "),");
}
}
deleteListItem.list_summ.setText(sb.toString());
it gives as(12),asd(123),asdf(1234)
But problem is , it can be like
String sa = {"as,asdf"};
String qw = {"12,123,1234"};
So in this I want like
as(12),asdf(123),1234
Try this code :
String sa = {"as,asd"};
String qw = {"12,123,1234"};
String[] separated = ItemSumm.split(",");
String[] separateds = Itemumm.split(",");
StringBuffer sb = new StringBuffer();
for (int i = 0; i < separateds.length; i++) {
if (separated.length == i + 1) {
if(separated.length == i) {
sb.append(separateds[i] + "");
} else {
sb.append(separated[i] + "(" + separateds[i] + ")");
}
} else {
if(separated.length == i) {
sb.append("," + separateds[i]);
} else {
sb.append(separated[i] + "(" + separateds[i] + "),");
}
}
}
deleteListItem.list_summ.setText(sb.toString());
// Answer : as(12),asd(123),1234
String sa = {"as,asd,asdf"};
String qw = {"12,123,1234"};
String[] separated = ItemSumm.split(",");
String[] separateds = Itemumm.split(",");
StringBuffer sb = new StringBuffer();
// first loop through separated, starting with a comma
for (int i = 0; i < separated.length; i++) {
sb.append(",").append(separated[i]).append("(").append(separateds[i]).append(")"));
}
// append remaining items in separateds
for (int i = separated.length; i < separateds.length; i++) {
sb.append(",").append(separateds[i]);
}
deleteListItem.list_summ.setText(sb.toString().substring(1)); // remove starting comma
if the lenghts of the strings are the sa, do the join
if (separated.length == i + 1 && (separated[i].lenght == separateds[i].lenght))

Categories

Resources