简体   繁体   English

如何将一个字符串的第一个字符与 Java 中另一个字符串的第 5 个字符进行比较? 并检查它们是否相同。我收到如下错误

[英]how to compare first character of one string to 5th char of another string in Java? and check if they are same.I am getting error as below

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.我是初学者 java 请帮助我如何比较姓氏的第一个字符与泛卡的第五个字符并检查它是否相同并打印无效或有效。 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.我收到错误,因为索引超出范围异常并且有时会收到无效的泛卡作为 output。 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.将 1 个字符串的第一个字符与另一个字符串的第 5 个字符进行比较。

You don't have to loop through all the letters.您不必遍历所有字母。 Just use the condition in if statement and show the results.只需在 if 语句中使用条件并显示结果。 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...");
    }
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM