0

The following java code prints the set of prime numbers below the given numbers as a string! how can i get those numbers in the string into an integer array?

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

class Prime
{
    public static void main (String[] args)
    {
        Scanner s = new Scanner(System.in);
        int x = s.nextInt();
        int i =0;
        int num =0;
        //Empty String
        String  primeNumbers = "";

        for (i = 1; i <= x; i++)
        {
            int counter=0;
            for(num =i; num>=1; num--)
            {
                if(i%num==0)
                {
                    counter = counter + 1;
                }
            }
            if (counter ==2)
            {
                //Appended the Prime number to the String
                primeNumbers = primeNumbers + i + " ";
            }
        }

        System.out.println(primeNumbers);
    }
}
nbrooks
  • 18,126
  • 5
  • 54
  • 66
Amal
  • 91
  • 1
  • 1
  • 10
  • Possible duplicate of [How to split a string in Java](http://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java) – nbrooks Oct 22 '16 at 23:03

1 Answers1

0

Just change the type of primeNumbers to the desired container, like: ArrayList<Integer>.

And, instead of using the + operator, append items to the collection with the add method.

Like so:

Initialization:

ArrayList<Integer> primeNumbers = new ArrayList<Integer>();

Append new items:

primeNumbers.add(i);

And don't forget to add an import to the ArrayList class:

import java.util.ArrayList

MordechayS
  • 1,552
  • 2
  • 19
  • 29
  • Thanx alot! :) how can get 3 numbers frm the array list so that their sum is the number that i enter? that would be a great help – Amal Oct 22 '16 at 23:04
  • @Amal Happy to help. First, If this answer solved your issue, please mark it as accepted. Second, I don't really understand your next question. Could you please edit and add an example of the desired result? – MordechayS Oct 22 '16 at 23:08
  • i meant if we give input 65! i need to get 3 numbers from the arraylist thats sums to 65 and display them! eg- 23 ,31 and 11 – Amal Oct 22 '16 at 23:13
  • @Amal Read more about ArrayList and iterating through it with a 'foreach' loop, for example. See: http://stackoverflow.com/questions/18410035/ways-to-iterate-over-a-list-in-java. – MordechayS Oct 22 '16 at 23:16
  • i don't understand how to do please help me i am less used to arraylists! – Amal Oct 22 '16 at 23:22
  • @Amal Calm down. This isn't rocket-science. :) You have the tutorial above for iterating through lists, and I can see you are comfortable with conditions. Put it all together + google = You will be OK. If you really try and don't get the desired result, feel free to post a second question, and show what you tried and what seems to be the problem. – MordechayS Oct 22 '16 at 23:26