Why i am getting WA?

Problem link-https://www.codechef.com/problems/ALPHA
I used this Approach.
My Solution-https://www.codechef.com/viewsolution/11541325

class alpha

{

public static void main(String[] args)

{
    Scanner sc=new Scanner(System.in);
    int t=sc.nextInt();
    while(t!=0)
    {
    
    String alpha="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    String p=sc.next();
  
    StringBuilder sb=new StringBuilder();
    char ch;
    int ind=0;
    boolean flag=false;
    for(int i=0;i<p.length();i++)
    {
        flag=false;
       ch=p.charAt(i);     
      
       ind=alpha.indexOf(ch);

        if(ind!=-1)
    {

       if(ind==25)
        {
            ind=0;
            flag=true;
        }

         if(ind==51)

       {
            ind=26;
            flag=true;
        }

        if(flag!=true)
       ch=alpha.charAt(ind+1);

        else 
          ch=alpha.charAt(ind);

       sb.append(ch);
    
     }
    
    }
        System.out.println(sb);
    t--;
     }
}

}

Change p=sc.next() to p=sc.nextLine().


Also you need to write sc.nextLine() after sc.nextInt() so that the scanner skips the entire line in which int is written as scanner would be positioned after int only after reading it. So you need to get to the next string after encountering line break.

1 Like

Yes,got accepted Thanks a lot…

But Please tell what was happening with previous code as it was running well in laptop?

Actually the test cases involve spaces also. So sc.next() would accept one word and would not ignore any space. So to deal with that you must write sc.nextLine() which ensures that a complete line is read including spaces. And to know more about the second point which I made you can read here: http://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo

You can also upvote my answer if you find it helpful.