1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Java】char型の変数に文字列を代入したらincompatible typesエラーが発生した

Posted at

環境

・ホストOS: Windows10 Home
・ゲストOS: WSL2 Ubuntu18.04 LTS
・VScode ver 1.44.2
・Java openjdk11

エラー内容


public static int execute(int firstNum, char operator, int secondNum) throws ArithmeticException{
        switch (operator) {
            case "+": //1
                return firstNum + secondNum;
                break;

上のコードを実行したところ、//1の箇所で下記のエラーが発生した。
・incompatible types
・Type mismatch: cannot convert from String to char

"+"がchar型ではなく、String型の文字列として認識された模様。

解決法

・文字をchar型の変数として扱う際はシングルクォーテーションでくくる。


public static int execute(int firstNum, char operator, int secondNum) throws ArithmeticException{
        switch (operator) {
            case '+': //修正箇所
                return firstNum + secondNum;
                break;

上のように修正した結果コンパイルエラーがなくなった。

考察等

ソースコードに「文字」データを記述する場合は引用符(')で囲みます。そして「文字列」データを記述する場合は二重引用符(")を使います。
(中山清喬, 国本大吾 『スッキリわかるJava入門 第2版』p.50)

ということで
String型の文字列→""で囲む
char型の文字→''で囲む

と覚えておきたい。

参考資料

スッキリわかるJava入門 第2版

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?