我的问题看起来很简单,我正在尝试在android中加密一个字符串。
该程序的目标是,在文本框1中放入一个单词或一个字母,单击“加密”按钮,文本框2应该在您输入的字母的第二个数组中的相同位置显示该符号。
例如我写letter A (array 1 [0])
必须显示symbol $ (array 2 [0])
如果点击ENCRYPT
按钮,如果我输入一个符号并单击 DECRYPT
必须显示与数组位置相同的字母
需要帮助。抱歉,语法和编辑问题,第一次,没有英语使用者,我试图让它更简单。
Arreglo
类,仅用于声明2个数组。
package PaqueteArreglo;
public class Arreglo {
public String [] encrypt = new String[3];
public String [] decrypt = new String[3];
}
主要 Activity
package com.example.encrypt;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import PaqueteArreglo.Arreglo;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
//Instance the class with the arrays
PaqueteArreglo.Arreglo ins = new Arreglo();
public Button button1,button2;
public EditText text1, text2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
ins.encrypt[0] = "a";
ins.encrypt[1] = "b";
ins.encrypt[2] = "c";
ins.decrypt[0] = "$";
ins.decrypt[1] = "%";
ins.decrypt[2] = "&";
}
private void initialize(){
text1 = (EditText)findViewById(R.id.txtWord);
text2 = (EditText)findViewById(R.id.txtResult);
button1 = (Button)findViewById(R.id.btnEncrypt);
button1.setOnClickListener(this);
button2 =(Button)findViewById(R.id.btnDecrypt);
button2.setOnClickListener(this);
}
@Override
public void onClick(View view) {
String word = String.valueOf(this.text1.getText());
if (view.getId() == R.id.btnEncrypt)
{
String demo = "";
int lon = 0;
lon = word.length();
for (int i = 0; i < lon; i++ )
{
if (ins.encrypt[i].equalsIgnoreCase(String.valueOf(word.charAt(i))))
{
demo = demo + ins.decrypt[i];
text2.setText(demo);
}
}
}
}
}
最佳答案
使用两种不同的方法可以解决您的问题:
1-使用您定义的结构(顺便说一下,它没有优化),您需要放置两个嵌套循环进行检查:
for (int i = 0; i < lon; i++ )
{
for(int j = 0; j<ins.encrypt.length;j++)
{
if (ins.encrypt[j].equalsIgnoreCase(String.valueOf(word.charAt(i))))
{
demo = demo + ins.decrypt[j];
}
}
}
text2.setText(demo);
2- 使用更好的数据结构,例如 HashMap
:
将 Arreglo 更改为以下内容:
public class Arreglo {
public HashMap<Character, Character> encrypt = new HashMap<>();
public HashMap<Character, Character> decrypt = new HashMap<>();
}
现在更改添加数据的方式,例如:
ins.encrypt.put('a','@');
ins.decrypt.put('@','a');
...
最后进行加密:
for (int i = 0; i < lon; i++ )
{
demo = demo + ins.encrypt.get(word.charAt(i));
}
text2.setText(demo);
第二种实现效率更高
关于java - Android中使用数组简单加密解密字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36561948/