简体   繁体   中英

Problems checking for letters or 0, within a string.[JAVA]

I am new to java, and have encountered a problem I can't seem to get around.

I am trying to make sure that there are no letters or 0's in a string full of numbers. If the string only contains numbers I want it to return true, and if there are letters or 0's in it I want it to return false.

Please note that I don't want anything too complex for me such as RegEx, so if you could keep it as basic as possible I would be very grateful.

ex. "123456789" = true , "98765x321" = false , "46813079" = false .

Here is my code thus far:

private static boolean isCorrectSyntax (String str){

    boolean trueCheck = false;
    int i = 0;
    char charCheck = str.charAt(i);

    if(str != null && str.length() == 9){

        for(i = 0; i < 9; i++){

            if (Character.isLetter(charCheck) || charCheck <= 0){
                trueCheck = false;
                break;
            }
            else{
                trueCheck = true;
            }   
        }   
    }

You can check for indexOf() 0 first , if it evaluates to -1 , which means the string didn't contain a 0 , then try to parseLong() the string and handle the NumberFormatException . If there is an exception, then your test fails .

If the number string is huge , you can go for BigInteger() , but I think it would be an overkill .

These are the pointers , you can develop your code around this.

You might want to use the following;

String str = "1234XX";        
Pattern pattern = Pattern.compile(".*[^1-9].*");
System.out.println(!(pattern.matcher(str).matches()));

Hope that helps.

You can set charCheck to true before looping through and only set it to false if necessary. Also, you only use one character throughout your entire loop. You need to set it to the next character each iteration of the loop, not one time before the loop starts.

boolean trueCheck = true;
int i;
char charCheck;

if (str != null && str.length() == 9) {

    for (i = 0; i < 9; i++) {

        // get the current character
        charCheck = str.charAt(i);

        // if the character is a letter or 0
        // the check is false, so set the flag and stop checking
        if (Character.isLetter(charCheck) || charCheck == '0') {
            trueCheck = false;
            break;
        }
    }   
}

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