【问题标题】:Creating "Password detector" for EditText in android project在 android 项目中为 EditText 创建“密码检测器”
【发布时间】:2016-04-10 11:33:28
【问题描述】:

我正在尝试使用字符串密码创建一个应用程序,它所做的就是遍历字符和数字的所有可能组合,直到找到正确的组合,类似这样:

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class PasswordDetector extends AppCompatActivity {
private static final String PASSWORD = "abc123";
private Button search;
private EditText combination;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    search.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //here I want the loop to run, untill it hits the PASSWORD
            combination.setText("combinations");
            if (combination.getText().toString().equals(PASSWORD)) {
                Toast.makeText(PasswordDetector.this, "Success", Toast.LENGTH_SHORT).show();
            }
        }
    });


}
}

我应该如何处理它?

【问题讨论】:

    标签: java android


    【解决方案1】:

    这类问题最常见的方法是重复排列。

    public static String[] getAllLists(String[] elements, int lengthOfList)
    {
        //initialize our returned list with the number of elements calculated above
        String[] allLists = new String[(int)Math.pow(elements.length, lengthOfList)];
    
        //lists of length 1 are just the original elements
        if(lengthOfList == 1) return elements; 
        else {
            //the recursion--get all lists of length 3, length 2, all the way up to 1
            String[] allSublists = getAllLists(elements, lengthOfList - 1);
    
            //append the sublists to each element
            int arrayIndex = 0;
    
            for(int i = 0; i < elements.length; i++){
                for(int j = 0; j < allSublists.length; j++){
                    //add the newly appended combination to the list
                    allLists[arrayIndex] = elements[i] + allSublists[j];
                    arrayIndex++;
                }
            }
            return allLists;
        }
    }
    
    public static void main(String[] args){
        String[] database = {"a","b","c"};
        for(int i=1; i<=database.length; i++){
            String[] result = getAllLists(database, i);
            for(int j=0; j<result.length; j++){
                System.out.println(result[j]);
            }
        }
    }
    
    1. String[] elements 是密码中使用的字符数组。
    2. int lenghtOflist 是密码长度。

    Check this answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-01
      • 2021-06-17
      • 1970-01-01
      • 2011-07-20
      • 1970-01-01
      • 2012-07-02
      相关资源
      最近更新 更多