Java: parses string array items into, int, double, or string
•
Java
import java.io.File;
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)); } } }
The above is what I have done for my program What I want to do is convert the items in the string array created in the try section and further parse them into specific available variables, int, double, etc Should I parse strings and discard arrays when creating strings? I don't know how to continue parsing string arrays Any help would be great... I'm new to Java
Solution
import java.io.File;
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)); } } } }
Since double precision and floating-point number are almost the same, only one of them can save larger data values. I take all floating-point / double precision numbers as double precision numbers and integers as integer data I tested each string to see if it contained "." If it is a period character, I add it to my doubles ArrayList. If not, I add it to my integer ArrayList
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码