My program reads first name then last name in separately , while I need it to read first and last name together java

Viewed 51

My program is for a voting system and the voting ballots have the candidate's first and last names. I am testing out just printing the information from the file but it separates the name of the candidates by spaces and not separate votes.

import java.io.*;
import java.util.*;


public class readFile {
   private Scanner x;
   public void openFile() {
       try {
           x = new Scanner (new File("SmallListBallots.txt"));
       }
       catch(Exception e) {
           System.out.println("could not find file");
       }   
   }
   public void readfile () {
       while(x.hasNext()) {
           String a =x.next();
           String b =x.next();
           String c =x.next();
           String d =x.next();
           
           System.out.printf("%s %s %s %s \n", a,b,c,d);
       }
   }
   public void closefile() {
       x.close();
   }
}

the text that is being read in:

VoterID First Choice    Second Choice   Third Choice

1001    Dalinar Kholin  Jasnah Kholin   Renarin Kholin

1002    Dalinar Kholin  Jasnah Kholin   Kaladin Stormblessed

1003    Torol Sadeas    Meridas Amaram  Shallan Davar

The program currently displays

1001 Dalinar Kholin Jasnah 
Kholin Renarin Kholin 1002 
Dalinar Kholin Jasnah Kholin 
Kaladin Stormblessed 1003 Torol 
Sadeas Meridas Amaram Shallan 
Davar

My goal is to display their full name as one "vote" and then code the rest of the program so that I can count how many votes each candidate got in the first round. Goal output:

Dalinar Kholin  Jasnah Kholin   Renarin Kholin

Dalinar Kholin  Jasnah Kholin   Kaladin Stormblessed

Torol Sadeas    Meridas Amaram  Shallan Davar
1 Answers

try this

public void readfile () {
    Pattern pattern = Pattern.compile("[a-z|A-Z]+\\s[a-z|A-Z]+");
    while(x.hasNext()) {
        Matcher matcher = pattern.matcher(x.nextLine());
        StringBuilder stringBuilder = new StringBuilder();
        while (matcher.find()) {
            stringBuilder.append(matcher.group());
            stringBuilder.append("\t");
        }
        System.out.println(stringBuilder.toString());
    }
}
Related