Reputation: 43
So I am trying to get them separated but for some reason I need to add exclamations at the end which works but in the real world isn't how it is usually formatted. How could I do this without adding exclamations at the end only between words? The text file reads: John!Smith!85! Matthew!Smith!82! The code is as follows: '''
package cmpsci111;
import java.util.*;
import java.io.*;
/**
*
* @author Matt
*/
public class Files2 {
public static void main(String[] args) throws IOException{
File f = new File("scores.txt");
String firstname = "";
String lastname = "";
int score = 0;
Scanner input = new Scanner(f);
while(input.hasNextLine()){
input.useDelimiter("!");
firstname = input.next();
lastname=input.next();
score = input.nextInt();
System.out.println(firstname+ " "+ lastname + " " + score);
}
input.close();
}
}
'''
Upvotes: 0
Views: 38
Reputation: 11
useDelimiter can accept regular expression as argument. "!|\r\n|\n|\r" can be used to separate by ! or line ending symbols. Text file can look like:
John!Smith!85
Matthew!Smith!82
Modified main method:
public static void main(String[] args) throws IOException{
File f = new File("scores.txt");
String firstname = "";
String lastname = "";
int score = 0;
Scanner input = new Scanner(f);
input.useDelimiter("!|\r\n|\n|\r"); //Before while loop
while(input.hasNextLine()){
//input.useDelimiter("!"); // No need
firstname = input.next();
lastname=input.next();
score = input.nextInt();
System.out.println(firstname+ " "+ lastname + " " + score);
}
input.close();
}
Upvotes: 1