Amal Amal - 1 year ago 78
Java Question

How to break elements in a string and put into a numerical array

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.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

class Prime
public static void main (String[] args)
Scanner s = new Scanner(;
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--)
counter = counter + 1;
if (counter ==2)
//Appended the Prime number to the String
primeNumbers = primeNumbers + i + " ";


Answer Source

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:


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

Append new items:


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

import java.util.ArrayList

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download