【问题标题】:Searching for chars from a String in a 2d char array?从二维字符数组中的字符串中搜索字符?
【发布时间】:2015-03-31 20:35:44
【问题描述】:

我希望能够搜索我的数组并找到用户输入的字符串中的字符?因此,如果用户键入“消息”,我希望它返回 'm' 'e' 's' 的索引,依此类推。我该怎么做?到目前为止,这是我的代码:

import java.util.ArrayList;
import java.util.Scanner;

public class Matrix {
private char[][] matrix = new char[6][6];
private int[] usedNumbers = new int[50];

{for(int x = 0; x < usedNumbers.length; x++) usedNumbers[x] = -1;}

private final char[] CIPHER_KEY = {'A','D','F','G','V','X'};
private final String validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";


public Matrix() {
    int random;
    for(int i = 0; i < CIPHER_KEY.length; i++) {
        for(int j = 0; j < CIPHER_KEY.length; j++) {
            validation: while(true) {
                random = (int)(Math.random()*validChars.length()-1);
                for(int k = 0; k < usedNumbers.length; k++) {
                    if(random == usedNumbers[k]) continue validation;
                    else if(usedNumbers[k]==-1) usedNumbers[k] = random;
                }
                break;
            }
            matrix[i][j] = validChars.split("")[random].charAt(0);  
        }
    }
}

public void searchMatrix(){

    Scanner console = new Scanner (System.in);

    String phrase = "";

    System.out.println("\n Enter the message you would like "
            + "to encrypt with the cipher: \n");
    phrase = console.nextLine();

    char[] phraseSplit = phrase.toCharArray();

    console.close();

}

public String toString() {
    String output = "   A D F G V X\n";
    for(int i = 0; i < CIPHER_KEY.length; i++) {
        output += CIPHER_KEY[i] + "  ";
        for(int j = 0; j < CIPHER_KEY.length; j++) {
            output += matrix[i][j] + " ";
        }
        output += "\n";
    }
    return output;
}// toString end

}

我已经在网上寻找教程,但找不到在这种情况下对我有帮助的教程!帮助?我不知道下一步该做什么。

【问题讨论】:

  • 不需要生成随机数然后检查是否已经使用了数字。只需使用 Collections.shuffle() 打乱您的 char 数组,然后从那里一个接一个地获取字符

标签: java matrix multidimensional-array char


【解决方案1】:

如果我没记错的话,你就快到了。您所要做的就是在获得phraseSplit 之后添加嵌套循环。

for (int k=0; k<phraseSplit.length; k++) {
    for (int i=0; i<matrix.length; i++) {
        for (int j=0; j<matrix[i].length; j++) {
            if (phraseSplit[k] == matrix[i][j]) {
                System.out.printf("%c at %d, %d\n", phraseSplit[k], i, j);
            }//end if
        }//end for j
    }//end for i
}//end for k

可能有更好的方法来做到这一点。另外,Sasha 的shuffle() 是一个非常好的建议。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    • 2016-02-15
    • 1970-01-01
    • 2020-07-27
    相关资源
    最近更新 更多