Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lab 3 #115

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open

Lab 3 #115

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 15 additions & 12 deletions src/main/java/org/translation/CountryCodeConverter.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
// TODO CheckStyle: Wrong lexicographical order for 'java.util.HashMap' import (remove this comment once resolved)
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

// TODO Task: pick appropriate instance variable(s) to store the data necessary for this class
private final Map<String, String> countryToCode;
private final Map<String, String> codeToCountry;

/**
* Default constructor which will load the country codes from "country-codes.txt"
Expand All @@ -30,18 +30,24 @@ public CountryCodeConverter() {
* @throws RuntimeException if the resource file can't be loaded properly
*/
public CountryCodeConverter(String filename) {
countryToCode = new HashMap<>();
codeToCountry = new HashMap<>();

try {
List<String> lines = Files.readAllLines(Paths.get(getClass()
.getClassLoader().getResource(filename).toURI()));

// TODO Task: use lines to populate the instance variable(s)

for (int i = 1; i < lines.size(); i++) {
String[] parts = lines.get(i).split("\t");
String country = parts[0];
String code = parts[2];
countryToCode.put(country, code);
codeToCountry.put(code, country);
}
}
catch (IOException | URISyntaxException ex) {
throw new RuntimeException(ex);
}

}

/**
Expand All @@ -50,8 +56,7 @@ public CountryCodeConverter(String filename) {
* @return the name of the country corresponding to the code
*/
public String fromCountryCode(String code) {
// TODO Task: update this code to use an instance variable to return the correct value
return code;
return codeToCountry.get(code.toUpperCase());
}

/**
Expand All @@ -60,16 +65,14 @@ public String fromCountryCode(String code) {
* @return the 3-letter code of the country
*/
public String fromCountry(String country) {
// TODO Task: update this code to use an instance variable to return the correct value
return country;
return countryToCode.get(country);
}

/**
* Returns how many countries are included in this code converter.
* @return how many countries are included in this code converter.
*/
public int getNumCountries() {
// TODO Task: update this code to use an instance variable to return the correct value
return 0;
return countryToCode.size();
}
}
26 changes: 13 additions & 13 deletions src/main/java/org/translation/InLabByHandTranslator.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
* the country code "can" to several languages.
*/
public class InLabByHandTranslator implements Translator {
public static final String CANADA = "can";

/**
* Returns the language abbreviations for all languages whose translations are
* available for the given country.
Expand All @@ -23,16 +25,12 @@ public class InLabByHandTranslator implements Translator {
*/
@Override
public List<String> getCountryLanguages(String country) {
// TODO Checkstyle: The String "can" appears 4 times in the file.
if ("can".equals(country)) {
if (CANADA.equals(country)) {
return new ArrayList<>(List.of("de", "en", "zh"));
}
return new ArrayList<>();
}

// TODO Checkstyle: Static variable definition in wrong order.
public static final String CANADA = "can";

/**
* Returns the country abbreviations for all countries whose translations are
* available from this Translator.
Expand All @@ -41,7 +39,7 @@ public List<String> getCountryLanguages(String country) {
*/
@Override
public List<String> getCountries() {
return new ArrayList<>(List.of("can"));
return new ArrayList<>(List.of(CANADA));
}

/**
Expand All @@ -55,20 +53,22 @@ public List<String> getCountries() {
public String translate(String country, String language) {
// TODO Checkstyle: Return count is 5 (max allowed for non-void methods/ lambdas is 2).
// TODO Checkstyle: String literal expressions should be on the left side of an equals comparison
if (!country.equals("can")) {
if (!country.equals(CANADA)) {
return null;
}
if (language.equals("de")) {
return "Kanada";
String countryTranslated;
if ("de".equals(language)) {
countryTranslated = "Kanada";
}
else if (language.equals("en")) {
return "Canada";
else if ("en".equals(language)) {
countryTranslated = "Canada";
}
else if ("zh".equals(language)) {
return "加拿大";
countryTranslated = "加拿大";
}
else {
return null;
countryTranslated = null;
}
return countryTranslated;
}
}
10 changes: 6 additions & 4 deletions src/main/java/org/translation/JSONDemo.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
public class JSONDemo {
/**
* A first example of working with JSON data.
*
* @param args not used
*/
public static void main(String[] args) {
Expand All @@ -29,12 +30,13 @@ public static void main(String[] args) {
/**
* Returns the value of key "key1" from the second object in the given jsonArray.
* The code may assume that the key exists and that the jsonArray has at least two items in it.
*
* @param jsonArray the jsonArray to get the value from
* @return value of key "key1" from the second object in the given jsonArray
*/
public static String getKeyOneOfSecond(JSONArray jsonArray) {
// TODO: Complete this method.
return "";
}
JSONObject secondObject = jsonArray.getJSONObject(1);

}
return secondObject.getString("key1");
}
}
23 changes: 16 additions & 7 deletions src/main/java/org/translation/JSONTranslationExample.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,8 @@ public JSONTranslationExample() {
try {
// this next line of code reads in a file from the resources folder as a String,
// which we then create a new JSONArray object from.
// TODO CheckStyle: Line is longer than 120 characters
// (note: you can split a line such that the next line starts with a .method()... call
String jsonString = Files.readString(Paths.get(getClass().getClassLoader().getResource("sample.json").toURI()));
String jsonString = Files.readString(Paths.get(getClass().getClassLoader()
.getResource("sample.json").toURI()));
this.jsonArray = new JSONArray(jsonString);
}
catch (IOException | URISyntaxException ex) {
Expand All @@ -38,20 +37,30 @@ public JSONTranslationExample() {
public String getCanadaCountryNameSpanishTranslation() {

// TODO Checkstyle: '30' is a magic number.
JSONObject canada = jsonArray.getJSONObject(30);
JSONObject canada = jsonArray.getJSONObject(CANADA_INDEX);
return canada.getString("es");
}

// TODO Task: Complete the method below to generalize the above to get the country name
// for any country code and language code from sample.json.

/**
* Returns the name of the country based on the provided country and language codes.
* @param countryCode the country, as its three-letter code.
* @param languageCode the language to translate to, as its two-letter code.
* @return the translation of country to the given language or "Country not found" if there is no translation.
*/
public String getCountryNameTranslation(String countryCode, String languageCode) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject countryObject = jsonArray.getJSONObject(i);

if (countryObject.has("alpha2") && countryObject.getString("alpha2")
.equalsIgnoreCase(countryCode) || countryObject.has("alpha3") && countryObject
.getString("alpha3").equalsIgnoreCase(countryCode)) {

if (countryObject.has(languageCode)) {
return countryObject.getString(languageCode);
}
}
}

return "Country not found";
}

Expand Down
33 changes: 21 additions & 12 deletions src/main/java/org/translation/JSONTranslator.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,20 @@
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
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
private final Map<String, Map<String, String>> countries;

/**
* Constructs a JSONTranslator using data from the sample.json resources file.
Expand All @@ -36,10 +39,21 @@ public JSONTranslator(String filename) {
String jsonString = Files.readString(Paths.get(getClass().getClassLoader().getResource(filename).toURI()));

JSONArray jsonArray = new JSONArray(jsonString);
this.countries = new HashMap<>();

// 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 country = jsonArray.getJSONObject(i);
Map<String, String> codeTable = new HashMap<>();
for (Map.Entry<String, Object> entry : country.toMap().entrySet()) {
// Yes this saves "alpha2" and "alpha3" as countries technically
// No I don't care at all
if (entry.getValue() instanceof String && !entry.getKey().equals("alpha2") && !entry.getKey()
.equals("alpha3")) {
codeTable.put(entry.getKey(), (String) entry.getValue());
}
}
this.countries.put(country.getString("alpha3"), codeTable);
}
}
catch (IOException | URISyntaxException ex) {
throw new RuntimeException(ex);
Expand All @@ -48,21 +62,16 @@ public JSONTranslator(String filename) {

@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<>();
return new ArrayList<>(countries.get(country.toLowerCase()).keySet());
}

@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<>();
return new ArrayList<>(countries.keySet());
}

@Override
public String translate(String country, String language) {
// TODO Task: complete this method using your instance variables as needed
return null;
return countries.get(country.toLowerCase()).get(language);
}
}
39 changes: 26 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,15 @@
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
* 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
private final Iterator<String> countries;

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

// TODO Task: use lines to populate the instance variable
// tip: you might find it convenient to create an iterator using lines.iterator()

// TODO Checkstyle: '}' on next line should be alone on a line.
} catch (IOException | URISyntaxException ex) {
this.countries = lines.iterator();
}
catch (IOException | URISyntaxException ex) {
throw new RuntimeException(ex);
}

}

/**
Expand All @@ -50,7 +47,13 @@ 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
while (this.countries.hasNext()) {
String country = this.countries.next();
String[] split = country.split("\t");
if (split[1].equalsIgnoreCase(code)) {
return split[0];
}
}
return code;
}

Expand All @@ -60,7 +63,13 @@ 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
while (this.countries.hasNext()) {
String country = this.countries.next();
String[] split = country.split("\t");
if (split[0].equalsIgnoreCase(language)) {
return split[1];
}
}
return language;
}

Expand All @@ -69,7 +78,11 @@ public String fromLanguage(String language) {
* @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;
int count = 0;
while (this.countries.hasNext()) {
this.countries.next();
count++;
}
return count;
}
}
Loading