【问题标题】:ArrayList lastIndexofArrayList lastIndexof
【发布时间】:2020-07-21 19:05:33
【问题描述】:
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()) ;

    }

}

上面的代码是用来匹配括号的,但是我偶然发现了ArrayList方法lastIndexOf
但是,它没有获取正确的索引,并且像 indexOf 方法一样工作。

我应该使用堆栈还是linkedlist 而不是ArrayList

此外,任何关于迭代数组列表和删除其元素的帮助,因为迭代器和 foreach 会出错。

【问题讨论】:

  • 你好,你能举一个你的代码应该做什么的例子吗?

标签: java arraylist compiler-errors iterator lastindexof


【解决方案1】:

你能给我们更多的信息吗?方法 lastIndexOf 工作正常,它为您提供列表中最后一次出现的对象,它不像 indexOf 那样工作。如果你想从 arraylist 中删除最后出现的“(”,只需取消注释你的 temp.remove(x) 行。

【讨论】:

  • 乐于助人。如果是这样,请将问题标记为已解决,有可能有人会做类似的事情并且可以找到这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-03
  • 2012-10-10
  • 1970-01-01
  • 2015-03-24
  • 2014-02-18
  • 2020-03-30
  • 1970-01-01
相关资源
最近更新 更多