IndexOutOfBounds错误Java,带有构造函数,方法,数组列表和对象

时间:2019-01-23 01:21:06

标签: java indexoutofboundsexception

编写一个名为SameEnds的类。编写SameEndsTester来测试您的课程。 SameEnds确定array list在左边和结尾是否具有相同的数字序列,如果是,则确定该序列有多长。 您不会提示用户输入数据。通过SameEnds中的SameEndsTester构造函数输入测试数据。您可以假设array list中的所有元素都是整数。

For example, the array list
1 4 9 10 11 12 1 4 9

在左侧和右侧具有相同的序列1 4 9,并且具有length 3。因此,您的SameEndsTester将打印出“The longest sequence is 1 4 9, and the sequence length is 3”。 如果arraylist左右没有共同的序列,例如

1 4 9 16 25

SameEndsTester应该打印出“没有共同的序列”。 这两个序列不能重叠。例如,在数组

1 1 1 1

序列1 1出现在左侧和右侧,您的方法应返回“The longest sequence is 1 1, and the sequence length is 2”

To view the question and see the work easier or see it down below

import java.util.ArrayList;
import java.util.Scanner;

public class SameEnds {
    Scanner scan = new Scanner(System.in);
    private ArrayList<Integer> nums; // for list of names

    public SameEnds(ArrayList<Integer> nums) {
        this.nums = nums;
    }

    public void testEnds() {
        String data = "";
        for (int i = 0; i < nums.size(); i++)
            if (nums.get(i) == nums.get(nums.size() - i))
                data += nums.get(i) + " ";
        System.out.println("The longest sequence is + " + data);
    }

    @Override
    public String toString() {
        return "SameEnds [nums=" + nums + "]";
    }

}

import java.util.ArrayList;

public class SameEndsTester {

public static void main(String[] args) {
    //  int [] inta = {1,2,3,4,1,2};
        ArrayList<Integer> ali = new ArrayList<Integer>();
        ali.add(1);
        ali.add(2);
        ali.add(3);
        ali.add(4);
        ali.add(1);
        ali.add(2);
        SameEnds typeNum = new SameEnds(ali);
        typeNum.testEnds();
        System.out.print(typeNum);

        }
    }

IndexOutOfBoundsException Image

请帮助我解决这个具体问题和整个问题。

2 个答案:

答案 0 :(得分:0)

由于

IndexOutOfBounds异常即将到来
nums.get(nums.size() - i) // When i = 0

将其更改为以下代码即可解决:

nums.get(nums.size() - (i + 1))

答案 1 :(得分:0)

使用字符串和流会有所帮助。

这应该有效:

public ArrayList<Integer> findLongestPrefixSameAsPostfix(){

    String asString = String.join("", nums.stream().map(num -> num.toString()).toArray(String[]::new));

    String prefix = "";
    for(int i = 0 ; i < nums.size() ; i++){
        prefix = asString.substring(0, i);
        if(!asString.endsWith(prefix)){
            break;
        }
    }

    return nums.subList(0, prefix.length());
}