简体   繁体   English

Java文件扫描多行和变量类型

[英]Java File Scanning multiple lines and variable types

Trying to scan a file that has numerous lines, multiple types of variables and multiple segments (maybe not the best word to describe it?) 尝试扫描具有许多行,多种类型的变量和多个段的文件(也许不是描述它的最佳词吗?)

Basically this is my file input (placeholders to better explain): 基本上这是我的文件输入(占位符可以更好地解释):

String1
int1
double1

String2
int2
double2

String3
int3
double3

I'm wondering what the best way to get this data read so that it can be used in basic equations. 我想知道获取此数据以便在基本方程式中使用的最佳方法是什么。

I've looked into using Scanner but it seems due to the multiple lines I may be better using BufferedReader and then converting each line from a string to say an integer or a double if needed (or am I over complicating this?). 我已经研究过使用Scanner了,但是由于有多行,所以我似乎最好使用BufferedReader,然后将每行从一个字符串转换为一个整数或一个双精度(如果需要的话)(或者我是否使这个复杂化了?)。

I have some previous experience with C++ but nothing further than basic for loops and arrays, so please try to keep this as clear and beginner proof as possible. 我以前有一些C ++的经验,但是除了循环和数组的基础知识外,别无其他,因此请尽量保持清晰和初学者的证明。

Since your file goes string,int,double,blank line,string,int,double,... We can easily use a while loop for this. 由于您的文件为string,int,double,空白行,string,int,double,...我们可以轻松地为此使用while循环。 Make 3 Arraylists that hold the corresponding strings, ints, and doubles. 制作3个包含相应字符串,整数和双精度的Arraylist。

public static void main(String[] args){
    Scanner file = new Scanner(new File("file path here"));

    ArrayList<String> strings = new ArrayList<String>();
    ArrayList<Integer> ints = new ArrayList<Integer>();
    ArrayList<Double> doubles = new ArrayList<Double>();

    while(file.hasNextLine()){
        strings.add(file.nextLine());
        ints.add(Integer.parseInt(file.nextLine()));
        doubles.add(Double.parseDouble(file.nextLine()));
        if(file.hasNextLine())
            file.nextLine();
    }
    file.close();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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