Convert String[] with text to double[] - java

I have an Arraylist that I want to convert to a double[] array. I first convert the Arraylist to a String []. I then try to convert the String[] to a double[] but fail in the process. Here's the issue: the string contains some text, as well as some numbers with decimals. I want to convert only the numbers and decimals to a double[] array and simply delete the text. However, I only know how to delete the text with a String, not a String[]. Please take a look:
import java.util.ArrayList;
import java.util.List;
import jsc.independentsamples.SmirnovTest;
public class example {
public static void main(String[] arg) throws Exception {
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
list1.add("RSP0001,1.11,1.22");
list1.add("RSP0002,2.11,2.22");
list1.add("RSP0003,3.11,3.22");
list1.add("RSP0004,4.11,4.22");
String[] str1 = new String[list1.size()];
str1 = list1.toArray(str1);
str1.replaceAll("RSP_\\d+","");
double array1 = Double.parseDouble(str1);
System.out.println(array1);
}
}
Two errors come from this: the first is a "cannot find symbol" error at str1.replaceAll. The second is a "method parseDouble" error at "Double.parseDouble". The issue there is I need a String instead of a String[].
Any ideas on how to convert my String[] to a double[] ?
Thanks,
kjm

You need to split each String in list1 on "," and attempt to parse each String that gets split out:
ArrayList<Double[]> results = Lists.newArrayList();
for( String s : list1 ) {
String[] splitStrings = s.split(",");
Double[] doublesForCurrentString = new Double[splitStrings.length];
for(int i=0; i<splitStrings.length; i++){
try {
doublesForCurrentString[i] = Double.valueOf(splitStrings[i]);
} catch( NumberFormatException ex ) {
// No action.
}
}
results.add(doublesForCurrentString);
}
Double[][] doubleArray = (Double[][])results.toArray();
Crucial points:
EDIT: As #Tim Herold points out, you're probably better of performance-wise avoiding attempting to parse content you know to be non-numeric. In this case, I'd still split first and then just put in code that prevents you from attempting to parseDouble() on the first split String in each line, rather than trying to do String replacement before the split; that will be faster (and if we're not concerned about performance, then try/catch is perfectly fine and more readable). ORIGINAL: You need a try/catch when you try to parse the doubles, in case there's any invalid input. Bonus: you don't need to remove the non-numeric text now, you can just let this try/catch handle it.
Your strings have two doubles in each of them. You're not going to be able to just strip the text at the beginning and then parse the rest, because it's not going to be a valid double.
ArrayLists are generally easier to use; I'd opt for returning ArrayList<Double> (or ArrayList<ArrayList<Double>>) over Double[] or Double[][] any day of the week. There are certainly situations where I'd do differently, but yours doesn't sound like one of them to me.

Loop throug the Array:
foreach String[]
double[counter] = parseToDouble(String[counter])
EDIT:
Java:
String[] str1 = list1.toArray(str1);
double[] dou1 = new double[str1.length]
for(int counter = 0; counter < str1.length;counter++)
dou1[counter] = Double.parseDouble(str1[counter].replaceAll("RSP_\\d+",""));

Use this
String[] str1 = new String[list1.size()];
str1 = list1.toArray(str1);
double[] doubleArray = new double[str1.length]
int i=0;
for(String s:str1){
doubleArray[i] = Double.valueOf(s.trim());
i++;
}

This will do the work.
double[] doubles = new double[array1.length];
for(int i=0; i<array1.length; i++){
doubles[i] = Double.valueOf(array1[i])
}
Thanks SmartLemon for the edit, you could do this too instead of using a String[]:
double[] doubles = new double[list1.size()];
for(int i=0; i<list1.size(); i++){
doubles[i] = Double.valueOf(list1.get(i).replace("RSP_\\d+",""));
}
EDIT: So yes, you need a delimiter:
double[] doubles = new double[array1.length*2]; //multiply by 2 because you really have 8 numbers not 4
String [] array2 = null;
for(String string: array1) {
array2 = string.split(",");
for(int i=0; i<array2.length; i++){
doubles[i] = Double.valueOf(array2[i]);
}
}
this should do the work for sure.

I would do this:
make array
convert to string
then this code
for (String s: list1) {
boolean obtained = false;
double tempD;
try {
tempD = Double.parseDouble(s);
obtained = true;
} catch (Exception e) {
e.printStackTrace();
}
if (obtained) {
list2.add(tempD);
}
}

Related

Merge two or more elements of ArrayList

Is there any possibility to merge two elements of ArrayList?
This is my array = [u,s,m,a,t,t]
and I want to have something like this = [us,matt]
I've tried to use toString(), and replace('',''), but it merges whole array [usmatt].
Any other options?
I don't know exactly what you mean but what you try to achieve could be done this way:
Pseudo-code:
String[] array1 = [u,s,m,a,t,t]
String a = array[0]+array[1]
String b = array[2]+array[3]+array[4]+array[5]
String[] array2 = [a,b]
Try this: (For any length ArrayList.)
public static void MergeArrayList() {
ArrayList<Character> Array = new ArrayList<Character>() {{ add('u');add('s');
add('m');add('a');add('t');add('t');}};
ArrayList<String> newArray = new ArrayList<>();
int n=2; // Change this to indicate where you need to make the cut.
String str="";
for (int i=0;i<Array.size();i++) {
if (i==n) {
newArray.add(str);
str="";
}
str += Array.get(i);
}
newArray.add(str);
System.out.println(Array);
System.out.println(newArray);
}

how to separate values in a string index that are char and int

okay basically im wanting to separate the elements in a string from int and char values while remaining in the array, but to be honest that last parts not a requirement, if i need to separate the values into two different arrays then so be it, id just like to keep them together for neatness. this is my input:
5,4,A
6,3,A
8,7,B
7,6,B
5,2,A
9,7,B
now the code i have so far does generally what i want it to do, but not completely
here is the output i have managed to produce with my code but here is where im stuck
54A
63A
87B
76B
52A
97B
here is where the fun part is, i need to take the numbers and the character values and separate them so i can use them in a comparison/math formula.
basically i need this
int 5, 4;
char 'A';
but of course stored in the array that they are in.
Here is the code i have come up with so far.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
public class dataminingp1
{
String[] data = new String[100];
String line;
public void readf() throws IOException
{
FileReader fr = new FileReader("C:\\input.txt");
BufferedReader br = new BufferedReader(fr);
int i = 0;
while ((line = br.readLine()) != null)
{
data[i] = line;
System.out.println(data[i]);
i++;
}
br.close();
System.out.println("Data length: "+data.length);
String[][] root;
List<String> lines = Files.readAllLines(Paths.get("input.txt"), StandardCharsets.UTF_8);
root = new String[lines.size()][];
lines.removeAll(Arrays.asList("", null)); // <- remove empty lines
for(int a =0; a<lines.size(); a++)
{
root[a] = lines.get(a).split(" ");
}
String changedlines;
for(int c = 0; c < lines.size(); c++)
{
changedlines = lines.get(c).replace(',', ' '); // remove all commas
lines.set(c, changedlines);// Set the 0th index in the lines with the changedLine
changedlines = lines.get(c).replaceAll(" ", ""); // remove all white/null spaces
lines.set(c, changedlines);
changedlines = lines.get(c).trim(); // remove all null spaces before and after the strings
lines.set(c, changedlines);
System.out.println(lines.get(c));
}
}
public static void main(String[] args) throws IOException
{
dataminingp1 sarray = new dataminingp1();
sarray.readf();
}
}
i would like to do this as easily as possible because im not to incredibly far along with java but i am learning so if need be i can manage with a difficult process. Thank you in advance for any at all help you may give. Really starting to love java as a language thanks to its simplicity.
This is an addition to my question to clear up any confusion.
what i want to do is take the values stored in the string array that i have in the code/ input.txt and parse those into different data types, like char for character and int for integer. but im not sure how to do that currently so what im asking is, is there a way to parse these values all at the same time with out having to split them into different arrays cause im not sure how id do that since it would be crazy to go through the input file and find exactly where every char starts and every int starts, i hope this cleared things up a bit.
Here is something you could do:
int i = 0;
for (i=0; i<list.get(0).size(); i++) {
try {
Integer.parseInt(list.get(0).substring(i, i+1));
// This is a number
numbers.add(list.get(0).substring(i, i+1));
} catch (NumberFormatException e) {
// This is not a number
letters.add(list.get(0).substring(i, i+1));
}
}
When the character is not a number, it will throw a NumberFormatException, so, you know it is a letter.
for(int c = 0; c < lines.size(); c++){
String[] chars = lines.get(c).split(",");
String changedLines = "int "+ chars[0] + ", " + chars[1] + ";\nchar '" + chars[0] + "';";
lines.set(c, changedlines);
System.out.println(lines.get(c));
}
It is very easy, if your input format is standartized like this. As long as you dont specify more (like can have more than 3 variables in one row, or char can be in any column, not only just third, the easiest approach is this :
String line = "5,4,A";
String[] array = line.split(",");
int a = Integer.valueOf(array[0]);
int b = Integer.valueOf(array[1]);
char c = array[2].charAt(0);
Maybe something like this will help?
List<Integer> getIntsFromArray(String[] tokens) {
List<Integer> ints = new ArrayList<Integer>();
for (String token : tokens) {
try {
ints.add(Integer.parseInt(token));
} catch (NumberFormatException nfe) {
// ...
}
}
return ints;
}
This will only grab the integers, but maybe you could hack it around a bit to do what you want :p
List<String> lines = Files.readAllLines(Paths.get("input.txt"), StandardCharsets.UTF_8);
String[][] root = new String[lines.size()][];
for (int a = 0; a < lines.size(); a++) {
root[a] = lines.get(a).split(","); // Just changed the split condition to split on comma
}
Your root array now has all the data in the 2d array format where each row represents the each record/line from the input and each column has the data required(look below).
5 4 A
6 3 A
8 7 B
7 6 B
5 2 A
9 7 B
You can now traverse the array where you know that first 2 columns of each row are the numbers you need and the last column is the character.
Try this way by using getNumericValue() and isDigit methods. This might also work,
String myStr = "54A";
boolean checkVal;
List<Integer> myInt = new ArrayList<Integer>();
List<Character> myChar = new ArrayList<Character>();
for (int i = 0; i < myStr.length(); i++) {
char c = myStr.charAt(i);
checkVal = Character.isDigit(c);
if(checkVal == true){
myInt.add(Character.getNumericValue(c));
}else{
myChar.add(c);
}
}
System.out.println(myInt);
System.out.println(myChar);
Also check, checking character properties

JTextField to int[] array?

I'm working on my graphic user interface for a application I'm creating. Basically there is this JTextField that the user has to input integers. For example
25, 50, 80, 90
Now, I have this other class that needs to get those values and put them in an int Array.
I've tried the following.
guiV = dropTheseText.getText().split(",");
And in the other class file I retieve the String, but I have no idea how to get the value for each one.
In the end I'm just trying to get something like
int[] vD = {textfieldvaluessplitbycommahere};
Still fairly new to Java but this has me crazy.
private JTextField txtValues = new JTextField("25, 50, 80, 90");
// Strip the whitespaces using a regex since they will throw errors
// when converting to integers
String values = txtValues.getText().replaceAll("\\s","");
// Get the inserted values of the text field and use the comma as a separator.
// The values will be returned as a string array
private String[] strValues = values.split(",");
// Initialize int array
private int[] intValues = new int[strValues.length()];
// Convert each string value to an integer value and put it into the integer array
for(int i = 0; i < strValues.length(); i++) {
try {
intValues[i] = Integer.parseInt(strValues[i]);
} catch (NumberFormatException nfe) {
// The string does not contain a parsable integer.
}
}
As you are fairly new to Java, rather than giving you the code snippet, I will just give you some indications:
Use the String class: it has a method for splitting a String into an array of Strings.
Then use the Integer class: it has a method to convert a String to an int.
You cant do it directly, you may need to add a method to convert your string array to int array. Something like this:
public int[] convertStringToIntArray(String strArray[]) {
int[] intArray = new int[strArray.length];
for(int i = 0; i < strArray.length; i++) {
intArray[i] = Integer.parseInt(strArray[i]);
}
return intArray;
}
Pass your guiV to this method and get back the int array
a simple solution is a function hat does the conversion:
public static int[] convertTextFieldCommaSeparatedIntegerStringToIntArray(String fieldText) {
String[] tmp = fieldText.split(",");
int[] result = new int[tmp.length];
for(int i = 0; i < tmp.length; i++) {
result[i] = Integer.parseInt(tmp[i].trim());
}
return result;
}
The essential methods are:
split for splitting the original input at the comma.
parseInt for converting a String -> int. The valueOf function of Integer is an option but then you have to convert String -> Integer -> int.
Note:
You should use trim to eliminate white-spaces. Furthermore, you should catch the NumberFormatException thrown by parseInt. As an unchecked exception you do not need to catch it, but it is always wise to check user input and sanitize it if necessary.
Try this code:
public int[] getAsIntArray(String str)
{
String[] values = str.getText().split(",");
int[] intValues = new int[values.length];
for(int index = 0; index < values.length; index++)
{
intValues[index] = Integer.parseInt(values[index]);
}
return intValues;
}

Getting the strings from line strings, from an ArrayList in java)

I have an ArrayList:
private static ArrayList<String> lista;
static void fileReading() {
inp = new LineNumberReader(new BufferedReader(new InputStreamReader(new FileInputStream(inFileNev), "ISO8859-1")));
String sor;
while ((sor = inp.readLine()) != null) {
lista.add(sor);
lista.add(System.getProperty("line.separator"));
}
I need the strings from this, not the whole line (like "pakcage" and "asd;").
I tried these but none of these works:
String[] temp=null;
for(String s : lista) {
temp = s.split("\\W+");
}
System.out.println(temp);
I get: [Ljava.lang.String;#6ef53890
If I write println Within the for I get the same, just more of this.
If I use this:
String str ="" ;
for(int i=0; i<lista.size(); i++){
str+=lista.get(i)+" ";
String[] temp = new String[str.length()];
for(int i=0; i < str.length(); i++) {
temp[i]=str.valueOf(i);
System.out.println(temp[i]);
}
I get only numbers, and can't figure out how to get the strings from str.
I need to know the strings indexes, and replace them later.
In this example
String[] temp=null;
for(String s : lista) {
temp = s.split("\\W+");
}
System.out.println(temp);
Trying to print an object will result in invoking its toString() method. In fact you are not printing any String value, but an array of Strings, which is an object.
In your second snippet str.valueOf(i); is returning a "string representation of the int argument."
What you probably want to do is
Split your elements into some table, like you did here temp = s.split("\\W+");
And then iterate through the array using foreach:
Which would look like
for (String s : yourStringArray) {
System.out.println(s);
}
Hope this helps... after almost a year ;)

Using String.split() to access numeric values

i tried myself lot but can't get a solution so i'm asking help.
i have an string String input="---4--5-67--8-9---";
now i need to convert in into an string array which will look like:
String [][]output={{4},{5},{67},{8},{9}};
i tried with split() and
java.util.Arrays.toString("---4--5-67--8-9---".split("-+")
but can't find the desired answer. so what to do?
actually i need the value 4,5,67,8,9.but i'm not sure how to find them. i will treat the values as integer for further processing
String[] numbers = "---4--5-67--8-9---".split("-+");
String[][] result = new String[numbers.length][1];
for (int i = 0; i < numbers.length; i++) {
result[i][0] = numbers[i];
}
Update: to get rid of the initial empty value, you can get a substring of the input, like:
int startIdx = 0;
char[] chars = input.toCharArray();
for (int i = 0; i < chars.length; i ++) {
if (Character.isDigit(chars[i])) {
startIdx = i;
break;
}
}
input = input.substring(startIdx);
(or you can check them for not being empty (String.isEmpty()) when processing them later.)
First, here is the answer to your question. This code will generate a two-dimensional array where each element is an array consisting of a single numeric string.
final String input = "---4--5-67--8-9---";
// desired output: {{4},{5},{67},{8},{9}}
// First step: convert all non-digits to whitespace
// so we can cut it off using trim()
// then split based on white space
final String[] arrayOfStrings =
input.replaceAll("\\D+", " ").trim().split(" ");
// Now create the two-dimensional array with the correct size
final String[][] arrayOfArrays = new String[arrayOfStrings.length][];
// Loop over single-dimension array to initialize the two-dimensional one
for(int i = 0; i < arrayOfStrings.length; i++){
final String item = arrayOfStrings[i];
arrayOfArrays[i] = new String[] { item };
}
System.out.println(Arrays.deepToString(arrayOfArrays));
// Output: [[4], [5], [67], [8], [9]]
However, I think what you really need is an array of Integers or ints, so here is a revised solution:
final String input = "---4--5-67--8-9---";
// Convert all non-digits to whitespace
// so we can cut it off using trim()
// then split based on white space
final String[] arrayOfStrings =
input.replaceAll("\\D+", " ").trim().split(" ");
// Now create an array of Integers and assign the values from the string
final Integer[] arrayOfIntegers = new Integer[arrayOfStrings.length];
for(int i = 0; i < arrayOfStrings.length; i++){
arrayOfIntegers[i] = Integer.valueOf(arrayOfStrings[i]);
}
System.out.println(Arrays.toString(arrayOfIntegers));
// Output: [4, 5, 67, 8, 9]
// Or alternatively an array of ints
final int[] arrayOfInts = new int[arrayOfStrings.length];
for(int i = 0; i < arrayOfStrings.length; i++){
arrayOfInts[i] = Integer.parseInt(arrayOfStrings[i]);
}
System.out.println(Arrays.toString(arrayOfInts));
// Output: [4, 5, 67, 8, 9]
Whether you use the Integer or the int version really depends on whether you want to just do some math (int) or need an object reference (Integer).
String[] result = "---4--5-67--8-9---".split("-+");
int i;
for (i = 0; i < result.length; i++) {
if (result[i].length() > 0) {
System.out.println(result[i]);
}
}
gives me output:
4
5
67
8
9
public class split{
public static void main(String[] argv){
String str="---4--5-67--8-9---";
String[] str_a=str.split("-+");
}
}
This seems to working for me.
Using a regex pattern seems more natural in this case:
public class split {
public static int[] main(String input) {
ArrayList<String> list = new ArrayList() ;
Pattern pattern = Pattern.compile("[0-9]") ;
Matcher matcher = pattern.matcher(input) ;
String match = null ;
while( ( match = matcher.find() ) === true ) {
list.add(match) ;
}
String[] array = list.toArray( new String[ ( list.size() ) ]() ) ;
return array ;
}
}
String input="---4--5-67--8-9---";
Scanner scanner = new Scanner(input).useDelimiter("-+");
List<Integer> numbers = new ArrayList<Integer>();
while(scanner.hasNextInt()) {
numbers.add(scanner.nextInt());
}
Integer[] arrayOfNums = numbers.toArray(new Integer[]{});
System.out.println(Arrays.toString(arrayOfNums));
I thought the following is quite simple, although it uses List and Integer arrays, Its not that an overhead for small strings:
For simplicity, I am returning a single dimension array, but can be easily modified to return an array you want. But from your question, it seems that you just want a list of integers.
import java.util.*;
public class Test {
public static void main(String[] args) throws Throwable {
String input = "---4--5-67--8-9---";
System.out.println(split(input).length); // 5
}
public static Integer[] split(String input) {
String[] output = input.split("\\-+");
List<Integer> intList = new ArrayList<Integer>(output.length);
// iterate to remove empty elements
for(String o : output) {
if(o.length() > 0) {
intList.add(Integer.valueOf(o));
}
}
// convert to array (or could return the list itself
Integer[] ret = new Integer[intList.size()];
return intList.toArray(ret);
}
}
I might be late to the party but I figured I'd give the guava take on this.
String in = "---4--5-67--8-9---";
List<String> list = Lists.newArrayList(Splitter.on("-").omitEmptyStrings().trimResults().split(in));
System.out.println(list);
// prints [4, 5, 67, 8, 9]

Categories