javastringjava.util.scannerpangram

Code to tell whether a string is a Pangram or not?


import java.io.*;
import java.util.*;


public class Solution {

    public static final int n = 26; 

    public int check(String arr) {
        if (arr.length() < n) {
           return -1;
        }
        for (char c = 'A'; c <= 'Z'; c++) {
            if ((arr.indexOf(c) < 0) && (arr.indexOf((char)(c + 32)) < 0)) {
               return -1;
            }
        }
        return 1;
    }  
}

public static void main(String[] args) {
    Scanner s1 = new Scanner(System.in);
    String s = s1.next();
    Solution obj = new Solution();

    int d = obj.check(s);

    if (d == -1) {
        System.out.print("not pangram");
    } else {
        System.out.print("pangram");
    }
}

If the string entered is:
We promptly judged antique ivory buckles for the next prize

It will give the wrong output:
not pangram.

I'm not able to find out what wrong with the code.
Thanks in advance!


Solution

  • The problem is that whitespace is a separator for Scanner.next(). So when you input We promptly judged antique ivory buckles for the next prize, s will point just to the string We. When you call obj.check(s) on We it will return -1.

    To verify that this is the case, you can print s and check its value. You can also do:

    String s = "We promptly judged antique ivory buckles for the next prize";
    

    Call obj.check(s) and see that it will return the correct answer.

    To fix it you should call Scanner.nextLine() instead of Scanner.next():

    String s = s1.nextLine();