while ((str = in.readLine()) != null) {
if (str.trim().length() == 0) {
continue;
}
String[] values = str.split("\\t");
System.out.println("Printing file content:");
System.out.println("First field" + values[0] +
"Next field" + values[1]);
}
oplossing
String[] values = str.split("\\t", -1); // don't truncate empty fields
System.out.println("Printing file content:");
System.out.println("First field" + values[0] +
(values.length > 1 ? ", Next field" + values[1] : " there is no second field"));
http://www.dreamincode.net/forums/topic/238109-reading-input-separated-by-tab/
import java.util.*; public class zipApp { public static void main (String[] args) { System.out.println("How many enteries will you be using?"); Scanner s = new Scanner(System.in); int length = s.nextInt(); s.nextLine(); String[] array = new String[length]; for(int x = 0; x<array.length; x++) { System.out.println("Please enter the First name, Last name, and Zip code, all separated by a tab: "); array[x]=s.nextLine(); } ZIP[] zips = new ZIP[length];
String delimiter = "\\t"; String[] temp; for(int x = 0; x<array.length; x++) { temp = array[x].split(delimiter); ZIP z = new ZIP(temp[0], temp[1], Integer.parseInt(temp[2])); zips[x] = z; } for (int x = 0; x<zips.length; x++) System.out.println(zips[x]); } } public class ZIP { String first; String last; int zip; public ZIP(String first, String last, int zip) { this.first = first; this.last = last; this.zip = zip; } public String toString() { return first+"\t"+last+"\t"+zip; } }
Een ander aangeboden oplossing
import java.util.Scanner; public class Main { public static void main( String[] args ) { new Main(); } public Main() { Scanner s = new Scanner( System.in ); System.out.println( "Enter number of individuals" ); int numb = s.nextInt(); s.nextLine(); System.out.println( "Enter individuals" ); s.useDelimiter( "[\\t\r]" ); Individual[] individuals = new Individual[numb]; for ( int i = 0; i < numb; i++ ) { String firstname = s.next(); String lastname = s.next(); int zip = s.nextInt(); s.nextLine(); individuals[i] = new Individual( firstname, lastname, zip ); } for ( Individual i : individuals ) System.out.println( i ); } public class Individual { String firstname; String lastname; int zip; public Individual( String firstname, String lastname, int zip ) { this.firstname = firstname; this.lastname = lastname; this.zip = zip; } public String toString() { return firstname + " " + lastname + " " + zip; } } }
JAVA REGULAR EXPRESSION