【问题标题】:What is a better way of calling a multi dimensional array in Java?在 Java 中调用多维数组的更好方法是什么?
【发布时间】:2018-10-11 23:54:11
【问题描述】:

我是 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,我有两个课程。我要做的就是找到一种更简单的方法,将英语短语翻译成用户选择要翻译成哪个短语时提供的四种语言之一。

旅游类

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












}

【问题讨论】:

  • 地图用于此目的,但是由于您没有学习它们,您的教授可能已经让您这样做了。
  • 我尝试了下面提供给我的两种解决方案并且它们有效,但仅在将短语翻译成西班牙语时才有效。如果用户选择了其他三个国家之一,我如何将其翻译成其他语言?

标签: java arrays bluej


【解决方案1】:

您的 speak 整数表示比该单词的索引多 1,因此使用 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】:

    您已经有了要返回的翻译的索引。你根本不需要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
    }
    

    【讨论】:

      【解决方案3】:

      感谢所有提供帮助并发布解决方案的人。我从发布答案的两个人那里得到了我所看到的,并且解决方案有效,但仅限于翻译成西班牙语时。我需要它能够根据用户所在的四个位置中的哪一个来翻译短语。所以我添加了一些 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]);
              }
      

      我刚刚在 if 语句中添加了spot,这样它就可以知道用户选择了哪个国家并将其翻译成该特定语言。然后我创建了speak &lt; 7,因为它没有翻译短语选项 5 和 6。对此我还是很陌生,但是当我说出当我弄清楚时我有多兴奋时,我非常高兴。

      【讨论】:

        猜你喜欢
        • 2016-10-08
        • 2015-02-26
        • 2016-11-07
        • 1970-01-01
        • 2020-02-21
        • 2019-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多