Reputation: 9
import java.util.Scanner;
public class CashSplitter {
public static void main(String[] args) {
Scanner S = new Scanner(System.in);
System.out.println("Cash Values");
String i = S.nextLine();
for(int b = 0;b<i.length(); b ++){
System.out.println(b);
System.out.println(i.substring(0,i.indexOf('.')+3));
i.replace(i.substring(0, i.indexOf('.') + 3), "");
System.out.println(i);
System.out.println(i.substring(0, i.indexOf('.') + 3));
}
}
}
The code should be able to take a string with multiple cash values and split them up, into individual values. For example 7.32869.32 should split out 7.32, 869.32 etc
Upvotes: 0
Views: 65
Reputation: 726479
There are several problems with your code:
replace
without assigning back to the string,For the last point, if you start with 2.222.222.22
, you would get only one cash value instead of three, because replace
would drop all three matches.
Java offers a nice way of splitting a String
on a regex:
String[] parts = S.split("(?<=[.]..)")
The regex is a look-behind that expects a dot followed by any two characters.
Upvotes: 1
Reputation: 44813
A string is immutable, therefore replace returns a new String for you to use
try
i = i.replace(i.substring(0, i.indexOf('.') + 3), "");
Although try using
https://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html
Upvotes: 1