简体   繁体   中英

Split comma and one by one value show on android

String ecg1 = "10,20,100,-100,20,10,110,-105,15,25"; 
Double.parseDouble(model.getEcg1().split(",") + "\n")

This is not working. I want the result like below ie value one by one column wise:

10
20
100
-100
20
10
110
-105
15
25

split will create a array of String , and not a single String , so you can't parse it to Double . After splitting the ecg1 , you can iterate through the list and print it.

try {
    String ecg1 = "10,20,100,-100,20,10,110,-105,15,25";
    String[] items = ecg1.split(",");
    ArrayList<Double> numbers = new ArrayList();
    for (int i=0; i<items.length; i++) {
        numbers.add(Double.parseDouble(items[i]));
    }
} catch (NumberFormatException e) {
    e.printStackTrace();
}

You can do anything you want with the list of double numbers. Double.parseDouble can throw exception so that you should catch it.

If you just want to generate a string which values are displayed as a column, there will be a simpler solution

String ecg1 = "10,20,100,-100,20,10,110,-105,15,25";
String result = ecg1.replace(",", "\n");
String ecg1 = "10,20,100,-100,20,10,110,-105,15,25";
String[] ecg2=ecg1.split(",");

then you can iterate through ecg2 with a normal loop

for(int i=0;i<ecg2.length;i++)
{
//ecg2[i] is the element you want
}

If you use Java 8 you just can do

String str = String.join("\n", ecg1.split(','));
System.out.println(str);

Try converting the given string into String Array and then insert the items by parsing into Double data type Like in the code given below:-

String[] items = ecg1.split(",");
ArrayList<Double> numbers = new ArrayList<Double>();
for (int i=0;i<items.length;i++) {
    numbers.add(Double.parseDouble(items[i]));
}

This will not work as model.getEcg1().split(",") will return a string array. You can not parse whole string array to double by this Double.parseDouble(model.getEcg1().split(",")) and adding \n is again not going to work.

if you only want the desired output to print you can try this below code

String ecg1 = "10,20,100,-100,20,10,110,-105,15,25";
    Stream<String> stream = Arrays.stream(ecg1.split(","));
    stream.forEach(x -> System.out.println(x));

if you want to store in Collection do as below

String ecg1 = "10,20,100,-100,20,10,110,-105,15,25";
    List<Double> li=new ArrayList<>();
    Stream<String> stream = Arrays.stream(ecg1.split(","));
    stream.forEach(x -> li.add(Double.parseDouble(x)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM