【发布时间】: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