-1

I think I am doing this wrong, I tried to put the prime numbers I'm printing into an array for the purpose of later cubing them (multiplying them by themselves x3.) Is this the most logical way to do this? Is there a better way to store them for manipulation?

package thingy;

public class thingy {
    
    public static void main(String[] args) {
    int x=102;
    for(int i=2;i<=102;i++) {
        isPrime(i);
        int [] array2= {array*array*array};
    }
    }
    
    static void isPrime(int n) {
        int i,m=0,flag=0;      
        ;//it is the number to be checked    
        m=n/2; 
        
          if(n==0||n==1){  
           
          }else{  
              
           for(i=2;i<=m;i++){      
            if(n%i==0){      
             flag=1;      
             break;      
            }      
           }      
           if(flag==0)  { System.out.println(n+" is prime number"); }  
           int [] array = {n};
          }//end of else  
        }       

}
geocodezip
  • 158,664
  • 13
  • 220
  • 245
  • I agree with @WJS about array lists. What is the purpose of lines like int [] array = {n}? That is just going to create a 1 element array with n inside it. I believe once the isPrime function ends that array falls out of scope and is not useful to the rest of your program. As a sidenote, check out https://stackoverflow.com/questions/4424374/determining-if-a-number-is-prime for a tip on how to calculate prime numbers. – The_Redhawk Jul 29 '21 at 04:39

1 Answers1

1

With arrays you need to know the size before using them and then readjusting as necessary. So use an ArrayList where you can keep adding values as you need to. You can also delete values which you can't easily do in arrays. Lists are simply easier to use.

List<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
... ad nauseum

System.out.println(list.get(1)); // prints 20
System.out.println(list); // prints [10, 20]

They also have many other handy methods too. Check them at ArrayList

WJS
  • 36,363
  • 4
  • 24
  • 39