编译错误:不兼容的操作数类型java.lang.String和char

时间:2013-05-06 02:39:09

标签: java drjava

import java.io.*;
import hsa.Console;
import java.awt.*;


    public static void main(String[] args) throws IOException {
        c = new Console();

        String sentence;
        String encrypt = "";
        String vowels = "AEIOUaeiou";
        final String PUNCTAUTION = ".,;?!\"\\/\' -";
        StringBuffer removePunctation = new StringBuffer();
        StringBuffer thirdLetters = new StringBuffer();

        char tempChar;

        //Open The Output File

        PrintWriter output;
        output = new PrintWriter(new FileWriter("output.txt"));

        c.println("Please enter the sentence you would like to encrypt");
        sentence = c.readLine();


        for (int i = 0; i < sentence.length(); i++) {
            tempChar = sentence.charAt(i);

            if (PUNCTAUTION.indexOf(tempChar) == -1) {
                encrypt = encrypt + tempChar;
            }
        }
        if (encrypt == 'A') {
            sentence.replace('A', '!');
        } else if (encrypt == 'I') {
            sentence.replace('I', '#');
        } else if (encrypt == 'E') {
            sentence.replace('E', '@');
        } else if (encrypt == 'O') {
            sentence.replace('O', '$');
        } else if (encrypt == 'U') {
            sentence.replace('U', '%');
        }
        c.println(encrypt.toString().toUpperCase());

        output.println(encrypt.toString().toUpperCase());
    }

我正在尝试删除所有标点符号和空格,并将元音AEIOU更改为!@#$%,但我收到错误。我也试图从底部的句子输出我替换的元音并反转它们。

3 个答案:

答案 0 :(得分:0)

正如编译器试图告诉您的那样,您无法使用==将字符串与字符进行比较。 ==运算符对基元(例如char)和引用类型(例如String)的工作方式不同,因此if(encrypt == 'U')之类的条件是无意义的。

答案 1 :(得分:0)

test strings for equality,请使用String.equals()。例如,"A".equals(encrypt)测试字符串encrypt是否为大写字母A.

请注意,如上所述,最好先放置常量字符串(而不是encrypt.equals("A")),以避免出现空指针异常。

如果您想要不区分大小写的匹配,那么还有String.equalsIgnoreCase()


关于您手头的任务(例如,删除/替换所有出现的内容),您可以考虑使用正则表达式。

例如,用!替换所有大写字母A!你可以使用类似的东西:

encrypt.replaceAll("A", "!")

或者,如果您将一遍又一遍地使用相同的正则表达式模式,或者希望灵活地制作不区分大小写的模式,那么:

Pattern a = Pattern.compile("A", Pattern.CASE_INSENSITIVE);
...
a.matcher(encrypt).replaceAll("!");

答案 2 :(得分:0)

字符串是对象,而char是私有数据类型。

你基本上要求计算机做的就像要求它将数字与数字列表进行比较。它不能,因为那是完全不同的两件事。

如下所述,您希望使用类似

的内容
  if(encrypt.equals("a")){ 

将字符串驻留到字符。

相关问题