-2

I have some sort of problem even tho, idk what it's actually that's my code

package $Random_Projects;
import java.util.Scanner;
public class PhoneBook {
    public static void main (String[] args){
        Scanner myScan = new Scanner(System.in);
        System.out.println("Enter number of entries in the phone book ");
        int num= myScan.nextInt();
        String PBEnteries[]=new String[num];
        for(int i=0; i<PBEnteries.length;i++){
            System.out.println("Enter name and telephone number: ");
            PBEnteries[i]=myScan.nextLine();
        }
        System.out.println("Enter name: ");
        String nameSearch=myScan.next();
        boolean search=false;
        for(int i=0;i<PBEnteries.length;i++)
            for(int j=0;j<nameSearch.length();j++){
                if(nameSearch.charAt(j)==PBEnteries[i].charAt(j)){
                    if(j == nameSearch.length()){
                        search=true;
                        System.out.println(PBEnteries[i]);}
                }
            }
        if(search == false)
            System.out.println("Invalid name.");
    }
}

my issue in 21 line : if(nameSearch.charAt(j)==PBEnteries[i].charAt(j)){ it should be searching for the name so the type name and phone number, ex."Sam 0000", "Danial 1111" and in search he writes the name ex."Sam" and should post num or even the whole array as "Sam 0000", but I've a problem with equalizing each char note: it's not a personal program, they want it all in one array with specific java knowledge, so it should compare each char in the name that he typed with the array

output :

Enter number of entries in the phone book 
3
Enter name and telephone number: 
Enter name and telephone number: 
Mohammed 1212
Enter name and telephone number: 
Ali 0000
Enter name: 
Ali
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    at java.lang.String.charAt(String.java:658)
    at $Random_Projects.PhoneBook.main(PhoneBook.java:21)
IRomio
  • 3
  • 1
  • This seems to be a duplicate of https://stackoverflow.com/q/13102045/5646962 - the problem described there is the reason that your first entry is empty – Thomas Kläger Mar 20 '19 at 16:38
  • @IRomio your code have more than 1 problems in it. while going with above approach i don't think you will get your desired output – Syed Mehtab Hassan Mar 20 '19 at 16:52

1 Answers1

0

If you have an empty string or null for index 0 of your entries array -- and from your run output it looks like you might -- it would make sense that asking for charAt[0] of that entry would fail. You may want to include a guard not to store empty entries, or, when you're looking up entries, you might want to check that it's not null or empty.

jwismar
  • 11,772
  • 3
  • 28
  • 42
  • thanks but actually i dont know whats that problem that also skips the first loop and go to the second :), if you know why I'd appreciate it – IRomio Mar 20 '19 at 16:28