Created
September 10, 2012 12:47
-
-
Save rokon12/3690719 to your computer and use it in GitHub Desktop.
Problems # 1: Suppose you have a plain text file. Write a simple java program to find out the first non-repeated word in the file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.therapjavafest.puzzle; | |
import java.io.BufferedReader; | |
import java.io.File; | |
import java.io.FileNotFoundException; | |
import java.io.FileReader; | |
import java.io.IOException; | |
import java.util.Hashtable; | |
import java.util.Map; | |
public class FirstNonRepeatedWordFinder { | |
@SuppressWarnings("resource") | |
public static String readTextFromFile(String fileName) | |
throws FileNotFoundException { | |
StringBuilder builder = new StringBuilder(); | |
File file = new File(fileName); | |
// check if file is exist or not, if not exist throw a Exceptions | |
if (!file.exists()) { | |
throw new FileNotFoundException(); | |
} | |
BufferedReader reader; | |
try { | |
reader = new BufferedReader(new FileReader(file)); | |
String line = ""; | |
while ((line = reader.readLine()) != null) { | |
builder.append(line); | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
return builder.toString(); | |
} | |
public static String findNonRepeatedWords(String text) { | |
Map<String, Integer> map = new Hashtable<>(); | |
Integer intgr = null; | |
final String[] words = text | |
.split("[ \"!#$%&'()*+,-.//:;<=>?@^_`{|}~]"); // split this text using delimiters | |
for (String str : words) { | |
intgr = map.get(str); | |
// If there is no value for that word in the | |
// map then insert a '1' | |
if (intgr == null) { | |
map.put(str, new Integer(1)); | |
} else { | |
// else if there is already a value for that word, increment the | |
// value by 1 | |
map.put(str, new Integer(intgr.intValue() + 1)); | |
} | |
} | |
System.out.println(map); | |
for (String str : words) { | |
if (map.get(str).intValue() == 1) { | |
return str; | |
} | |
} | |
return null; | |
} | |
public static void main(String[] args) { | |
try { | |
System.out.println("First Non Repeated Word is: " | |
+ findNonRepeatedWords(readTextFromFile("textfile.txt"))); | |
} catch (FileNotFoundException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment