In: Computer Science
JAVA JAVA JAVA . I need to convert a string input to int array, for example if user enters 12 / 27 / 2020 , I want to store each value in a separate array and add them afterwards.
For converting string to an int you can use the java method Integer.parseInt()
But this is valid only for a string which is of length more than 0 and is a valid integer.
That is why in you case we cannot directly use this method, instead we have to convert your input in usable format.
For this
Please take a look at the Java code below for better understanding.
import java.util.*;
public class StringToIntArray{
//method which takes in input string and parses int array from it
static ArrayList<Integer> convert(String inp){
ArrayList<Integer> arr = new ArrayList<Integer>();
//return blank array if input is empty
if(inp.length()==0)
return arr;
int num=0;
//this variable keeps a track on wheather we have started making out number
boolean framing = false;
int i=0;
while(i<inp.length()){
//check if it is a digit
char x = inp.charAt(i);
if(x>='0'&&x<='9'){
framing=true;
num=num*10+(x-'0'); //extract the numerical digit from char representation
}else{
if(framing){
//if this character is not a digit and we were making the number,
//then it is time to stop
arr.add(num);
//prepare for next run
num=0;
framing=false;
}
}
i++;
}
//Once string ends we might still have a number in process which needs to be added
if(framing){
//if this character is not a digit and we were making the number,
//then it is time to stop
arr.add(num);
//prepare for next run
num=0;
framing=false;
}
return arr;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter string with integers.");
//read all of input in one string
String inp = sc.nextLine();
//call conversion method
ArrayList<Integer> arr = convert(inp);
System.out.println("Elements in INT array");
//print output array
for(int i=0;i<arr.size();i++){
System.out.print(arr.get(i)+" ");
}
}
}
Sample Output