4

I have a text file data.txt. I want to input the data into a Hashmap and do some datamapping. When ever I hit the value without dot(). I will get an error

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1

How to I overcome it by skipping those entry without dot(.).

I created a small snippet to illustrate my problem.

  static HashMap<String, String> newList = new HashMap<>();
    public static void main(String[] args) throws FileNotFoundException, IOException {
        String inputFile = "data.txt";
        BufferedReader brInput = new BufferedReader(new FileReader(inputFile));
        String line;

        while ((line = brInput.readLine()) != null) {
            newList.put(line, "x");
        }

        for (Map.Entry<String, String> entry : newList.entrySet()) {

            String getAfterDot = entry.getKey();
            String[] split = getAfterDot.split("\\.");
            String beforeDot = "";
            beforeDot = getAfterDot.substring(0, getAfterDot.lastIndexOf("."));
            System.out.println(beforeDot);
        }

    }

data.txt

0
0.1
0.2
0.3.5.6
0.2.1
2.2

expected result when i print the map(doesnt need to be in order)

0
0
0.3.5
0.2
2

7 Answers 7

11

Use the String method lastIndexOf(int ch).

int lastIndxDot = st.lastIndexOf('.');

st.substring(0, lastIndxDot); will be the substring you want. If it returned -1, then there is no '.' in the string.

EDIT:

for (Map.Entry < String, String > entry: newList.entrySet()) {
    String getAfterDot = entry.getKey();
    int lastIndxDot = getAfterDot.lastIndexOf('.');
    if (lastIndxDot != -1) {
        String beforeDot = getAfterDot.substring(0, lastIndxDot);
        System.out.println(beforeDot);
    }
}
7
  • i still get Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 Commented Mar 24, 2016 at 5:28
  • @newbieprogrammer which line is it on? Commented Mar 24, 2016 at 5:29
  • int lastIndxDot = getAfterDot.lastIndexOf('.'); beforeDot = getAfterDot.substring(0, lastIndxDot); Commented Mar 24, 2016 at 5:29
  • @newbieprogrammer Let me know how it goes Commented Mar 24, 2016 at 5:34
  • this work too but any different from the previous answer ? by checking if line contain . Commented Mar 24, 2016 at 5:37
1

Try this code it should work:

static HashMap < String, String > newList = new HashMap < > (); 
public static void main(String[] args) throws FileNotFoundException, IOException {

    String inputFile = "input";
    BufferedReader brInput = new BufferedReader(new FileReader(inputFile));
    String line = null;

    while ((line = brInput.readLine()) != null) {

        newList.put(line, "x");
    }

    for (Map.Entry < String, String > entry: newList.entrySet()) {

        String getAfterDot = entry.getKey();
        if (getAfterDot.contains(".")) {
            String[] split = getAfterDot.split("\\.");
            String beforeDot = "";
            beforeDot = getAfterDot.substring(0, getAfterDot.lastIndexOf("."));
            System.out.println(beforeDot);
        }
    }

}

I got this output with above code:

0
0
2
0.3.5
0.2
0

You may check to see if the string has a dot before by using getAfterDot.contains(".") before invoking the substring function on the string.

static HashMap<String, String> newList = new HashMap<String, String>();
public static void main(String[] args) throws FileNotFoundException, IOException {
    String inputFile = "data.txt";
    BufferedReader brInput = new BufferedReader(new FileReader(inputFile));
    String line;
    while ((line = brInput.readLine()) != null) {
        newList.put(line, "x");
    }
    for (Map.Entry<String, String> entry : newList.entrySet()) {
        String getAfterDot = entry.getKey();
        String[] split = getAfterDot.split("\\.");
        String beforeDot = "";
        if(getAfterDot.contains(".")){
            beforeDot = getAfterDot.substring(0, getAfterDot.lastIndexOf("."));
            System.out.println(beforeDot);
        }
    }

}
1
  • @newbieprogrammer, for performance, get lastindexOf() and check it if greater than -1 instead of checking with contains() and getting last index after that
    – Nurlan
    Commented Mar 24, 2016 at 9:02
0
    String[] lines = new String[]{"0", "0.1", "0.2", "0.3.5.6", "0.2.1", "2.2"};
    for (String line : lines) {
        int lastIndexOf = line.lastIndexOf(".");
        if (lastIndexOf > -1) {
            line = line.substring(0, lastIndexOf);
            System.out.println(line);
        }
    }
2
  • 1
    where did the array come from? Commented Mar 24, 2016 at 5:46
  • @DebosmitRay, lines is initialized for example, same as your data.txt file content.
    – Nurlan
    Commented Mar 24, 2016 at 8:52
0

One option would be to use String.replaceAll() with a regex which extracts out the portion of the string coming before the period (if the period exists).

for (Map.Entry<String, String> entry : newList.entrySet()) {
    String getAfterDot = entry.getKey();
    String beforeDot = getAfterDot.replaceAll("(.*)\\..*", "$1");
    System.out.println(beforeDot);
}
2
  • Thought I'd point this out if you overlooked. lastIndexOf actually returns -1 if the character is not found. So, you dont have to make a repeat iteration by calling contains. Just thought I would let you know. Commented Mar 24, 2016 at 5:39
  • @DebosmitRay Please review my updated answer, thanks. Commented Mar 24, 2016 at 5:45
0

If you are fine with using libraries, you don't need to re-invent the wheel:

beforeDot = StringUtils.substringBeforeLast(getAfterDot, ":");

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#substringBeforeLast-java.lang.String-java.lang.String-

-2

I just thought I would point that this can be done in a single line of code:

foo.substringAfterLast(".")
1

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.