简体   繁体   English

字符串替换 function 不能正确替换字符 - Java

[英]String replace function not replacing characters correctly - Java

I am trying to replace a specific character '8' with a '2' in a string.我正在尝试用字符串中的“2”替换特定字符“8”。 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.要运行它,请使用“80802”或类似的输入对其进行测试。 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 );

    }
}

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). String.replace()不会更改字符串,因为字符串是不可变的(它们无法更改)。 Instead, such methods return a new String with the calculated value.相反,这些方法返回一个带有计算值的新字符串。

number.replace() returns a new string. number.replace()返回一个新字符串。 It does not change `number'.它不会改变“数字”。

number.replace('8','2'); 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');要获得所需的功能,您必须键入 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.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM