我的问题似乎很简单,我正在尝试加密android中的字符串。
该程序的目标是,在textbox1中放置一个单词或一个字母,单击按钮加密,textbox2应该在您输入的字母的第二个数组中的相同位置显示该符号。
例如,如果点击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];
}
主要活动
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);
}
}
}
}
}
答案 0 :(得分:1)
使用两种不同的方法可以解决您的问题:
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);
第二种实施更有效率