Java-在string.replace()问题中有字符输入

时间:2018-07-28 14:35:53

标签: java string char

是否可以通过创建与该字符相等的新字符串变量来解决此问题

import java.util.Scanner;
public class mean_and_scary {
    public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter Text:");
        String text = scanner.nextLine();
        char leftchar = scanner.next().charAt(0);
        char rightchar = scanner.next().charAt(0);
        char removechar = scanner.next().charAt(0);
        int width = scanner.nextInt();
        text = text.replace(removechar, ""); // at this point
        text = text.toUpperCase();
        System.out.println(text);
        scanner.close();
    }
}

3 个答案:

答案 0 :(得分:0)

您可以将下面的行替换为:

text = text.replace(String.valueOf(removechar), ""); // at this point

答案 1 :(得分:0)

错误是String类中没有带参数(char,String)的方法

尝试以下操作:text = text.replace(removechar + "", "");

答案 2 :(得分:0)

发生错误是因为.replace(char,String)类的方法String不存在,所以他们可以找到它。

Java Documentation

public static void main(String[] args) {
    "Test".replace("",""); // OK because the method replace with params CharSequence,CharSequence exist
    "Test".replace('e', '\u0000'); // OK because the method replace with params char,char exist
    "Test".replace('\u0000', ""); // Not OK because the method don't exist 
}