-3

I am an beginner java please help me how to compare 1st char of surname to 5th character of pan card and check if it is same and print invalid or valid. Please advise what changes i need to make accordingly? Thanks in advance.

import java.util.*;
public class Pancardletter {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String s;
        String surname="";
        System.out.println("Enter pan card number");
         Scanner sc=new Scanner(System.in);        
         s=sc.nextLine();
         System.out.println("Enter your surname");
         surname=sc.nextLine();
         char[] ch=new char[s.length()];
         char[] ch1=new char[surname.length()];
         
         for(int i=0;i<s.length();i++) {
             for(int j=0;j<surname.length()-1;j++) {
             if(Character.toLowerCase(s.charAt(4)) ==surname.charAt(0)) {
                 System.out.println("This is a valid pan card");
             }else {
                 System.out.println("Invalid pancard...");
                     
                 }
             }
         }
    }
}

I am getting error as index out of bounds exception and getting invalid pan card as output sometimes. Please suggest wat changes i should make in order to it should work as expected. Compare first char of 1 string to 5th char of another string.

Reporter
  • 3,897
  • 5
  • 33
  • 47
  • Have you already checked what "Out of bounce exception" means? – Reporter Sep 09 '22 at 07:38
  • Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Chaosfire Sep 09 '22 at 07:46

1 Answers1

0

You don't have to loop through all the letters. Just use the condition in if statement and show the results. Also check the length of pan card string, if it's properly entered.

public static void main(String[] args) {
    System.out.print("Enter pan card number : ");
    Scanner sc=new Scanner(System.in);
    String s=sc.nextLine();
    System.out.print("Enter your surname : ");
    String surname=sc.nextLine();

    if(s.length()>4 && Character.toLowerCase(s.charAt(4))==Character.toLowerCase(surname.charAt(0))) {
        System.out.println("This is a valid pan card");
    }else {
        System.out.println("Invalid pancard...");
    }
}

}