Я новенькая Java и получил проект кодирования от моего инструктора. Я создаю Java-программу, которая поможет кому-то, если он путешествует в другую страну. Прямо сейчас я пытаюсь найти лучший способ перевести фразу с английского на один из языков, перечисленных в многомерном массиве, который я создал. Извините, что этот пост длинный. Это мой второй опыт использования переполнения стека за месяцы.
String[][] Phrases =
{{"Hola", "Adios", "Gracias", "Si", "No", "Lo siento or perdón"},//Spanish
{"Bonjour", "Goodbye", "Au revoir", "Oui", "Non", "Je suis désolé"},//French
{"Merhaba", "Güle güle", "teşekkür ederim", "Evet", "yok hayır", "üzgünüm"},//Turkish
{"Здравствуйте (Zdravstvuyte)", "Прощай (Proshchay)", "Спасибо (Spasibo)", "да (da)", "нет (net)", "прости (prosti)"}};//Russian
У меня есть оператор switch, а в случае 4 я собирался сделать операторы if для вызова массива для перевода фраз английского языка на основе ввода пользователя. Он отлично работает для перевода на испанский язык, но это много, если я должен сделать это для других трех языков.
switch (option){
case 4: System.out.println("Select which phrase 1 through 6 you would like to translate to.");
System.out.println("1 - Hello, \n2 - Goodbye, \n3 - Thank you, \n4 - Yes, \n5 - No, \n6 - I'm Sorry");
int speak = 0;
speak = info.nextInt();
if (speak ==1){
System.out.println("Option " + speak + " translates to " + Phrases[0][0]);
} else if (speak == 2){
System.out.println("Option " + speak + " translates to " + Phrases[0][1]);
}else if (speak == 3){
System.out.println("Option " + speak + " translates to " + Phrases[0][2]);
}else if (speak == 4){
System.out.println("Option " + speak + " translates to " + Phrases[0][3]);
}else if (speak == 5){
System.out.println("Option " + speak + " translates to " + Phrases[0][4]);
}
break;
//Give user menu of phrases, store phrase input, call array for phrase,
}
Определенно, есть лучший способ сделать это, чем написать кучу операторов if. Какой лучший способ вызова массива для перевода фразы, которую пользователь хочет перевести? Я прошу прощения, если это не имеет никакого смысла, но на данный момент я полностью потерян. Ниже все, что я получил до сих пор. Я использую Blue J, и у меня есть два класса. Все, что я хочу сделать, - это найти более простой способ перевода английских фраз на один из четырех языков, предоставляемых, когда пользователь выбирает, какую фразу переводить.
Класс Travle
import java.util.Scanner;
public class Travel
{
public static void main (String args[]) {
System.out.println("Welcome to One Culture! Before selecting a vacation spot, we'll need to ask a few things.");
//User input
System.out.println("What's your full name?");
Scanner info = new Scanner(System.in);
String name = info.nextLine();
System.out.println("What's your nationality?");
String origin = info.nextLine();
System.out.println("Are you looking for a place where the weather is hot or cold?");
String temp = info.nextLine();
System.out.println("How much money do you plan on traveling with? What's your budget?");
int money = info.nextInt();
System.out.println("Traveler's Information: \n" + "Name: " + name + "\nOrigin: " + origin +
"\nBudget: " + money +" USD" + "\nPreferred Weather: " + temp + "\n");
System.out.println("Based on traveler's information, here are locations of interest: \n");
Assistant.vacationSpot();
int spot = 0;
if (temp.equals ("hot")){
System.out.println("\nBased on weather choice, here are recommended locations for hot: ");
Assistant.warm();
System.out.println("\nUse the following codes to input your currency choices for your destination: \n 1 - Mexican peso \n 2 - Senegal West African CFA franc");
spot = info.nextInt();
}
else if(temp.equals ("cold")){
System.out.println("\nBased on weather choice, here are recommended locations for cold: ");
Assistant.cold();
System.out.println("\nUse the following codes to input your currency choices for your destination: \n 3 - Turkish Lira \n 4 - Russian ruble");
spot = info.nextInt();
}
int option = 0;
//Greeting user
String greet = "";
if (spot == 1) {
greet = "Mexico";
}
else if (spot == 2){
greet = "Senegal";
}
else if (spot == 3){
greet = "Turkey";
}
else if (spot == 4){
greet = "Russia";
}
String[] moneySwap = {"peso", "CFA franc", "Lira", "ruble"};
/*String[] spanishPhrases = {"Hola", "Adios", "Gracias", "Si", "No", "Lo siento or perdón"};
String[] frenchPhrases = {"Bonjour", "Goodbye", "Au revoir", "Oui", "Non", "Je suis désolé"};
String[] turkishPhrases = {"Merhaba", "Güle güle", "teşekkür ederim", "Evet", "yok hayır", "üzgünüm"};
String[] russianPhrases = {"Здравствуйте (Zdravstvuyte)", "Прощай (Proshchay)", "Спасибо (Spasibo)", "да (da)", "нет (net)", "прости (prosti)"};
*/
String[][] Phrases =
{{"Hola", "Adios", "Gracias", "Si", "No", "Lo siento or perdón"},//Spanish
{"Bonjour", "Goodbye", "Au revoir", "Oui", "Non", "Je suis désolé"},//French
{"Merhaba", "Güle güle", "teşekkür ederim", "Evet", "yok hayır", "üzgünüm"},//Turkish
{"Здравствуйте (Zdravstvuyte)", "Прощай (Proshchay)", "Спасибо (Spasibo)", "да (da)", "нет (net)", "прости (prosti)"}};//Russian
System.out.println("Welcome to " + greet + " What would you like to do now?");
//Menu of task to perform
System.out.println("1 - convert currency \n 2 - Haggle prices \n 3 - Make a purchase \n 4 - Translate a phrase.");
option = info.nextInt();
switch (option){
case 1: System.out.println("Your budget from USD to " + moneySwap[spot - 1] + " is " + Assistant.currency(money, spot));
break;
case 2:
break;
case 3: //ask user for purchase cost, store number, subtract from total budget, check if budget is less than 0
break;
case 4: System.out.println("Select which phrase 1 through 6 you would like to translate to.");
System.out.println("1 - Hello, \n2 - Goodbye, \n3 - Thank you, \n4 - Yes, \n5 - No, \n6 - I'm Sorry");
int speak = 0;
speak = info.nextInt();
if (speak ==1){
System.out.println("Option " + speak + " translates to " + Phrases[0][0]);
} else if (speak == 2){
System.out.println("Option " + speak + " translates to " + Phrases[0][1]);
}else if (speak == 3){
System.out.println("Option " + speak + " translates to " + Phrases[0][2]);
}else if (speak == 4){
System.out.println("Option " + speak + " translates to " + Phrases[0][3]);
}else if (speak == 5){
System.out.println("Option " + speak + " translates to " + Phrases[0][4]);
}
break;
//Give user menu of phrases, store phrase input, call array for phrase,
}
}
}
Ниже это помощник
public class Assistant
{
//Displaying warm locations
public static void warm() {
String[][] warm = {{"Mexico","Senegal"},
{"Spanish", "French"}};
hot(warm);
}
public static void hot(String x[][]){
for(int row = 0; row < x.length; row++){
for (int col = 0; col < x[row].length;col++){
System.out.print(x[row][col]+ "\t");
}
System.out.println();
}
}
//Displaying colder locations
public static void cold() {
String[][] freeze = {{"Turkey ","Russia"},
{"Turkish","Russian",}};
display(freeze);
}
public static void freeze(String x[][]){
for(int row = 0; row < x.length; row++){
for (int col = 0; col < x[row].length;col++){
System.out.print(x[row][col]+ "\t");
}
System.out.println();
}
}
//money conversion
public static double currency(int budget, int dest) {
double temp = budget;
if (dest == 1) {
temp = budget * 18.84;
}
else if (dest == 2){
temp = budget * 543.75;
}
else if (dest == 3){
temp = budget * 4.10;
}
else if (dest == 4){
temp = budget * 63.42;
}
return temp;
}
}