[英]Java: Parsing String array items into, 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 have already for my program. 上面是我已经为我的程序。 What I want to do is convert the items from the string array created in the try section and parse that further into specific useable variables, int, double ect.
我想要做的是转换在try部分中创建的字符串数组中的项目,并进一步解析为特定的可用变量int,double等。 Should I instead just parse the string when its created and scrap the array?
我是否应该在创建字符串时解析字符串并废弃数组? I am not sure how to proceed in parsing the string array.
我不知道如何继续解析字符串数组。 Any help would be great...I am really new to java...
任何帮助都会很棒...我对java很新...
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 doubles and floats and practically the same thing just one of them being able to hold a larger data value, i took all floats/doubles in as a double and the integers as a int. 由于双精度和浮点数几乎相同,只有其中一个能够保存更大的数据值,我将所有浮点数/双精度数作为双精度数并将整数作为整数数据。 I tested each string to see if it contained a "."
我测试了每个字符串,看它是否包含“。” period character and if it did, i added it to my doubles arraylist and if it didn't, i added it to my integers arrayList.
句点字符,如果它,我把它添加到我的双打arraylist,如果没有,我将它添加到我的整数arrayList。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.