1

I am trying to create two separate strings from one string around a delimiter using split. However it keeps telling me I am going out of bounds. The book I am reading uses this example:

reads: 3/4 or something

String currentFraction = fractionReader.nextLine();
String numHolder = currentFraction.split("/")[0];
String denHolder = currentFraction.split("/")[1]; 

When I try my own such as :

reading: 5.93

String moneyHolder = moneyReader.nextLine();
String dolHolder = moneyHolder.split(".")[0];
String centHolder = moneyHolder.split(".")[1];

I am guessing I have to make an array and then split it? All the examples I see online are for each loops printing stuff out. So how would I catch the left and right of the split into two strings?

  • Could you post a stack trace for the crash? – Epiglottal Axolotl Apr 19 '14 at 22:04
  • java.lang.ArrayIndexOutOfBoundsException: 0 at Money.add(Money.java:273) at Lab2Driver.moneyDriver(Lab2Driver.java:190) at Lab2Driver.main(Lab2Driver.java:30) Sorry I am new to comp sci – Peter Steuber Apr 19 '14 at 22:06
  • It is, Sorry that did not show up at all in my searches. The book did not say what I had to escape or not I suppose, let me find and replace to double check – Peter Steuber Apr 19 '14 at 22:09

1 Answers1

3

In split method the pattern is regex. So dot means "any character" and split is done by any character. Try escaping this like this:

String moneyHolder = moneyReader.nextLine();
String dolHolder = moneyHolder.split("\\.")[0];
String centHolder = moneyHolder.split("\\.")[1];
bartektartanus
  • 15,284
  • 6
  • 74
  • 102