简体   繁体   English

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

[英]Type mismatch: cannot convert from char to String

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. 我遇到类型不匹配:无法从char转换为String。 How can I fix it? 我该如何解决? Thank you. 谢谢。

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') {

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. 您只需要更改为单引号,因为这些用于Java中的char符号。 When you're using double quotes, Java is considering it a String , therefore a mismatch of types on comparison. 当您使用双引号时,Java会将其视为String ,因此比较时类型不匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM