[英]Simple Encrypt Decrypt String with array in Android
我的問題似乎很簡單,我正在嘗試在android中加密字符串。
該程序的目的是在textbox1中放入一個單詞或一個字母,單擊“加密”按鈕,textbox2應該在所輸入字母的第二個數組中的同一位置顯示該符號。
例如,如果單擊ENCRYPT
按鈕,則我寫letter A (array 1 [0])
必須顯示symbol $ (array 2 [0])
,如果我放置符號並單擊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);
}
}
}
}
}
使用兩種不同的方法可以為您的問題提供兩種解決方案:
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);
第二種實現效率更高
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.