Results 1 to 4 of 4
- 02-12-2009, 04:18 PM #1
Member
- Join Date
- Feb 2009
- Posts
- 7
- Rep Power
- 0
Use of Scanner class and Delimiter
How would i use the scanner class to read a textfile called "music". It contains data in the form;
David/Grey#Elton/John#Micheal/Buble#Celine/Dion#
/ - splits up the name
# - marks end of person
i would like to put them in to the fields 'forename' and 'surname' for printing.
- 02-12-2009, 04:52 PM #2
Member
- Join Date
- Feb 2009
- Location
- Italy
- Posts
- 51
- Rep Power
- 0
an easy solution could be:
the important parts are the settings of delimiters in scanner and in split....Java Code:scan = new Scanner(new File("music.txt")); scan.useDelimiter("#"); while(scan.hasNext()){ String[] list = scan.next().split("/"); System.out.println("name = "+list[0]); System.out.println("surname = "+list[1]); }
a delimiter can be any regular expression
hope it helped
- 02-12-2009, 05:18 PM #3
Member
- Join Date
- Feb 2009
- Posts
- 7
- Rep Power
- 0
Sorry i did not make it very clear. The main method should input one person’s data at a time, assign that person’s names to two String variables called forename and surname, respectively, and then print out forename and surname on a line.
i understand that i need the two variables
String forename;
String surname;
and i have
try
{
filescan = new Scanner(new File("music"));
}
catch(Exception e)
{
System.out.println(e);
}
filescan.useDelimiter("#");
Its the fact of breaking up the string
David/Grey#...etc
and putting it into the two String variables then printing.
- 02-12-2009, 05:26 PM #4
Member
- Join Date
- Feb 2009
- Location
- Italy
- Posts
- 51
- Rep Power
- 0
sorry sorry.....
or i don't understand what you want to do or you don't understand the code i wrote.....
i splitted all your text file....
the scanner gets me strings like "name/surename"
and then the split gets me an array containing ["name","surename"]
so....
Java Code:String name = list[0]; String surname = list[1]; // and we write it to the same line System.out.println(name+" "+surename);
Similar Threads
-
Using Scanner class to read int value
By Java Tip in forum Java TipReplies: 1Last Post: 02-07-2009, 02:47 AM -
Scanner Class...
By TheRocket in forum New To JavaReplies: 5Last Post: 12-05-2008, 09:48 AM -
Scanner class problems
By sypherz in forum New To JavaReplies: 6Last Post: 06-09-2008, 09:46 AM -
Scanner class
By ajaymenon.k in forum Advanced JavaReplies: 1Last Post: 11-26-2007, 07:01 AM -
JDK 5.0 Scanner Class
By Sircedric88 in forum New To JavaReplies: 3Last Post: 07-27-2007, 06:55 PM


1Likes
LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks