【发布时间】:2019-06-29 18:13:03
【问题描述】:
我试图构建一个简单的应用程序,它将纯文本和无行作为输入,并使用围栏加密技术将纯文本转换为密文。我没有从用户输入任何行,并通过强制转换将该字符串输入转换为整数。当我这样做时,它显示NumberFormatException。我在 try 块内编写了强制转换行,并且在该变量的范围受到限制之后,我的 encryption() 方法无法访问它。当我的onClick 函数没有生成正确的所需密文时,我该怎么办?
该按钮的行为就像它从未被点击过一样。
我尝试在 try 块之外创建该变量,然后在块内对其进行类型转换,我还创建了 lines 变量 final,因为它是在类中访问的。然后它要求我初始化变量,我也这样做了,但它似乎对我没有帮助。
Button decryptBtn, encryptBtn;
TextView hlWrld, encryptedText;
EditText noOfLines, plainText;
int lines;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
decryptBtn = findViewById(R.id.decryptBtn);
encryptBtn = findViewById(R.id.encrptBtn);
hlWrld = findViewById(R.id.hlwWorld);
encryptedText = findViewById(R.id.encryptedText);
noOfLines = findViewById(R.id.lineNo);
plainText = findViewById(R.id.plntxt);
final String plntxt = plainText.getText().toString();
final String noOflines = noOfLines.getText().toString();
int lines = 0;
try {
lines = Integer.parseInt(noOflines);
} catch (NumberFormatException e) {
}
final int finalLines = lines;
encryptBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
encryption(plntxt, finalLines);
}
});
}
public void encryption(String plntxt, int lines) {
boolean checkdown = false; // check whether it is moving downward or upward
int j = 0;
int row = lines; // no of row is the no of rails entered by user
int col = plntxt.length(); //column length is the size of string
char[][] a = new char[row][col];
// we create a matrix of a of row *col size
for (int i = 0; i < col; i++) { // matrix visiting in rails order and putting the character of plaintext
if (j == 0 || j == row - 1)
checkdown = !checkdown;
a[j][i] = plntxt.charAt(i);
if (checkdown) {
j++;
} else {
j--;
}
}
// visiting the matrix in usual order to get ciphertext
for (int i = 0; i < row; i++) {
for (int k = 0; k < col; k++) {
System.out.print(a[i][k] + " ");
}
System.out.println();
}
String en = "";
System.out.println("----------------------");
for (int i = 0; i < row; i++) {
for (int k = 0; k < col; k++) {
if (a[i][k] != 0)
en = en + a[i][k];
}
}
System.out.println(en); // printing the ciphertext
encryptedText.setText(en);
}
我希望输出是密文,这是我在textView 上应用的setText() 方法的结果。但是,什么都没有发生。
【问题讨论】:
-
您在 onCreate() 方法中获取 plntxt 和 noOfLines 的值,甚至还没有显示组件,因此用户没有机会输入任何内容。这些值可能是空字符串,因此 parseInt() 将失败,因为空字符串不是有效的数字格式。
-
请添加您的日志猫
标签: java android exception encryption casting