My World Rules
My World Rules

Reputation: 9

String.replace isn't working

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

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

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.

Upvotes: 1

Scary Wombat
Scary Wombat

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

Related Questions