+ 1
How can i separate numbers from a string and then add it to an Integer array in java?
3 Antworten
+ 1
suppose str is the string that contains number as well as alphabets.
l=str.length ();
int a []=new int [10];
p=0;
for (i=0;i <l;i++)
{
char ch=str.charAt (i);
if (ch>=48 && ch <=57)
a [p]=(int)ch-48;
p++;
}
+ 1
see my code for more information regarding this .
https://code.sololearn.com/coo5NjjQNNxf/?ref=app
+ 1
I just asked a similar question. This code will take user input made up of integers and characters and then parse the input on the "-" and then create an arraylist out of it. Here is the code. I added the print array at the end to show that the arraylist exists and the first print shows the parsed string. Credit to "ace" and "ChaoticDawg" for guiding me.
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
public class PairCalc
{
public static void main(String[] args) {
Scanner rawinput = new Scanner(System.in); // scanner for input
List<Integer> numbers = new ArrayList<>(); // create ArrayList
for(String num: rawinput.nextLine().split("-")) { //for loop splitting int's out of rawinput
numbers.add(Integer.parseInt(num)); //add int's to ArrayLIst "numbers"
}
for(Integer num: numbers) { //for loop printing ArrayList "numbers"
System.out.println(num);
}
}
}