Reputation: 3
I am writing a program that will determine if a double literal is 4 characters, and print it out on the screen. I believe I did the part right where I will check to see if there are exactly 4 characters. I am stuck on how to check if a +, - or . is the first character. With my
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.");
}
}
}
Upvotes: 0
Views: 239
Reputation: 4084
Another way:
switch ( str.charAt(0) ) {
case '+': case '-': case '.':
<do something>
break;
}
Upvotes: 3
Reputation: 831
replace this if ( str.charAt(0) == "+" || "-" || ".") {
with
`if ( str.charAt(0) == '+' || str.charAt(0)=='-' || str.charAt(0)=='.') {
Upvotes: 2
Reputation: 181824
This ...
if ( str.charAt(0) == "+" || "-" || ".") {
... does not make sense. The operands of the ||
operator need to be boolean
s. The expression str.charAt(0) == "+"
evaluates to a boolean
, but the two strings standing by themselves do not.
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. Such as indexOf()
:
if ("+-.".indexOf(str.charAt(0)) >= 0) {
// starts with +, -, or .
}
Upvotes: 2