Skip to content

Commit

Permalink
Done A3
Browse files Browse the repository at this point in the history
  • Loading branch information
cbolinius committed Sep 26, 2024
1 parent 71cad00 commit d40167a
Show file tree
Hide file tree
Showing 7 changed files with 182 additions and 59 deletions.
10 changes: 7 additions & 3 deletions src/main/java/org/translation/CountryCodeConverter.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* This class provides the service of converting country codes to their names.
Expand Down Expand Up @@ -71,8 +75,8 @@ public String fromCountryCode(String code) {
*/
public String fromCountry(String country) {
for (Map.Entry<String, List<String>> entry : countryDictionary.entrySet()) {
if (entry.getKey().equals(country)) {
return entry.getValue().get(COUNTRY_CODE_INDEX);
if (entry.getKey().equalsIgnoreCase(country)) {
return entry.getValue().get(COUNTRY_CODE_INDEX).toLowerCase();
}
}
return "Country Not Found";
Expand Down
14 changes: 7 additions & 7 deletions src/main/java/org/translation/InLabByHandTranslator.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,6 @@
import java.util.ArrayList;
import java.util.List;

// TODO Task: modify this class so that it also supports the Spanish language code "es" and
// one more language code of your choice. Each member of your group should add
// support for one additional langauge code on a branch; then push and create a pull request on GitHub.

// Extra Task: if your group has extra time, you can add support for another country code in this class.

/**
* An implementation of the Translator interface which translates
* the country code "can" to several languages.
Expand All @@ -27,7 +21,7 @@ public class InLabByHandTranslator implements Translator {
@Override
public List<String> getCountryLanguages(String country) {
if (CANADA.equals(country)) {
return new ArrayList<>(List.of("de", "en", "zh"));
return new ArrayList<>(List.of("de", "en", "zh", "es", "fr"));
}
return new ArrayList<>();
}
Expand Down Expand Up @@ -65,6 +59,12 @@ else if ("en".equals(language)) {
else if ("zh".equals(language)) {
toReturn = "加拿大";
}
else if ("es".equals(language)) {
toReturn = "Canadá";
}
else if ("fr".equals(language)) {
toReturn = "Canada";
}

return toReturn;
}
Expand Down
88 changes: 78 additions & 10 deletions src/main/java/org/translation/JSONTranslator.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,25 @@
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

/**
* An implementation of the Translator interface which reads in the translation
* data from a JSON file. The data is read in once each time an instance of this class is constructed.
*/
public class JSONTranslator implements Translator {

// TODO Task: pick appropriate instance variables for this class
// Index where alpha3 code is stored
private static final int ALPHA3_INDEX = 2;

// HashMap storing all country info in the converter
private Map<String, List<Map>> translator = new HashMap<>();

/**
* Constructs a JSONTranslator using data from the sample.json resources file.
Expand All @@ -38,32 +45,93 @@ public JSONTranslator(String filename) {

JSONArray jsonArray = new JSONArray(jsonString);

// TODO Task: use the data in the jsonArray to populate your instance variables
// Note: this will likely be one of the most substantial pieces of code you write in this lab.
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
List<Map> tempList = new ArrayList<>();
String[] keys = JSONObject.getNames(jsonObject);
JSONArray values = getValues(jsonObject);
String alpha3Code = new String();

// int j = ALPHA3_INDEX + 1
for (int j = 0; j < jsonObject.length(); j++) {
if ("id".equals(keys[j]) || "alpha2".equals(keys[j]) || "alpha3".equals(keys[j])) {
if ("alpha3".equals(keys[j])) {
alpha3Code = values.getString(j);
}
continue;
}
Map<String, String> tempMap = new HashMap<>();
Object value = values.get(j);
if (value instanceof String) {
tempMap.put(keys[j], (String) value);
}
else {
tempMap.put(keys[j], value.toString());
}
// tempMap.put(keys[j], values.getString(j));
tempList.add(tempMap);
}
this.translator.put(alpha3Code, tempList);
}
}
catch (IOException | URISyntaxException ex) {
throw new RuntimeException(ex);
}
}

private static JSONArray getValues(JSONObject jsonObject) {
JSONArray values = new JSONArray();
Iterator<String> keys = jsonObject.keys();

while (keys.hasNext()) {
String key = keys.next();
values.put(jsonObject.get(key));
}
return values;
}

/**
* Returns the language codes for all languages whose translations are
* available for the given country.
* @param country the alpha3 code of the country
* @return list of language codes which are available for this country
*/
@Override
public List<String> getCountryLanguages(String country) {
// TODO Task: return an appropriate list of language codes,
// but make sure there is no aliasing to a mutable object
return new ArrayList<>();
List<Map> translations = translator.get(country);
List<String> languages = new ArrayList<>();
for (Map map : translations) {
languages.add(map.keySet().iterator().next().toString());
}
return languages;
}

/**
* Returns the country codes for all countries whose translations are
* available from this Translator.
* @return list of country codes for which we have translations available
*/
@Override
public List<String> getCountries() {
// TODO Task: return an appropriate list of country codes,
// but make sure there is no aliasing to a mutable object
return new ArrayList<>();
List<String> countries = new ArrayList<>();
translator.keySet().forEach(key -> countries.add(key));
return countries;
}

/**
* Returns the name of the country based on the specified country abbreviation and language abbreviation.
* @param country the country code
* @param language the language code
* @return the name of the country in the given language or null if no translation is available
*/
@Override
public String translate(String country, String language) {
// TODO Task: complete this method using your instance variables as needed
List<Map> translations = translator.get(country);
for (Map map : translations) {
if (map.containsKey(language)) {
return map.get(language).toString();
}
}
return null;
}
}
38 changes: 25 additions & 13 deletions src/main/java/org/translation/LanguageCodeConverter.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,19 @@
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;

/**
* This class provides the service of converting language codes to their names.
*/
public class LanguageCodeConverter {

// TODO Task: pick appropriate instance variables to store the data necessary for this class
// Indexes where country name and language are stored on each line
private static final int COUNTRY_NAME_INDEX = 0;
private static final int LANGUAGE_CODE_INDEX = 1;

// HashMap storing all country-code key-value pairs in the converter
private Map<String, String> codeMap = new HashMap<>();

/**
* Default constructor which will load the language codes from "language-codes.txt"
Expand All @@ -33,9 +36,11 @@ public LanguageCodeConverter(String filename) {
try {
List<String> lines = Files.readAllLines(Paths.get(getClass()
.getClassLoader().getResource(filename).toURI()));

// TODO Task: use lines to populate the instance variable
// tip: you might find it convenient to create an iterator using lines.iterator()
// Start at index 1 to skip the header
for (String line : lines.subList(1, lines.size())) {
String[] values = line.split("\t");
this.codeMap.put(values[COUNTRY_NAME_INDEX], values[LANGUAGE_CODE_INDEX]);
}
}
catch (IOException | URISyntaxException ex) {
throw new RuntimeException(ex);
Expand All @@ -49,8 +54,12 @@ public LanguageCodeConverter(String filename) {
* @return the name of the language corresponding to the code
*/
public String fromLanguageCode(String code) {
// TODO Task: update this code to use your instance variable to return the correct value
return code;
for (Map.Entry<String, String> entry : codeMap.entrySet()) {
if (entry.getValue().equalsIgnoreCase(code)) {
return entry.getKey();
}
}
return "Language Code Not Found";
}

/**
Expand All @@ -59,16 +68,19 @@ public String fromLanguageCode(String code) {
* @return the 2-letter code of the language
*/
public String fromLanguage(String language) {
// TODO Task: update this code to use your instance variable to return the correct value
return language;
for (Map.Entry<String, String> entry : codeMap.entrySet()) {
if (entry.getKey().equalsIgnoreCase(language)) {
return entry.getValue();
}
}
return "Language Not Found";
}

/**
* Returns how many languages are included in this code converter.
* @return how many languages are included in this code converter.
*/
public int getNumLanguages() {
// TODO Task: update this code to use your instance variable to return the correct value
return 0;
return codeMap.size();
}
}
53 changes: 29 additions & 24 deletions src/main/java/org/translation/Main.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.translation;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

Expand All @@ -21,11 +22,7 @@ public class Main {
*/
public static void main(String[] args) {

// TODO Task: once you finish the JSONTranslator,
// you can use it here instead of the InLabByHandTranslator
// to try out the whole program!
// Translator translator = new JSONTranslator(null);
Translator translator = new InLabByHandTranslator();
Translator translator = new JSONTranslator();

runProgram(translator);
}
Expand All @@ -43,19 +40,16 @@ public static void runProgram(Translator translator) {
if (quit.equals(country)) {
break;
}
// TODO Task: Once you switch promptForCountry so that it returns the country
// name rather than the 3-letter country code, you will need to
// convert it back to its 3-letter country code when calling promptForLanguage
String language = promptForLanguage(translator, country);

CountryCodeConverter countryConverter = new CountryCodeConverter();
String language = promptForLanguage(translator, countryConverter.fromCountry(country));
if (language.equals(quit)) {
break;
}
// TODO Task: Once you switch promptForLanguage so that it returns the language
// name rather than the 2-letter language code, you will need to
// convert it back to its 2-letter language code when calling translate.
// Note: you should use the actual names in the message printed below though,
// since the user will see the displayed message.
System.out.println(country + " in " + language + " is " + translator.translate(country, language));

LanguageCodeConverter languageConverter = new LanguageCodeConverter();
System.out.println(country + " in " + language + " is " + translator
.translate(countryConverter.fromCountry(country), languageConverter.fromLanguage(language)));
System.out.println("Press enter to continue or quit to exit.");
Scanner s = new Scanner(System.in);
String textTyped = s.nextLine();
Expand All @@ -69,11 +63,15 @@ public static void runProgram(Translator translator) {
// Note: CheckStyle is configured so that we don't need javadoc for private methods
private static String promptForCountry(Translator translator) {
List<String> countries = translator.getCountries();
// TODO Task: replace the following println call, sort the countries alphabetically,
// and print them out; one per line
// hint: class Collections provides a static sort method
// TODO Task: convert the country codes to the actual country names before sorting
System.out.println(countries);
List<String> countryNames = new ArrayList<>();

for (String country : countries) {
countryNames.add(translator.translate(country, "en"));
}
countryNames.sort(String::compareToIgnoreCase);
for (String countryName : countryNames) {
System.out.println(countryName);
}

System.out.println("select a country from above:");

Expand All @@ -84,11 +82,18 @@ private static String promptForCountry(Translator translator) {

// Note: CheckStyle is configured so that we don't need javadoc for private methods
private static String promptForLanguage(Translator translator, String country) {
List<String> languages = translator.getCountryLanguages(country);
List<String> languageNames = new ArrayList<>();

LanguageCodeConverter converter = new LanguageCodeConverter();

// TODO Task: replace the line below so that we sort the languages alphabetically and print them out;
// one per line
// TODO Task: convert the language codes to the actual language names before sorting
System.out.println(translator.getCountryLanguages(country));
for (String language : languages) {
languageNames.add(converter.fromLanguageCode(language));
}
languageNames.sort(String::compareToIgnoreCase);
for (String languageName : languageNames) {
System.out.println(languageName);
}

System.out.println("select a language from above:");

Expand Down
20 changes: 18 additions & 2 deletions src/test/java/org/translation/JSONTranslatorTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,17 @@ public class JSONTranslatorTest {
JSONTranslator jsonTranslator = new JSONTranslator();

@Test
public void getCountryLanguages() {
public void getCountryLanguagesCAN() {
List<String> countryLanguages = jsonTranslator.getCountryLanguages("can");
assertEquals("There should be 35 languages but got " + countryLanguages.size(), 35, countryLanguages.size());
}

@Test
public void getCountryLanguagesAFG() {
List<String> countryLanguages = jsonTranslator.getCountryLanguages("afg");
assertEquals("There should be 35 languages but got " + countryLanguages.size(), 35, countryLanguages.size());
}

@Test
public void getCountries() {
List<String> languages = jsonTranslator.getCountries();
Expand All @@ -24,7 +30,17 @@ public void getCountries() {
}

@Test
public void translate() {
public void translateCAN_EN() {
assertEquals("Canada", jsonTranslator.translate("can", "en"));
}

@Test
public void translateAFG_PT() {
assertEquals("Afeganistão", jsonTranslator.translate("afg", "pt"));
}

@Test
public void translateZWE_AR() {
assertEquals("زيمبابوي", jsonTranslator.translate("zwe", "ar"));
}
}
Loading

0 comments on commit d40167a

Please sign in to comment.