Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Java 

Threads and public key.

Hello there,

So i am trying to create with the help of threads (im totally new to them) a program where given a number from the user i can find the 2 numbers that create him , for ex: 3337=47*71 prime factorization.

here is my code:
Code
package excersise1lab;

import java.util.Scanner;


public class Excersise1lab implements Runnable {
  
    
    private Thread t;
    private String threadName;
  
   Excersise1lab( String name) {
      threadName = name;
      System.out.println("Creating " +  threadName );
   }
    
    
    public void run() {
      
        int[] myList = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101};
        int[] factors = new int[2];
        int i=0,j=0;
        int result=0;
    
        Scanner reader = new Scanner(System.in);  // Reading from System.in
        System.out.println("Enter a number: ");
        int n = reader.nextInt();
        
        while(myList.length!=27)
        {
            result = n/myList[i];
            i++;
            if((result%1)==0)
            {
               factors[j]=result;
               j++;
            }
        }
        System.out.println("The prime Numbers that make :" + n);
        System.out.println(factors[0]);
        System.out.println(factors[1]);
      
    }
    
     public void start ()
     {
      System.out.println("Starting " +  threadName );
      if (t == null)
      {
         t = new Thread (this, threadName);
         t.start ();
      }
     }
  
    
        public static void main(String args[])
        {
            
            Excersise1lab R1 = new Excersise1lab( "Thread-1");
            R1.start();
          
            Excersise1lab R2 = new Excersise1lab( "Thread-2");
            R2.start();
        }
     }


and the errors:
Quote:Exception in thread "Thread-1" Exception in thread "Thread-2" java.lang.ArrayIndexOutOfBoundsException: 2
at excersise1lab.Excersise1lab.run(Excersise1lab.java:36)
at java.lang.Thread.run(Thread.java:745)
java.lang.ArrayIndexOutOfBoundsException: 2
at excersise1lab.Excersise1lab.run(Excersise1lab.java:36)
at java.lang.Thread.run(Thread.java:745)


that means error to:
factors[j]=result;


what i am missing.

thanks 🎉
Your factors array only has the indices 0 and 1, because it is of length 2. Your program is accessing array index 2, which doesn't exist. So perhaps make your factors array larger.


Possibly Related Threads...
Thread / Author Replies Views Last Post
[C] by putnik1313Jun 21, 2025 08:59 PM 12 438 Jun 21, 2025 08:59 PM
Last Post: Goods
[C#] by severosOct 26, 2015 09:06 AM 7 184 Oct 26, 2015 09:06 AM
Last Post: Zyklon A
[C] by FuqkFeb 6, 2015 10:32 PM 1 118 Feb 6, 2015 10:32 PM
Last Post: netisshitbro