Results 1 to 2 of 2
Thread: Scanner help
- 04-15-2012, 01:44 PM #1
Member
- Join Date
- Apr 2012
- Posts
- 9
- Rep Power
- 0
Scanner help
Hi, I’m trying to find capitalized names in a sentence. For example: “His name is Bugs Bunny and he loves carrots. “ The code below will get Bugs Bunny but then it skips “and” because of the scan.next(); Is there any way to NOT skip the “and”? I want the scanner to continue scanning the same sentence in case of another name and I don’t want to miss any of the tokens.
*EDIT* I really apologize, I didn't realize i didn't post enough of the code to show the problem. The scanner goes through the sentence with a while loop, however when it finds a keyword (after the keyword might be a name) from the database in the sentence. It will check if the following word is capitalized and scans until it doesnt find a capitalized word anymore.
Java Code:ArrayList<String> Persons=new ArrayList<String>(); int i; Scanner scan=new Scanner("His name is Bugs Bunny and he loves carrots."); String word,nextWord,name=" "; while (scan.hasNext()) { word=scan.next(); db.pst = (com.mysql.jdbc.PreparedStatement) db.con.prepareStatement("SELECT * FROM articletable"); db.rs = db.pst.executeQuery(); while (db.rs.next()) { kword=db.rs.getString(2); if(word.equalsIgnoreCase(kword)) { isKword=true; } } if(isKword){ //if a keyword was found, check if the following words are capitalized and add to arrayList if(scan.hasNext()) { nextWord=scan.next(); if(Character.isUpperCase(nextWord.charAt(0))) { name+=" "+nextWord; if(scan.hasNext()) { nextWord=scan.next(); while(Character.isUpperCase(nextWord.charAt(0)) && scan.hasNext()) { name+=" " +nextWord; nextWord=scan.next(); } } if((name.trim().length() > 0)){ Persons.add(name); name=" "; } } } isKword=false; } }Last edited by onions; 04-15-2012 at 03:02 PM.
-
Re: Scanner help
Use a while loop to go through the String checking while (scan.hasNext()), and inside of this loop, call scan.next() only once. In other words each call to scan.hasNextXXX() should be matched by a single call to scan.nextXXX().
Similar Threads
-
How to use Scanner ?
By sandeep43 in forum New To JavaReplies: 7Last Post: 08-10-2011, 01:29 PM -
Using scanner for CSV
By getName() in forum Advanced JavaReplies: 7Last Post: 06-20-2010, 04:33 PM -
Help With Scanner
By jtmoney0511 in forum New To JavaReplies: 10Last Post: 10-12-2009, 11:24 PM -
Scanner
By choko in forum New To JavaReplies: 10Last Post: 01-24-2009, 03:37 PM -
need help with scanner
By whiterex in forum New To JavaReplies: 1Last Post: 04-22-2008, 01:41 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks