Java: Parsing String array elements in, int, double or string

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;


public class DataStructure {
 public static void main(String[] aArgs) {
     String [] fileContents=new String[6];
     File testFile = new File ("testFile.txt");

     try{
         Scanner testScanner = new Scanner(testFile);
         int i=0;
         while (i < fileContents.length){
             fileContents[i]=testScanner.nextLine();
         i++;
         }
         testScanner.close();
     }
 catch (FileNotFoundException e) {
      e.printStackTrace();
 }
     finally{
         System.out.println(Arrays.toString(fileContents)); 

     }
     }

 }

Above is what I already have for my program. What I want to do is convert the elements from the array of strings created in the try section and analyze them further on the specific variables used, int, double ect. Should I instead just parse the string when it is created and the array is broken? I am not sure how to start parsing an array of strings. Any help would be great ... I'm really new to java ...

+4
source share
1 answer
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;

public class DataStructure {
 public static void main(String[] aArgs) {
     String [] fileContents=new String[6];
     ArrayList<Integer> intList = new ArrayList<>();
     ArrayList<Double> doubList = new ArrayList<>();

     File testFile = new File ("testFile.txt");

     try{
         Scanner testScanner = new Scanner(testFile);
         int i=0;
         while (i < fileContents.length){
             fileContents[i]=testScanner.nextLine();
             i++;
         }
         testScanner.close();
     }
 catch (FileNotFoundException e) {
      e.printStackTrace();
 }
     finally{
         System.out.println(Arrays.toString(fileContents)); 
         for( int i = 0; i < fileContents.length; i++ ){
            if(fileContents[i].contains(".")){
                doubList.add(Double.parseDouble(fileContents[i]));
            }else{
                intList.add(Integer.parseInt(fileContents[i]));
            }
         }
         for(int i = 0; i < intList.size(); i++ ){
            System.out.println(intList.get(i));
         }
         System.out.println(" ");
         for(int i = 0; i < doubList.size(); i++ ){
            System.out.println(doubList.get(i));
         }
     }
     }

 }

, , , float/double double int. , , ".". , , , arrayList.

0

Source: https://habr.com/ru/post/1612654/


All Articles