简体   繁体   中英

Checking if a String contains the letters I want plus a whitespace at the end of it

Im looking for a way to check if the String the User enters, contains two things: First: It should start with "hello "(its hello and a whitspace!) or if it starts with a number. If both is false I want to print out false , if one of both is true i print out true.

if (text.startsWith("hello ") == false)
{
    if (Character.isDigit(text.CharAt(0)) == false)
    { 
        System.out.println("false"); 
    }

    Syso("true"); 
}
Syso("true");

I know that the two If's are not the smartest choice in this case but im fine with this. The only problem I have at the Moment is that if the text is "hello" so without a whitespace it still gives me true. Does it have to do something with the method startsWith? is there another method to use ?

Sorry , My english is bad and I'm knew to programming. But thanks for the feedbak

You want something to be true if one of two conditions is true. This is thus a logical or :

System.out.println(text.startsWith("hello ") || Character.isDigit(text.charAt(0)));
if (! text.startsWith ("hello ") && ! Character.isDigit (text.charAt (0)) {
          Syso ("false"); 
}
else Syso ("true"); 

This can be further condensend. If (! a && ! b) is equivalent to if (! (a || b)).

if (! (text.startsWith ("hello ") || Character.isDigit (text.charAt (0)))) {
          Syso ("false"); 
}
else Syso ("true"); 

Negating the condition is, however, confusing. So if there is no good reason, you should formulate a positive, hence more simple condition:

    if (text.startsWith ("hello ") || Character.isDigit (text.charAt (0))) 
              Syso ("true"); 
    else Syso ("false"); 

I can't reproduce your error with the blank - maybe you tricked yourself with the too-much-negation?

Note, that you should test your example code to reproduce your error - and cut and paste it, to prevent new errors. String.charAt (0) must start with a lower c in the method name.

Note, that you need an ' else ' after the closing braces, to reach your goal.

The way you included print statements in your code is wrong. The problem in your code is if it doesn't start with 'hello ' it enters the if block. If it doesn't start with a digit, it further enters the inner if, prints false. Once it comes out it prints true and then after outer if it prints a true again.

if (str.startsWith("hello ") || Character.isDigit(str.charAt(0))) {
    System.out.println("True");
}
else{
    System.out.println("False");
}

try using trim() method, trim takes off the white spaces from a text:

String txt = "hello ";
System.out.println(txt.trim() + jhon);

console: hellojhon

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM