import java.util.Scanner;
import java.util.*;
public class bracketMatch {
public bracketMatch() {
}
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("enter seq");
String[] seq = scan.nextLine().split("");
ArrayList<String> temp = new ArrayList<>();
int x = 0;
String check = null;
System.out.println(Arrays.toString(seq));
for(String brak : seq)
{
switch(brak)
{
case "(":
temp.add("(");
break;
case "[":
temp.add("[");
break;
case "{":
temp.add("{");
break;
case "<":
temp.add("<");
break;
case ")":
temp.add( ")");
break;
case "]":
temp.add("]");
break;
case "}":
temp.add("}");
break;
case ">":
temp.add(">");
break;
}
}
x = temp.lastIndexOf("(");
System.out.println( x);
/* if(x != -1)
{
temp.remove(check);
temp.remove(x);
}*/
System.out.println(temp.toString()) ;
}
}
The above code is for matchingbrackets, but I stumbled upon ArrayList
method lastIndexOf
.
However, it is not fetching the correct index and is working like indexOf
method.
Should I use stack or linkedlist
instead of ArrayList
?
Also, any help on iterating an arraylist and removing its element, since iterator and foreach gives error.
Can you give us some more information? Method lastIndexOf works properly, it gives you last occurence of object in list, it doesn't work like indexOf. If you want to delete last occurence of "(" from arraylist just uncomment your temp.remove(x) line.