Method to copy primes from one array to another in JavaHow can I concatenate two arrays in Java?Create ArrayList from arrayHow do I call one constructor from another in Java?Fastest way to determine if an integer's square root is an integerWhat's the simplest way to print a Java array?How to create a generic array in Java?How to get an enum value from a string value in Java?How do I determine whether an array contains a particular value in Java?How do I declare and initialize an array in Java?prime numbers test in java

How to prevent a hosting company from accessing a VM's encryption keys?

Why can't you say don't instead of won't?

Employing a contractor proving difficult

RAID0 instead of RAID1 or 5, is this crazy?

Can a network vulnerability be exploited locally?

Can I get a PhD for developing educational software?

Which polygons can be turned inside out by a smooth deformation?

If the UK Gov. has authority to cancel article 50 notification, why do they have to agree an extension with the EU

web scraping images

Why does this London Underground poster from 1924 have a Star of David atop a Christmas tree?

Is there a way to tell what frequency I need a PWM to be?

How to say "I only speak one language which is English" in French?

The meaning of asynchronous vs synchronous

Did ancient peoples ever hide their treasure behind puzzles?

What checks exist against overuse of presidential pardons in the USA?

Why did the population of Bhutan drop by 70% between 2007 and 2008?

Is Nikon D500 a good fit for nature and ambient-lighting portraits and occasional other uses?

Why does glibc's strlen need to be so complicated to run quickly?

Should I use the words "pyromancy" and "necromancy" even if they don't mean what people think they do?

Why is there not a willingness from the world to step in between Pakistan and India?

STM32 cannot reach individual registers and pins as PIC

What does GDPR mean to myself regarding my own data?

Alternatives to Network Backup

Why can't I identify major and minor chords?



Method to copy primes from one array to another in Java


How can I concatenate two arrays in Java?Create ArrayList from arrayHow do I call one constructor from another in Java?Fastest way to determine if an integer's square root is an integerWhat's the simplest way to print a Java array?How to create a generic array in Java?How to get an enum value from a string value in Java?How do I determine whether an array contains a particular value in Java?How do I declare and initialize an array in Java?prime numbers test in java






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I'm rather new to Java, and I'm trying to figure out a way to copy all primes inside of an array and copy those to another array.



To do so, I've implemented a separate isPrime() method to check whether the element is a prime, and another method that counts the number of primes in that array countPrimes(), such that I can determine the new array's size.



Here is where I'm kind of stuck:



public static int[] primesIn(int[] arr) 
int primeHolder = countPrimes(arr);
int[] copyArr = new int[primeHolder];
for (int i = 0; i < arr.length; i++)
if (isPrime(arr[i]) == true)
copyArr[>Needs to start from 0<] = arr[i];


return copyArr;


int[] arrayMan = 3,5,10,15,13;


At copyArr the position should be 0, followed by +1 everytime it finds a prime. If I were to give it i position, as in copyArr[i] = arr[i], then say the prime is at position 5, it would try to save the prime onto position 5of copyArr, which doesn't exist if there are only three primes in the original array, which would've given copyArr a length of only three.



Something tells me a different for loop, or maybe even an additional one would help, but I can't see how I should implement it. Help is greatly appreciated!










share|improve this question






























    0















    I'm rather new to Java, and I'm trying to figure out a way to copy all primes inside of an array and copy those to another array.



    To do so, I've implemented a separate isPrime() method to check whether the element is a prime, and another method that counts the number of primes in that array countPrimes(), such that I can determine the new array's size.



    Here is where I'm kind of stuck:



    public static int[] primesIn(int[] arr) 
    int primeHolder = countPrimes(arr);
    int[] copyArr = new int[primeHolder];
    for (int i = 0; i < arr.length; i++)
    if (isPrime(arr[i]) == true)
    copyArr[>Needs to start from 0<] = arr[i];


    return copyArr;


    int[] arrayMan = 3,5,10,15,13;


    At copyArr the position should be 0, followed by +1 everytime it finds a prime. If I were to give it i position, as in copyArr[i] = arr[i], then say the prime is at position 5, it would try to save the prime onto position 5of copyArr, which doesn't exist if there are only three primes in the original array, which would've given copyArr a length of only three.



    Something tells me a different for loop, or maybe even an additional one would help, but I can't see how I should implement it. Help is greatly appreciated!










    share|improve this question


























      0












      0








      0








      I'm rather new to Java, and I'm trying to figure out a way to copy all primes inside of an array and copy those to another array.



      To do so, I've implemented a separate isPrime() method to check whether the element is a prime, and another method that counts the number of primes in that array countPrimes(), such that I can determine the new array's size.



      Here is where I'm kind of stuck:



      public static int[] primesIn(int[] arr) 
      int primeHolder = countPrimes(arr);
      int[] copyArr = new int[primeHolder];
      for (int i = 0; i < arr.length; i++)
      if (isPrime(arr[i]) == true)
      copyArr[>Needs to start from 0<] = arr[i];


      return copyArr;


      int[] arrayMan = 3,5,10,15,13;


      At copyArr the position should be 0, followed by +1 everytime it finds a prime. If I were to give it i position, as in copyArr[i] = arr[i], then say the prime is at position 5, it would try to save the prime onto position 5of copyArr, which doesn't exist if there are only three primes in the original array, which would've given copyArr a length of only three.



      Something tells me a different for loop, or maybe even an additional one would help, but I can't see how I should implement it. Help is greatly appreciated!










      share|improve this question














      I'm rather new to Java, and I'm trying to figure out a way to copy all primes inside of an array and copy those to another array.



      To do so, I've implemented a separate isPrime() method to check whether the element is a prime, and another method that counts the number of primes in that array countPrimes(), such that I can determine the new array's size.



      Here is where I'm kind of stuck:



      public static int[] primesIn(int[] arr) 
      int primeHolder = countPrimes(arr);
      int[] copyArr = new int[primeHolder];
      for (int i = 0; i < arr.length; i++)
      if (isPrime(arr[i]) == true)
      copyArr[>Needs to start from 0<] = arr[i];


      return copyArr;


      int[] arrayMan = 3,5,10,15,13;


      At copyArr the position should be 0, followed by +1 everytime it finds a prime. If I were to give it i position, as in copyArr[i] = arr[i], then say the prime is at position 5, it would try to save the prime onto position 5of copyArr, which doesn't exist if there are only three primes in the original array, which would've given copyArr a length of only three.



      Something tells me a different for loop, or maybe even an additional one would help, but I can't see how I should implement it. Help is greatly appreciated!







      java for-loop primes






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 27 at 21:21









      TomTom

      1848 bronze badges




      1848 bronze badges

























          2 Answers
          2






          active

          oldest

          votes


















          1















          Have a second index variable int primeCount, and increment it whenever you find a prime. No need for a 2nd loop.



          In modern days of abundant memory, things are usually not done like this. If you don't have some extra hard requirements, you could just use a resizable ArrayList<Integer>, and add() stuff in there. (and convert it back to int[] at the end if needed). This is also better in this case, because typically your countPrimes call will run much slower than ArrayList reallocations.






          share|improve this answer


































            1















            Read your words carefully:




            At copyArr the position should be 0, followed by +1 everytime it
            finds a prime.




            That means that index in a new array does not depend on its position in the old array.
            Create a counter. And each time you place a prime number into a new array, increment it by 1. Thus you can always know where to put a new number.






            share|improve this answer



























              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55386644%2fmethod-to-copy-primes-from-one-array-to-another-in-java%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              1















              Have a second index variable int primeCount, and increment it whenever you find a prime. No need for a 2nd loop.



              In modern days of abundant memory, things are usually not done like this. If you don't have some extra hard requirements, you could just use a resizable ArrayList<Integer>, and add() stuff in there. (and convert it back to int[] at the end if needed). This is also better in this case, because typically your countPrimes call will run much slower than ArrayList reallocations.






              share|improve this answer































                1















                Have a second index variable int primeCount, and increment it whenever you find a prime. No need for a 2nd loop.



                In modern days of abundant memory, things are usually not done like this. If you don't have some extra hard requirements, you could just use a resizable ArrayList<Integer>, and add() stuff in there. (and convert it back to int[] at the end if needed). This is also better in this case, because typically your countPrimes call will run much slower than ArrayList reallocations.






                share|improve this answer





























                  1














                  1










                  1









                  Have a second index variable int primeCount, and increment it whenever you find a prime. No need for a 2nd loop.



                  In modern days of abundant memory, things are usually not done like this. If you don't have some extra hard requirements, you could just use a resizable ArrayList<Integer>, and add() stuff in there. (and convert it back to int[] at the end if needed). This is also better in this case, because typically your countPrimes call will run much slower than ArrayList reallocations.






                  share|improve this answer















                  Have a second index variable int primeCount, and increment it whenever you find a prime. No need for a 2nd loop.



                  In modern days of abundant memory, things are usually not done like this. If you don't have some extra hard requirements, you could just use a resizable ArrayList<Integer>, and add() stuff in there. (and convert it back to int[] at the end if needed). This is also better in this case, because typically your countPrimes call will run much slower than ArrayList reallocations.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 27 at 21:36

























                  answered Mar 27 at 21:33









                  battlmonstrbattlmonstr

                  2,9671 gold badge12 silver badges25 bronze badges




                  2,9671 gold badge12 silver badges25 bronze badges


























                      1















                      Read your words carefully:




                      At copyArr the position should be 0, followed by +1 everytime it
                      finds a prime.




                      That means that index in a new array does not depend on its position in the old array.
                      Create a counter. And each time you place a prime number into a new array, increment it by 1. Thus you can always know where to put a new number.






                      share|improve this answer





























                        1















                        Read your words carefully:




                        At copyArr the position should be 0, followed by +1 everytime it
                        finds a prime.




                        That means that index in a new array does not depend on its position in the old array.
                        Create a counter. And each time you place a prime number into a new array, increment it by 1. Thus you can always know where to put a new number.






                        share|improve this answer



























                          1














                          1










                          1









                          Read your words carefully:




                          At copyArr the position should be 0, followed by +1 everytime it
                          finds a prime.




                          That means that index in a new array does not depend on its position in the old array.
                          Create a counter. And each time you place a prime number into a new array, increment it by 1. Thus you can always know where to put a new number.






                          share|improve this answer













                          Read your words carefully:




                          At copyArr the position should be 0, followed by +1 everytime it
                          finds a prime.




                          That means that index in a new array does not depend on its position in the old array.
                          Create a counter. And each time you place a prime number into a new array, increment it by 1. Thus you can always know where to put a new number.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 27 at 21:35









                          Pavel SmirnovPavel Smirnov

                          3,3523 gold badges9 silver badges22 bronze badges




                          3,3523 gold badges9 silver badges22 bronze badges






























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55386644%2fmethod-to-copy-primes-from-one-array-to-another-in-java%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                              SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                              은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현