javastringstringtokenizer

StringTokeniser not reading data


I've to read data from a file and I've just entered some sample data as a String in StringTokenizer. I can't understand what is wrong with my code here. Can someone please advise?

import java.util.StringTokenizer;

public class rough {

    public static void main(String[] args) throws Exception {
        StringTokenizer itr = new StringTokenizer("PKE2324 02-12-2020 200"
      + "\nMJD432 19-05-2019 150");

        while (itr.hasMoreTokens()){
            String line = itr.nextToken().toString();
            String[] tokens = line.split(" ");
            String[] date = tokens[1].split("-");
            String yr = date[2];
            String reg = tokens[0];
            String regy = new String(reg + " " + yr);
            System.out.println(regy);   
            }
     }

}

I want to get the registration number and year as a String. When I run this, I keep getting ArrayIndexOutofBounds


Solution

  • This is the type of runtime error which has been caused due to logical error and inappropriate delimeter.

    Assuming you want to tokenise the big string using newline character, use, \n as delimeter to StringTokenizer.

    Have a look at the corrected code below which satisfies your use case:

    import java.util.StringTokenizer;
    
    public class rough {
    
        public static void main(String[] args) throws Exception {
            StringTokenizer itr = new StringTokenizer("PKE2324 02-12-2020 200"
        + "\nMJD432 19-05-2019 150", "\n");
    
            while (itr.hasMoreTokens()){
                String line = itr.nextToken().toString();
                String[] tokens = line.split(" ");
                String[] date = tokens[1].split("-");
                String yr = date[2];
                String reg = tokens[0];
                String regy = new String(reg + " " + yr);
                System.out.println(regy);   
                }
        }
    }
    

    Output:

    PKE2324 2020
    MJD432 2019