problem with string array indexing at changing locations

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 894 Views - Last Post: 09 September 2013 - 10:54 AM Rate Topic: -----

#1 hina123   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 09-September 13

problem with string array indexing at changing locations

Posted 09 September 2013 - 08:48 AM

public List <String> first_n=new ArrayList();
          public  List <String> last_n=new ArrayList();
 InputStream stream = FINALPROJECT.class.getResourceAsStream("namings.txt");
     BufferedReader rd = new BufferedReader(new InputStreamReader(stream));  
    String s;  
    try {  
            while (null != (s = rd.readLine())) {
        //while ((s = rd.readLine()) != null){  
               
                System.out.println(s);  
                String []res= s.split(" ");
                System.out.println(res[0]);
            System.out.println(res[1]);
                                        first_n.add(res[0]);
                                       last_n.add(res[1]);
            }  
    } finally {  
            rd.close();  
    }  


i have a text file containing names e.g.(abdul rehman).now i want the first and last names to be added to first_n and last_n.Problem is that for some name which is not same everytime,it gives the error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1" which gets away if i comment out res[1] part.I dont see why it works at sometimes and sometimes doesnt while all names have same structure.

Is This A Good Question/Topic? 0
  • +

Replies To: problem with string array indexing at changing locations

#2 Ryano121   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1461
  • View blog
  • Posts: 3,289
  • Joined: 30-January 11

Re: problem with string array indexing at changing locations

Posted 09 September 2013 - 08:56 AM

That is probably because in your text file you have a few lines that only contain one name or a line with no spaces. Therefore when you split at the spaces there is only one resulting element and so trying to access the second element throws an exception.

Before you try accessing the elements test the length of the split array. If its two then you know you are dealing with two names and you are safe to access both of them

if(res.length == 2) // or maybe just > 1
{
   // add the values of res[0] and res[1] to the lists
}

This post has been edited by Ryano121: 09 September 2013 - 08:57 AM

Was This Post Helpful? 0
  • +
  • -

#3 hina123   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 09-September 13

Re: problem with string array indexing at changing locations

Posted 09 September 2013 - 09:11 AM

View PostRyano121, on 09 September 2013 - 08:56 AM, said:

That is probably because in your text file you have a few lines that only contain one name or a line with no spaces. Therefore when you split at the spaces there is only one resulting element and so trying to access the second element throws an exception.

Before you try accessing the elements test the length of the split array. If its two then you know you are dealing with two names and you are safe to access both of them

if(res.length == 2) // or maybe just > 1
{
   // add the values of res[0] and res[1] to the lists
}


thanks but the thing is that i have checked my file several times for such matters and have found no problems.And for a safe side i also added your line and printed out a "yes" if the length is true and is giving yes even at the place where it gives error.And if i have the problem in file then it should give the error for same name but it changes location..and another thing is that it doesnt stop after error..it reads whole file though
Was This Post Helpful? 0
  • +
  • -

#4 Ryano121   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1461
  • View blog
  • Posts: 3,289
  • Joined: 30-January 11

Re: problem with string array indexing at changing locations

Posted 09 September 2013 - 09:22 AM

Well yes it does stop after the error. If an exception is being thrown in that bit of code in the middle of reading the file then it will not finish. It will break out.

In that code snippet the only possibility of getting an exception thrown when accessing res[1] is when the .split() method results in just one value. This is confirmed when you take out the code where you access res[1] and the code works fine.
Was This Post Helpful? 0
  • +
  • -

#5 hina123   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 09-September 13

Re: problem with string array indexing at changing locations

Posted 09 September 2013 - 09:25 AM

should i post the whole code?and i can attach the text file as well if u want
Was This Post Helpful? 0
  • +
  • -

#6 Ryano121   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1461
  • View blog
  • Posts: 3,289
  • Joined: 30-January 11

Re: problem with string array indexing at changing locations

Posted 09 September 2013 - 09:29 AM

Yes go for it.
Was This Post Helpful? 0
  • +
  • -

#7 hina123   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 09-September 13

Re: problem with string array indexing at changing locations

Posted 09 September 2013 - 09:33 AM

public class FINALPROJECT {
   public List <String> first_n=new ArrayList();
          public  List <String> last_n=new ArrayList();
          public  List <String> start_code=new ArrayList();
  
       
    
    void analysis() throws IOException {
         InputStream stream = FINALPROJECT.class.getResourceAsStream("namings.txt");
     BufferedReader rd = new BufferedReader(new InputStreamReader(stream));  
    String s;  
    try {  
            while (null != (s = rd.readLine())) {
        //while ((s = rd.readLine()) != null){  
               
                System.out.println(s);  
                String []res= s.split(" ");
                if(res.length == 2){
                    System.out.println("yes");
                }
                System.out.println(res[0]);
             
           System.out.println(res[1]);
                                        first_n.add(res[0]);
                                       last_n.add(res[1]);
            }  
    } finally {  
            rd.close();  
    }  

  
         InputStream stream1 = FINALPROJECT.class.getResourceAsStream("phones.txt");
     BufferedReader rd1 = new BufferedReader(new InputStreamReader(stream1));  
    String s1;  
    try {  
        while ((s1 = rd1.readLine()) != null){
       
                System.out.println(s1);  
               start_code.add(s1);
    }
    }  finally {  
            rd1.close();  
    }  
        //////////////////////////////////////////////////////////////////
      
}
void random() throws SQLException, NoSuchAlgorithmException, ClassNotFoundException
{
                 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
       
        String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=call details";
        Connection con = DriverManager.getConnection(connectionUrl,"aiza,"database");
        //Statement stmt = null;
            ResultSet rs = null;
            
            int s=start_code.size();
            int k=first_n.size();
            int ss=last_n.size();
            System.out.print(k);
         Random generate = new Random();
   for(int i=0;i<30000;i++)
    {
         int start=generate.nextInt(33);
        
        //System.out.print(start);
        String phone_num=start_code.get(start);
       // System.out.print("num");
            int num = 1000000 +generate.nextInt(9000000);
           // System.out.print(num);
          String x =Integer.toString(num);
         phone_num=phone_num+x;
        // System.out.print(phone_num);
         
         ////////////////////////////////////////////////////////////////////////////////////
         String nic;
                SecureRandom random = SecureRandom.getInstance("SHA1PRNG");

        byte [] a = new byte [7];
        random.nextBytes(a);
        byte seed[] = random.generateSeed(20);
        BigInteger b = new BigInteger(1,seed);

        String j = String.valueOf(B)/>;
        j= j.substring(0,14);
       String x1=j.substring(0,4);
               x1=x1+"-";
         String x2=j.substring(4,13);    
         x2=x2+"-";
          String x3=j.substring(13);
          nic=x1+x2+x3;
        //System.out.print("\n");
        //System.out.println(nic); 
        

        ///////////////////////////////////////////////////////////name//////////////////////////////
        int first=generate.nextInt(131);
        int last=generate.nextInt(131);
 String F=first_n.get(first);
 String L=last_n.get(last);
 String name=F+" "+L;
 
 String SQL = "SELECT f_Name FROM personal_data WHERE f_Name = ?";
 int n=0;
            
          PreparedStatement stmt =con.prepareStatement(SQL);
           stmt.setString(1,name);
            rs=stmt.executeQuery();
             while (rs.next()) {
            //System.out.println(rs.getString("f_name"));
                n=1;
           }
    String SQL1 = "SELECT nic FROM personal_data WHERE nic = ?";
 int m=0;
            
          PreparedStatement stmt1 =con.prepareStatement(SQL1);
           stmt1.setString(1,nic);
            rs=stmt1.executeQuery();
             while (rs.next()) {
                
                m=1;
           }       
             String SQL2 = "SELECT telephone FROM personal_data WHERE telephone = ?";
 int l=0;
            
          PreparedStatement stmt2 =con.prepareStatement(SQL2);
           stmt2.setString(1,phone_num);
            rs=stmt2.executeQuery();
             while (rs.next()) {
                
                l=1;
           }  
             
          if(l==0&&m==0&&n==0)
         
      {
          System.out.println("ghdghsrthjsrtjsrjrsjtjrjyrj");
          String SQL3 = "INSERT INTO personal_data (f_name,nic,telephone) VALUES (?,?,?)";
          PreparedStatement stmt3 =con.prepareStatement(SQL3);
          stmt3.setString(1,name); 
           stmt3.setString(2,nic);
            stmt3.setString(3,phone_num);
        int executeUpdate = stmt3.executeUpdate(); 
      
     }



}
con.close();


}


/**
* @param args the command line arguments
*/

public static void main(String[] args) throws SQLException, ClassNotFoundException, NoSuchAlgorithmException, IOException
{

FINALPROJECT g= new FINALPROJECT();

g.analysis();
// g.random();

// TODO code application logic here

}
}
/**
Was This Post Helpful? 0
  • +
  • -

#8 Ryano121   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1461
  • View blog
  • Posts: 3,289
  • Joined: 30-January 11

Re: problem with string array indexing at changing locations

Posted 09 September 2013 - 09:36 AM

So on exactly which line is the exception being thrown. It would also be helpful if you could post a full stack trace.
Was This Post Helpful? 0
  • +
  • -

#9 hina123   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 09-September 13

Re: problem with string array indexing at changing locations

Posted 09 September 2013 - 09:41 AM

Javaid Latif
yes
Javaid
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
Latif
Irfan Dogar
yes
Irfan
Dogar
Barjees Tahir
yes
Barjees
Tahir
MANSAB ALI
yes
MANSAB
ALI
Salman Hanif
yes
Salman
Hanif
Waseem Sheikh
yes
Waseem
Sheikh
Malik Rashid
yes
Malik
Rashid
Muhammad Ishaq
yes
Muhammad
Ishaq
Rana Hayat
yes
Rana
Hayat
ABBAS REBAIRA
yes
ABBAS
REBAIRA
Muhammad Arif
yes
Muhammad
Arif
Ashiq Shah
yes
at pkgfinal.project.FINALPROJECT.analysis(FINALPROJECT.java:54)
Ashiq
Shah
at pkgfinal.project.FINALPROJECT.main(FINALPROJECT.java:193Rao Ajmal
)

yes
Rao
Ajmal
Moeen Watto

I get error like this...the pattern of these three error statements is same but the name for which this happens changes everytime i run my code e.g this time it is happening after "javaid latif" and another time i ran it was after "hamza sharif"
Was This Post Helpful? 0
  • +
  • -

#10 Ryano121   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1461
  • View blog
  • Posts: 3,289
  • Joined: 30-January 11

Re: problem with string array indexing at changing locations

Posted 09 September 2013 - 10:17 AM

But what line is 54 and 193?

They don't line up with the code you posted.

Also has this got anything to do with the database portion of the code. It would be good to know so we can cut the irrelevant code out.

Actually I can see the problem

if(res.length == 2){
    System.out.println("yes");
}
System.out.println(res[0]);
System.out.println(res[1]);
first_n.add(res[0]);
last_n.add(res[1]);


So in your code you are checking if the length is two and printing yes if it is, but then going ahead and accessing both elements irrelevant of the result of the if check. Essentially there was no point in putting in the if check if you are going to try and access both values regardless.

The if check is important as it asserts that there are two elements that you can actually access. At the moment you are trying to access them without knowing whether or not they are actually there. Access res[0] and res[1] INSIDE the if check.
Was This Post Helpful? 1
  • +
  • -

#11 hina123   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 09-September 13

Re: problem with string array indexing at changing locations

Posted 09 September 2013 - 10:22 AM

System.out.println(res[1]); //line 54
g.analysis(); //line 193

and i dnt think there is some problem with database part because as i told you that it starts to read the second file of phones.txt if i remove res[1] part.

ok i will check after putting these two printout statements inside if
Was This Post Helpful? 0
  • +
  • -

#12 Ryano121   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1461
  • View blog
  • Posts: 3,289
  • Joined: 30-January 11

Re: problem with string array indexing at changing locations

Posted 09 September 2013 - 10:22 AM

Yep that makes sense then. There is a solution in the post above.
Was This Post Helpful? 0
  • +
  • -

#13 hina123   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 09-September 13

Re: problem with string array indexing at changing locations

Posted 09 September 2013 - 10:27 AM

  System.out.println(s);  
                String []res= s.split(" ");
                if(res.length == 2){
                    System.out.println(res[0]);
             
           System.out.println(res[1]);
                }
 first_n.add(res[0]);
 last_n.add(res[1]);    //line 56



after doing this,
Rao Ajmal
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
Rao
Ajmal
Moeen Watto
Moeen
Watto
Ghaffar Dogar
Ghaffar
Dogar
Makhdoom Javaid
Makhdoom
Javaid
Mahmood Qureshi
Mahmood
Qureshi
Sikandar Bosan
Sikandar
Bosan
Javed Shah
Javed
Shah
Dewan Bukhari
Dewan
Bukhari
Siddique Baloch
Siddique
Baloch
Hayat Hiraj
Hayat
Hiraj
Khan Daha
Khan
Daha
Aslam Bodla
Aslam
Bodla
Iftikhar Nazir
Iftikhar
Nazir
AHMAD SHAH
AHMAD
SHAH
MUHAMMAD ASHRAF
MUHAMMAD
ASHRAF
RAI HASAN
RAI
HASAN
SARDAR MANSAB
SARDAR
MANSAB
ATHAR GILLANI
ATHAR
GILLANI
Hussain Khan
Hussain
Khan
Nazeer Ahmed
Nazeer
Ahmed
Sajid Mehdi
Sajid
Mehdi
Tahir Iqbal
Tahir
Iqbal
at pkgfinal.project.FINALPROJECT.analysis(farooq Khosa
FINALPROJECT.java:56)

farooq
at pkgfinal.project.FINALPROJECT.main(FINALPROJECT.java:193)
Khosa
Abdul Kareem
Abdul
Kareem
Was This Post Helpful? 0
  • +
  • -

#14 Ryano121   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1461
  • View blog
  • Posts: 3,289
  • Joined: 30-January 11

Re: problem with string array indexing at changing locations

Posted 09 September 2013 - 10:32 AM

You are still trying to access res[1] outside of the if statement!

 System.out.println(s);  
String []res= s.split(" ");
if(res.length == 2){
     System.out.println(res[0]);      
    System.out.println(res[1]);
    first_n.add(res[0]);
    last_n.add(res[1]);    //line 56
               }



You also have some indentation issues with your code that should be sorted. At the moment its a bit of a mess to look at.
Was This Post Helpful? 1
  • +
  • -

#15 hina123   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 09-September 13

Re: problem with string array indexing at changing locations

Posted 09 September 2013 - 10:46 AM

thanks alot..it works now..i think now some names would be missing..so what do u suggest?i look in my file for possible errors?
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2