Amal Amal - 1 month ago 11
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.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);
}
}

Answer

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