在Java中调用多维数组的更好方法是什么?

时间:2018-05-01 23:08:32

标签: java arrays bluej

我是全新的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 Class

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;
    }












}

3 个答案:

答案 0 :(得分:2)

您已经拥有要返回的翻译索引。您根本不需要if语句。

替换:

         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]);
}

使用:

if(speak > 0 && speak < 5){
    System.out.println("Option " + speak + " translates to " + Phrases[0][speak-1]);
}else{
    //handle the invalid input however you want
}

答案 1 :(得分:0)

您的发言整数表示该单词的索引的一个以上,因此请使用speak - 1:

访问该单词
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();
        System.out.println("Option " + speak + " translates to " + Phrases[0][speak-1]

如果使用这种方法,那么使用额外的if语句检查speak是否介于1和5之间是明智的。

答案 2 :(得分:0)

感谢所有帮助并发布解决方案的人。我从我发现他们的答案和解决方案的两个人那里看到了我所看到的,但只有在翻译成西班牙语的时候。我需要它能够根据用户所在的四个位置中的哪一个来翻译短语。所以我添加了一些if语句并得到了这个......

 if(spot == 1 && speak > 0 && speak < 7){
      System.out.println("Option " + speak + " translates to " + Phrases[0][speak-1]);
     }else if ((spot == 2 && speak > 0 && speak < 7)) {         
         System.out.println("Option " + speak + " translates to " + Phrases[1][speak-1]);
         //handle the invalid input however you want
      } else if ((spot == 3 && speak > 0 && speak < 7)) {         
         System.out.println("Option " + speak + " translates to " + Phrases[2][speak-1]);

        }else if ((spot == 4 && speak > 0 && speak < 7)) {         
         System.out.println("Option " + speak + " translates to " + Phrases[3][speak-1]);
        }

我刚刚将spot添加到if语句中,以便知道用户选择了哪个国家/地区并将其翻译为该特定语言。然后我做了speak < 7,因为它没有翻译短语选项5和6.这还是新的,但是当我说出来时我很兴奋,我很高兴。