-3
import java.util.Scanner;
public class ValidString {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the String: ");
        //String s = scan.nextLine();
        StringBuilder str = new StringBuilder(scan.nextLine());
        System.out.println(isValidString(str));
        scan.close();
    }

    public static boolean isValidString(StringBuilder str) {
        for(int i = 0;i<str.length();i++) {
        int s = (int)newStr.charAt(i);
            if(s>=97 && s<=122 || s>=65 && s<=90){
                
                continue;
            }else {
                return false;
            }
        }
        return true;
    }

}

I was expecting the output as true if string contains only Alphabets else false value. Can anyone trace out what's the problem with this code.

7
  • 2
    condition str.charAt(i)<='A' && str.charAt(i)>='Z' && str.charAt(i)<='a' && str.charAt(i)>='z') is never satisfied. Commented Mar 17, 2023 at 18:13
  • 2
    To put it more simply - imagine you were dealing with integers. Your condition would be something like if (x <= 5 && x >= 10 && x <= 25 && x >= 30). What value would you expect to satisfy all those parts? (I'd also suggest that if you call str.charAt(i) once and store the result in a local variable to use in your condition multiple times, your condition is likely to end up being more readable.) Commented Mar 17, 2023 at 18:14
  • 1
    Yes, I realise that - but I suggest you look really carefully at what I've suggested (both parts). What value of x is both "less than or equal to 5" and "greater than or equal to 10"? Then apply that same thinking to character comparisons. Commented Mar 17, 2023 at 18:19
  • 1
    @SURAJMAHAKAL you're missing the point of the comments. Try a sample input string for which isValidString(StringBuilder str) is supposed to return true. Pretend you are the computer, and follow the logic of that method. Use pen and paper for your computer memory. Create truth tables with columns such as c <='A', c>='Z', and so on. Commented Mar 17, 2023 at 18:20
  • 1
    ... where c, in my previous comment, represents the current value pointed to by str.charAt(i). Commented Mar 17, 2023 at 18:29

1 Answer 1

1

Simply put, you will never have a character that is <= A and >=Z because the range A-Z is contiguous and ascending. The same is true for the range a-z. So instead of
str.charAt(i)<='A' && str.charAt(i)>='Z' && str.charAt(i)<='a' && str.charAt(i)>='z'
you need this -
!(str.charAt(i)>='A' && str.charAt(i)<='Z') && !(str.charAt(i)>='a' && str.charAt(i)<='z')

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.