该程序旨在检查任何用户字符串的第一个元素 然后检查是“大写字母”还是“ 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'))
答案 0 :(得分:1)
substring(0, 1)
返回String
,您的错误是使用String
和char
将>=
与<=
进行比较。
您应该使用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
与<=
和>=
进行比较。 String
和char
不能。
答案 1 :(得分:-1)
在比较两个不适合使用提供的运算符进行比较的操作数时,错误运算符的错误操作数类型出现。正如@Sweeper所指出的,您正在比较String和char。
解决问题的另一种方法是比较要比较的字符的ASCII值。这是替代解决方案。
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();
// Fetch the first character and then convert to int
// so that the comparison can be don based on ASCII values
int firstChar = (int) firstSen.charAt(0);
// ASCII value for A = 65, Z = 90
if ((firstChar <= 90) && (firstChar >= 65))
{System.out.println("Its a letter");}
// ASCII value for 2 = 50, 9 = 57
else if ((firstChar>= 50) && (firstChar<=57))
{System.out.println("Its a number");}
}
}