为什么我不能从这个数组中选择一个随机元素,它一直告诉我我不能从 String[] 转换为 int

问题描述 投票:0回答:1

这让我有点恼火,因为如果元素不是整数或双精度,我不知道如何从数组中选择随机元素……我需要字符串数组中的随机元素,但 math.random 确实如此不支持这个需求。请帮助我,这个程序将在几个小时后到期。谢谢。

// multidimensional array
public static final String[][] arrCapitals  =
{   
    { "Alabama", "Montgomery" },        { "Alaska", "Juneau" },
    { "Arizona", "Phoenix" },           { "Arkansas", "Little Rock" },
    { "California", "Sacramento" },     { "Colorado", "Denver" },
    { "Connecticut", "Hartford" },      { "Delaware", "Dover" },
    { "Florida", "Tallahassee" },       { "Georgia", "Atlanta" },
    { "Hawaii", "Honolulu" },           { "Idaho", "Boise" },
    { "Illinois", "Springfield" },      { "Indiana", "Indianapolis" },
    { "Iowa", "Des Moines" },           { "Kansas", "Topeka" },
    { "Kentucky", "Frankfort" },        { "Louisiana", "Baton Rouge" },
    { "Maine", "Augusta" },             { "Maryland", "Annapolis" },
    { "Massachusettes", "Boston" },     { "Michigan", "Lansing" },
    { "Minnesota", "Saint Paul" },      { "Mississippi", "Jackson" },
    { "Missouri", "Jefferson City" },   { "Montana", "Helena" },
    { "Nebraska", "Lincoln" },          { "Nevada", "Carson City" },
    { "New Hampshire", "Concord" },     { "New Jersey", "Trenton" },
    { "New York", "Albany" },           { "New Mexico", "Santa Fe" },
    { "North Carolina", "Raleigh" },    { "North Dakota", "Bismarck" },
    { "Ohio", "Columbus" },             { "Oklahoma", "Oklahoma City" },
    { "Oregon", "Salem" },              { "Pennsylvania", "Harrisburg" },
    { "Rhode Island", "Providence" },   { "South Carolina", "Columbia" },
    { "South Dakota", "Pierre" },       { "Tennessee", "Nashville" },
    { "Texas", "Austin" },              { "Utah", "Salt Lake City" },
    { "Vermont", "Montpelier" },        { "Virginia", "Richmond" },
    { "Washington", "Olympia" },        { "West Virginia", "Charleston" },
    { "Wisconsin", "Madison" },         { "Wyoming", "Cheyenne" }
};

public static int chooseState(Random rand, String[][] arrCapitals)
{
    //create variable to hold random state
    String state = ("");
    //for loop
    //for(int i=0; i< arrCapitals.length; i++)
    //{
    int i1 = (int) (Math.random() * arrCapitals.length);
    //}

    return arrCapitals[i1];
    
}
java multidimensional-array
1个回答
0
投票

你的chooseState方法是int,但你试图返回一个String数组,你可以将返回类型更改为String

public static String chooseState(Random rand, String[][] arrCapitals)
{
    //create variable to hold random state
    String state = "";
    //for loop
    //for(int i=0; i< arrCapitals.length; i++)
    //{
    int i1 = rand.nextInt(arrCapitals.length);
    //}

    return arrCapitals[i1][0]; // Return only the state name
}
© www.soinside.com 2019 - 2024. All rights reserved.