[英]How can I check if a string has +, -, or . (decimal) in the first character?
I am writing a program that will determine if a double literal is 4 characters, and print it out on the screen. 我正在编写一个程序,该程序将确定双精度文字是否为4个字符,并将其打印在屏幕上。 I believe I did the part right where I will check to see if there are exactly 4 characters. 我相信我做的正确,我将检查是否有4个字符。 I am stuck on how to check if a +, - or . 我被困在如何检查+,-或。 is the first character. 是第一个字符。 With my str.charAt(0) == "+" || "-" || "."
用我的str.charAt(0) == "+" || "-" || "."
str.charAt(0) == "+" || "-" || "."
I am receiving an Incompatible operand error. 我收到一个不兼容的操作数错误。
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.");
}
}
}
Another way: 其他方式:
switch ( str.charAt(0) ) {
case '+': case '-': case '.':
<do something>
break;
}
replace this if ( str.charAt(0) == "+" || "-" || ".") {
if ( str.charAt(0) == "+" || "-" || ".") {
with 与
`if ( str.charAt(0) == '+' || str.charAt(0)=='-' || str.charAt(0)=='.') {
This ... 这个 ...
if ( str.charAt(0) == "+" || "-" || ".") {
... does not make sense. ...没有意义。 The operands of the ||
||
的操作数 operator need to be boolean
s. 运算符必须为boolean
s。 The expression str.charAt(0) == "+"
evaluates to a boolean
, but the two strings standing by themselves do not. 表达式str.charAt(0) == "+"
计算结果为boolean
,但是两个str.charAt(0) == "+"
站立的字符串却不是。
There are numerous ways to solve this problem, and which one makes the most sense for you depends on context. 解决此问题的方法有很多,而哪种方法最适合您取决于上下文。 However, one way to go about it uses the fact that string literals are String
s like any other, on which you can invoke methods. 但是, 一种解决方法是使用一个事实,即字符串文字与其他String
一样都是String
,可以在其上调用方法。 Such as indexOf()
: 如indexOf()
:
if ("+-.".indexOf(str.charAt(0)) >= 0) {
// starts with +, -, or .
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.