0

I am trying to put a String into an array so I can print the tokens in a different order to how they are in the original file which I am reading from.

Below is the code I have so far, I have also included the input file I am reading from. What I would like to be able to do is print one word from the original file; system.out.println(tokens[4]); Which would print 'Species'

import java.util.Scanner;

public class inClassTest4Time {

  public static void main(String[] args) {

Scanner scan = new  
Scanner(inClassTest4Time.class.getResourcesAsStream("pet.txt"));
String line;
String[] tokens;
    while (scan.hasNextLine()) 
    {
        line = (scan.nextLine());
        tokens = line.split("//s");
        for (int i = 0; i < tokens.length; i++) {
            System.out.println(tokens[i]);

        }

    }


}
}

Input File:

Pet
===================
- species : String
+ isChipped : boolean
- name : String
- age : int
===================
+ Pet ( String name )
===================
0

1 Answer 1

2

I think you meant to put \\s instead of //s. //s is actually splitting based on the literal string //s (ie no escaping). Since none of your strings have that, there is no split. I suspect that if you do tokens[2] you will get - species : String.

Sign up to request clarification or add additional context in comments.

2 Comments

Ive changed it, i get the below output if i put system.out.println(tokens[4]); I get this output: Pet Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at InClassTest4.inClassTest4Time.main(inClassTest4Time.java:19) Java Result: 1
Yes, that's because in Java arrays are zero based, so for four tokens you would get token index 0, 1, 2 and 3.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.