我是java的新手,我正在努力奋斗!我已经编写了以下代码但仍然遇到错误。我现在要做的就是用字母A填充一个5x5矩阵。这是我到目前为止所做的,我不确定是否还需要发布错误?任何帮助将非常感激。
public class Encryption {
private String Unencoded, FiveLetterKeyword, EncryptedMessage;
//constructor method
public Encryption(String U, String F, String E)
{
Unencoded = U;
FiveLetterKeyword = F;
EncryptedMessage = E;
}
//create 2D string array 5 by 5
String Encrypt [][] = new String[5][5];
//create string filled with all letters of the alphabet
String String = new String
("A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z");
//method for loop to print out the matrix
public static void matrix()
//for loop to create matrix rows and columns
{
for (int row = 1; row < Encrypt.length; row++)
{
for (int column = 1; column < Encrypt[row].length; column++)
System.out.print(Encrypt[row][column] + " ");
}
}
//filling the array with the letter A
public char Encrypt(char Encrypt[][])
{
//char[] alpha = alphabets.toCharArray;
//declaring variable to fill array with A
char aChar = "A";
for (int row = 1; row < Encrypt.length; row++)
{
for (int column = 1; column < Encrypt.length; column++)
return Encrypt;
}
}
}
答案 0 :(得分:4)
Java中的数组从零开始,这意味着它们从索引0开始,并且范围直到索引array.length-1
。
您的代码在row
处启动column
和1
- 这意味着您正在跳过行/列0的初始化。这可能至少在哪里一些问题来自于,因为您使用5x5阵列(行/列0,1,2,3,4)作为4x4阵列(行/列1,2,3,4)。 / p>
还有一个事实是你的Encrypt
方法实际上没有对数组进行任何赋值。你可能想要像这样初始化它:
// NOTE: changed return type to void -- this is a side-effect-only method!
public void Encrypt(char Encrypt[][])
{
// NOTE: use single-quotes for chars. double-quotes are for strings.
char aChar = 'A';
// NOTE: changed the starting loop values from `1` to `0`
for (int row = 0; row < Encrypt.length; row++)
{
// NOTE: technically Encrypt.length works here since it's a square
// 2D array, but you should really loop until Encrypt[row].length
for (int column = 0; column < Encrypt[row].length; column++)
{
// NOTE: set each entry to the desired char value
Encrypt[row][column] = aChar;
}
}
}
您的原始代码存在多个问题。查看注释中的NOTE
条目,了解各个解释。
答案 1 :(得分:2)
你错过了你想要完成的最重要的部分。
您在哪里将矩阵设置为字母A?
将您的加密功能更改为以下内容:
//filling the array with the letter A
public void Encrypt(char arr[][])
{
//char[] alpha = alphabets.toCharArray;
//declaring variable to fill array with A
char aChar = 'A';
for (int row = 0; row < arr.length; row++)
{
for (int column = 0; column < arr[row].length; column++)
{
arr[row][column] = aChar;
}
}
}