gpt4 book ai didi

java - 如何解决 "error: bad operand types for binary operator"问题?

转载 作者:行者123 更新时间:2023-12-02 06:26:54 26 4
gpt4 key购买 nike

该程序旨在检查任何用户字符串的第一个元素然后,检查它是否是“大写字母”或“2到9的数字”

import java.util.*;
public class test1
{
public static void main (String [] args)
{
Scanner mykey= new Scanner (System.in);
System.out.println("Enter your first sentence");
String firstSen= mykey.nextLine();
String firstChar= firstSen.substring(0,1);
if ((firstChar <='Z') && (firstChar >= 'A'))
{System.out.println("Its a letter");}
else if ((firstChar>='2') && (firstChar<='9'))
{System.out.println("Its a number");}
}
}

错误

test1.java:10: error: bad operand types for binary operator '<='
if ((firstChar <='Z') && (firstChar >= 'A'))
^
first type: String
second type: char
test1.java:10: error: bad operand types for binary operator '>='
if ((firstChar <='Z') && (firstChar >= 'A'))
^
first type: String
second type: char
test1.java:12: error: bad operand types for binary operator '>='
else if ((firstChar>='2') && (firstChar<='9'))
^
first type: String
second type: char
test1.java:12: error: bad operand types for binary operator '<='
else if ((firstChar>='2') && (firstChar<='9'))

最佳答案

substring(0, 1)返回 String你的错误是比较 Stringchar使用>=<= .

您应该获取字符串的第一个字母,而不是 String ,但作为 char ,通过使用charAt方法:

  Scanner mykey= new Scanner (System.in);
System.out.println("Enter your first sentence");
String firstSen= mykey.nextLine();
char firstChar= firstSen.charAt(0); // note this line!
if ((firstChar <='Z') && (firstChar >= 'A'))
{System.out.println("Its a letter");}
else if ((firstChar>='2') && (firstChar<='9'))
{System.out.println("Its a number");}

两个 char s 可以与 <= 进行比较和>= 。一个String和一个 char不能。

关于java - 如何解决 "error: bad operand types for binary operator"问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55781144/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com