【问题标题】:What would I need to return from this 2D String method?我需要从这个 2D String 方法返回什么?
【发布时间】:2020-03-06 17:39:38
【问题描述】:

那么这个方法需要返回什么才能给我想要的结果呢?数组还是二维数组?

我尝试将 String temp 更改为 String[][] 之类的数组,但遇到了更多错误。

// The method 
public static String[][] Shuffle (String[][] states){  
       for ( int i = 0; i < states.length; i++){
            for (int j = 0; j <states[i].length; j++){
               int i1 = (int)(Math.random() * states.length);
               int j1 = (int) (Math.random() * states[i].length);

               String temp = states[i][j];
               states[i][j] = states[i1][j1];
               states[i1][j1] = temp;

               return temp;
          }
       }
    }

我的代码目前可以在不随机化数组中的第一行的情况下工作,但我想随机化状态。新方法将替换这一行 states[index][1]

【问题讨论】:

  • 如果你只是随机选择一个元素,你不需要打乱数组;您可以在随机索引处获取一个元素。
  • @Andreas 但如果我将其设为 void 方法,那么我无法将 .toLowerCase 与它链接

标签: java arrays multidimensional-array methods


【解决方案1】:

我认为你的代码太复杂了,而且你的方法命名不好。

试试这个:

/**
 * @return a random [state, capital]
 */
static String[] getRandomState(String[][] states){  
     return states[(int)(Math.random() * states.length)];
}

还有这个:

String[] state = getRandomState(states);

System.out.println("What is the capital of " + state[0] + "?");

// get user input as user_ans

gamecounter++;
if (user_ans.equalsIgnoreCase(state[1])) {
    System.out.println("Correct!");
    correct_ans++;
} else {
    System.out.println("Incorrect! The correct answer is " + states[1]);
}
System.out.println();

【讨论】:

  • 我认为第一个块需要一些[] 方括号而不是() 括号。
  • Bohemian 我很喜欢这个解释,但我似乎无法编译代码? @Andreas我也不能让它工作......?它说它在状态中找不到符号。
  • @Andreas 哦,是的!谢谢 :)
  • @Joven 我已经纠正了错误(感谢 Andreas)。应该是:return states[(int)(Math.random() * states.length)];(注意方括号)
猜你喜欢
  • 1970-01-01
  • 2013-10-14
  • 2019-06-26
  • 1970-01-01
  • 2013-03-20
  • 1970-01-01
  • 2022-01-17
  • 2012-02-02
  • 2015-08-08
相关资源
最近更新 更多