0

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 ); } } 

3 Answers 3

6

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.

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

2 Comments

Ahh. So that simply creates a new string with 8's as 2's and reassigns it to number?
Works perfectly and makes great sense! Thank you so much and I am pleased to know it is a common mistake =x
2

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

Comments

0

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.

1 Comment

Another user answered first but it does really help! Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.