0
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

2 Answers 2

1

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

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

1 Comment

More information about immutability in java here.
1

There are several problems with your code:

  • You want to add two, not three, to the index of the decimal point,
  • You cannot use replace without assigning back to the string,
  • Your code assumes that there are no identical cash values.

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("(?<=[.]..)") 

Demo.

The regex is a look-behind that expects a dot followed by any two characters.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.