-Host OS: Windows10 Home ・ Guest 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;
When I ran the above code, the following error occurred at // 1. ・ Incompatible types ・ Type mismatch: cannot convert from String to char
It seems that "+" is recognized as a String type character string instead of a char type.
-When handling a character as a char type variable, enclose it in single quotation marks.
public static int execute(int firstNum, char operator, int secondNum) throws ArithmeticException{
switch (operator) {
case '+': //Modification place
return firstNum + secondNum;
break;
As a result of the above correction, the compile error disappeared.
When describing "character" data in the source code, enclose it in quotation marks ('). And when describing "string" data, use double quotes ("). (Kiyotaka Nakayama, Daigo Kunimoto, "Introduction to Java with a Clear Understanding, 2nd Edition" p.50)
So String type character string → Enclose in "" Char type character → Enclose in''
I want to remember.
[Introduction to Java 2nd Edition](https://www.amazon.co.jp/%E3%82%B9%E3%83%83%E3%82%AD%E3%83%AA%E3%82] % 8F% E3% 81% 8B% E3% 82% 8BJava% E5% 85% A5% E9% 96% 80-% E7% AC% AC2% E7% 89% 88-% E3% 82% B9% E3% 83 % 83% E3% 82% AD% E3% 83% AA% E3% 82% B7% E3% 83% AA% E3% 83% BC% E3% 82% BA-% E4% B8% AD% E5% B1% B1-% E6% B8% 85% E5% 96% AC / dp / 484433638X)
Recommended Posts