Java 如何检查字符串是否有+;,-,或(十进制)在第一个字符中?
我正在编写一个程序,它将确定一个双字面值是否为4个字符,并在屏幕上打印出来。我相信我做的部分是正确的,我会检查是否有4个字符。我被困在如何检查a+、-或。是第一个字符。用我的Java 如何检查字符串是否有+;,-,或(十进制)在第一个字符中?,java,if-statement,Java,If Statement,我正在编写一个程序,它将确定一个双字面值是否为4个字符,并在屏幕上打印出来。我相信我做的部分是正确的,我会检查是否有4个字符。我被困在如何检查a+、-或。是第一个字符。用我的 str.charAt(0)=“+”| |“-“| |”我收到一个不兼容的操作数错误 public class Program4 { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in);
str.charAt(0)=“+”| |“-“| |”
我收到一个不兼容的操作数错误
public class Program4 {
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
String str;
System.out.println("Please enter a valid (4 character) double literal consisting of these numbers and symbols: '+', '-', '.', (decimal point), and '0' through '9'");
str = stdIn.nextLine();
int length = str.length();
// the next if statement will determine if there are exactly 4 characters \\
if ( length == 4 ) {
// the next if statement checks for a +, -, or . (decimal) in the first character \\
if ( str.charAt(0) == "+" || "-" || ".") {
}
}
else {
System.out.println ("Please restart the program and enter in a valid 4 character double literal.");
}
}
}
如果(str.charAt(0)=“+”| | |“-”| |“”){
与
这个
…没有意义。|
运算符的操作数必须是布尔值
s。表达式str.charAt(0)=“+”
的计算结果为布尔值
,但单独存在的两个字符串则不是
解决此问题的方法有很多种,其中哪种方法对您最有意义取决于上下文。但是,其中一种方法使用以下事实:字符串文字与其他任何方法一样,都是string
s,您可以在其上调用方法。例如indexOf()
:
另一种方式:
switch ( str.charAt(0) ) {
case '+': case '-': case '.':
<do something>
break;
}
开关(str.charAt(0)){
大小写“+”:大小写“-”:大小写“:
打破
}
如果(“+-”.indexOf(str.charAt(0))>=0{
str.charAt(0)='+'.| | str.charAt(0)=='-'.| str.charAt(0)='.
这不是COBOL;你不能做“快捷方式”像x==a | | b | | c
这样的布尔运算。您必须完整地写出每个比较:x==a | | x==b | | x==c
String#startsWith仍然是无效的Java语法,因为您不能说a==1 | | 2 | 3
显然------您没有用代码解决另一个问题,即比较字符
转换为字符串文字,而不是字符文字。
if ( str.charAt(0) == "+" || "-" || ".") {
if ("+-.".indexOf(str.charAt(0)) >= 0) {
// starts with +, -, or .
}
switch ( str.charAt(0) ) {
case '+': case '-': case '.':
<do something>
break;
}