Thaddius Naups
Thaddius Naups

Reputation: 3

String replace function not replacing characters correctly - Java

I am trying to replace a specific character '8' with a '2' in a string. I think I have everything set up correctly and when I look online for examples, this looks like it should. When I print the string though, it is just as I entered it. To run it, test it with "80802" or some similar input. Thanks!

import java.util.Scanner;

class PhoneNumber {

    public static void main(String[] args) {

        String number = null;

        Scanner scan = new Scanner(System.in);

        // Prompt the user for a telephone number
        System.out.print("Enter your telephone number: ");

        // Input the user's name
        number = scan.nextLine();

        // Replace the relevant letters with numbers
        number.replace('8', '2');

        System.out.println("Your number is: " + number );

    }
}

Upvotes: 0

Views: 1907

Answers (3)

user847229
user847229

Reputation: 55

number.replace('8','2'); returns the correct string it does not modify number. To get your desired functionality you must type number = number.replace('8','2');

public static void main(String[] args) {

    String number = null;

    Scanner scan = new Scanner(System.in);

    // Prompt the user for a telephone number
    System.out.print("Enter your telephone number: ");

    // Input the user's name
    number = scan.nextLine();

    // Replace the relevant letters with numbers
    number = number.replace('8', '2');

    System.out.println("Your number is: " + number );

}

Hope this helps.

Upvotes: 0

Bohemian
Bohemian

Reputation: 424973

A common mistake... You want:

    number = number.replace('8', '2');

String.replace() doesn't change the String, because Strings are immutable (they can not be changed). Instead, such methods return a new String with the calculated value.

Upvotes: 6

Ray Toal
Ray Toal

Reputation: 88378

number.replace() returns a new string. It does not change `number'.

Upvotes: 2

Related Questions