-
Help with Scanner Class
I need to find a way to take in either a char or a string using scanner class.
Could someone help me with how to do it
-
The "tokenized" object(s) in a scanner are strings. You take in the next token by using next() ... If you want to use the string a char at a time, use the string methods to accomplish this.
-
Scanner reader = new Scanner(new File("filename.txt"));
StringTokenizer wordsInLine=new StringTokenizer(reader.nextLine()); //this returns a line
String word=wordsInLine.nextToken(); //this returns a word in the line
-
Why would you use a StringTokenizer in this? Just use something like this (using as an example, a prior question in another thread):
Code:
Scanner reader = new Scanner(new File( "filename.txt" )).useDelimiter( "\n");
Scanner currentLine;
while (reader.hasNext())
{
currentLine = new Scanner(reader.next());
price = currentLine.nextFloat();
StringBuilder sb = new StringBuilder();
while (currentLine.hasNext())
{
sb.add(currentLine.next() );
}
item = sb.toString();
}
This will break the file into line sized tokens, first. Then you take each line, create a scanner object now using whitespace (the default delimiter for Scanner objects) to tokenize the line. Assign the first token to the float price, then read the remaining tokens into a StringBuilder object, assign it to the string item by then doing a toString() of the stringbuilder object.
If you want to read a char, you need to do
Code:
char c = '';
for( int i = 0; i < item.length(); ++i )
{
c = item.charAt(i);
.....
do what you're going to do with the char;
.....
}
Last edited by nspils; 09-23-2006 at 06:46 PM.
Similar Threads
-
By Osiris43 in forum .NET
Replies: 1
Last Post: 08-04-2006, 12:15 PM
-
Replies: 5
Last Post: 01-15-2006, 07:10 PM
-
By xdanielx in forum Java
Replies: 5
Last Post: 10-31-2005, 01:50 AM
-
By none_none in forum Java
Replies: 17
Last Post: 04-28-2005, 03:00 PM
-
Replies: 5
Last Post: 10-17-2002, 01:58 PM
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Development Centers
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center
|