简体   繁体   中英

Splitting a line from a textfile into two separate Arrays

I must apologize in advance if this question has been answered, I have not been able to find an answer to this problem on the forum thus far.

I am working on a Project Euler Problem, Problem 54 to be exact, and I am required to read in 1000 lines of data, each line contains two randomly generated Poker hands, the first half of the line being Player 1's hand, the second being Player 2's.

Below is an example of the layout of the document:

8CTSKC9H4S 7D2S5D3SAC

5CAD5DAC9C 7C5H8DTDKS

3H7H6SKCJS QHTDJC2D8S

TH8H5CQSTC 9H4DJCKSJS

What I have done thus far is manually make two documents copying the second "Hand" from each line and adding that to the new document. However I did that twice and came up with two different results, so I think I am making an error somewhere with all the copying. Below is an example of the the above function I used:

    ArrayList<String> player1 = new ArrayList<String>();
    ArrayList<String> player2 = new ArrayList<String>();
    String file1 = "FilePath1";
    String file2 = "FilePath2";
    Scanner input1  = new Scanner(new File(file1));
    while(input1.hasNext()) {
        player1.add(input1.nextLine());
    }
    Scanner input2  = new Scanner(new File(file2));
    while(input2.hasNext()) {
        player2.add(input2.nextLine());
    }

    input1.close();
    input2.close();

What I would like to know is how could I read only the first hand into an ArrayList, and then only the second hand into another one. Without having to create two separate documents and risk compromising the data. I am not sure how I would be able to use the Split function here if that is the way to go. I am fairly new to programming, I am trying to teach myself, so I apologize if this is a overly simple problem.

Thank you very much in advance

You can split on space (all whitespace)

For example:

String currLine = input1.nextLine();
//This only needed if you are not sure if the input will have leading/trailing space
currLine = currLine.trim();
String[] split = currLine.split("\\s+");
//Ensuring the line read was properly split
if(split.length == 2) {
    //split[0] will have the first hand
    player1.add(split[0]);
    //split[1] will have the second hand
    player2.add(split[1]);
}

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