类型不匹配:无法从char转换为String

时间:2023-01-12 13:15:15
package kreki;
import java.util.Scanner;
public class Hungry {
    public static void main(String [] args) {
        String input;
        char ans;
        Scanner Hungry = new Scanner(System.in);
        System.out.println("Are You Hungry?");
        input = Hungry.next();
        ans = input.charAt(0);
        if(ans == "Y") {
            System.out.println("Eat");
        }else {
            System.out.println("Starve");
        }
        Hungry.close();
    }
}

I'm getting Type mismatch: cannot convert from char to String. How can I fix it? Thank you.

我得到类型不匹配:无法从char转换为String。我该如何解决?谢谢。

2 个解决方案

#1


2  

It can be hard to spot for new in Java/programming overall.

总体而言,在Java /编程中很难发现新的东西。

Error is here:

错误在这里:

if(ans == "Y") {

Change double quotes to single one

将双引号更改为单引号

if(ans == 'Y') {

#2


1  

In the if:

在if:

  if(ans == 'Y') {
        System.out.println("Eat");
    }

you just need so change to single quote, because those are used for char symbols in Java. When you're using double quotes, Java is considering it a String, therefore a mismatch of types on comparison.

你只需要改变单引号,因为它们用于Java中的char符号。当您使用双引号时,Java将其视为字符串,因此在比较时类型不匹配。

#1


2  

It can be hard to spot for new in Java/programming overall.

总体而言,在Java /编程中很难发现新的东西。

Error is here:

错误在这里:

if(ans == "Y") {

Change double quotes to single one

将双引号更改为单引号

if(ans == 'Y') {

#2


1  

In the if:

在if:

  if(ans == 'Y') {
        System.out.println("Eat");
    }

you just need so change to single quote, because those are used for char symbols in Java. When you're using double quotes, Java is considering it a String, therefore a mismatch of types on comparison.

你只需要改变单引号,因为它们用于Java中的char符号。当您使用双引号时,Java将其视为字符串,因此在比较时类型不匹配。