0

I try several times to convert the text in a File into List and print some elements of the List according to reference index but I can't, it throws IndexOutOfBounds Exception: index 3 , Size 1

is there any possible way to overcome the situation.

myTEXT.txt

BUK,2023,IS,COMMING

my Code

List<String> TexttoList = new ArrayList<String>();
    
    FileReader scores = new FileReader("myTEXT.txt");
    
    Scanner scanText = new Scanner(myTEXT);
    scanText.useDelimiter(",\\s*");
    
    while(scanText.hasNext()) {
        
        
        for(int d = 0; d<4; d++){
        TexttoList.add(d , scanText.next());
        System.out.println(TexttoList.get(3));
        //IndexOutOfBounds Exception: index 4 , Size 1
        }
    }
    

it only prints First index(0) and return the entire text

    BUK
    2023
    IS
    COMMING
    
  • 1
    Sure this is your actual code? `B.add(A);` wouldn't compile - it should be `B.addAll(A);`. – Thomas Sep 15 '20 at 11:10
  • Your code won't compile. `B` is an `ArrayList` of `Double` type but you are trying to add another `ArrayList A` in to this `ArrayList`. You probably meant to add the elements of `A` in `B`. You also have a typo in the last line of code: `System.out.Println` – Yousaf Sep 15 '20 at 11:12
  • "Please What is my Problem ?" - have a look at what `==` means for objects (and why you should use `equals()` instead). You should also learn to step through your code with a debugger and have a look at those `if-if-if...` sequences. Finally, your code looks _very_ odd and fragile, what are you trying to achieve? – Thomas Sep 15 '20 at 11:12
  • when i run your code (with little fix like B.addAll(A), or println without capital P ) i have the following result : 2nd 1st 5th 4th 3rd – CLAIN Cyril Sep 15 '20 at 11:16
  • _I run the Code and gives me this output [1st , 2nd , 3rd , 4th , 5th]_ - your code won't compile but if you fix the errors, your code will not produce the output that you are claiming that it produces. – Yousaf Sep 15 '20 at 11:17
  • Yes I want add the Element of A in B – Najibu Tanimu Sep 15 '20 at 12:49
  • So Now how can I achieve the this output [ 1st , 1st , 3rd , 4th , 4th ] in my code – Najibu Tanimu Sep 15 '20 at 12:53

1 Answers1

0

The == operator compares the references. You should use the .equals() function instead to compare the values.

for example, A.get(a).equals(B.get(4))

see this answer for details.

Mubin
  • 130
  • 1
  • 9