Java 不可比数据类型 char 和 String

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12019454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 07:18:32  来源:igfitidea点击:

Java Incomparable Data types char and String

java

提问by Nate

When I run the Javac, it tells me that i have an incomparable data types char and String in the

当我运行 Javac 时,它告诉我我有一个无与伦比的数据类型 char 和 String

while(responseChar == "y")

not sure what to change to fix this error

不确定要更改什么来修复此错误

import java.util.Scanner;
public class UseOrder
{
public static void main(String[] args)
{

    int answer, num, q;
    String name, response;
    double p;
    char responseChar;
    Scanner keyboard = new Scanner(System.in);

    Order order1 = new Order();
    order1.setCustomerName();
    order1.setCustomerNum();
    order1.setQuantity();
    order1.setUnitPrice();
    order1.computePrice();
    order1.displayInfo();

    keyboard.nextLine(); 
    System.out.println("Do you need the shipping and handling service?");
    System.out.println("Enter y or n :");
    response = keyboard.nextLine();
    responseChar = response.charAt(0);
    while(responseChar == "y")
    {
        ShippedOrder order2 = new ShippedOrder();
        order2.getCustomerName();
        order2.getCustomerNum();
        order2.getQuantity();
        order2.getUnitPrice();
        order2.computePrice();
        order2.displayInfo();
    }
}
}

回答by Jeffrey

To define a character literal, use a single quote: '. Double quotes define string literals.

要定义字符文字,请使用单引号:'。双引号定义字符串文字。

while(responseChar == 'y')

回答by Hunter McMillen

Optionally you could use the big C Characterclass to convert your charto a String:

或者,您可以使用 big CCharacter类将您的转换charString

String converted = Character.toString(responseChar); 
while(converted.equalsIgnoreCase("y"))
{
  // ...
}

But this version is much more verbose than the literal comparison suggested by Jeffrey

但是这个版本比杰弗里建议的字面比较要冗长得多

回答by Amit Deshpande

Instead of "y"do this 'y'. ""Represents string.

而不是"y"这样做'y'""代表字符串。