如何在Android中将4位数转换为单个数字

时间:2012-12-28 09:00:36

标签: android

我有一个编辑文本,在我用来输入4位数字的编辑文本中,我已经设置了一些键和值对0-9的数字。

所以我的问题是,当我在edittext中输入一个4位数字(任何数字)时,它应该被转换成一位数字,以便显示keyvalue中的消息。

这是我的代码:

public class MainActivity extends Activity {

     String Sequence;
     Button buttonok;
     String UserEntreredNumber;
     HashMap<String,String> messagesMap = new HashMap<String,String>();
     String magicMessage;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText Sequence = (EditText)this.findViewById(R.id.Sequence);    

        Sequence.setError("Input must be 4 digits");



        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setPositiveButton(" ok ",  new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {

                dialog.cancel();
          }
        });

        //create hash map

       populateList(); 

        //populate hash map with 0 to 9 key and values


        buttonok=(Button)this.findViewById(R.id.buttonok);
        buttonok.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                UserEntreredNumber = Sequence.getText().toString();
                magicMessage = messagesMap.get(UserEntreredNumber);

                builder.setMessage( magicMessage);
                builder.show();         
        }
    });     

}
    private void populateList() { 

       messagesMap.put("0", "Congratulations!!!, you have been selected."); 
       messagesMap.put("1", "Wow! your program just ran without errors!"); 
       messagesMap.put("2", "It's very hot in office"); 
       messagesMap.put("3", "Wow, what a building? It's awesome");
       messagesMap.put("4", "You got a calll");
       messagesMap.put("5", "There were no errors");
       messagesMap.put("6", "U have been shortlisted for the next round");
       messagesMap.put("7", "nice costume");
       messagesMap.put("8", "do u have any idea!");
       messagesMap.put("9", "Today is a bad day");    
    }   
}

2 个答案:

答案 0 :(得分:1)

也许这会对你有所帮助:

Integer digit; 
try{
   digit = Integer.valueOf(Sequence.getText().toString());
} catch (NumberFormatException e){
   digit = null;
}
if (digit != null && digit >= 0 && digit <= 9999 && Pattern.matches("^[0-9]{4,4}$", Sequence.getText().toString());){
     //some logic
} else {
   Sequence.setError("Input must be 4 digits");
}  

答案 1 :(得分:0)

你说:

  

4位数字应转换为单个数字

如果这是您想要的,那么将4位数的除法的余数除以10,即操作的结果:

your 4 digit number % 10

它将返回0到9之间的数字:实际上是4位数的最后一位数。


假设你的4位数字在变量digit4中:

Integer digit4 = Integer.valueOf(Sequence.getText().toString());

然后你可以通过以下方式获得0到9之间的单个数字(实际上是4位数字的最后一位数字):

                int digit1 = digit4 % 10;

您尚未指定4位数字和单位数字之间的关系,因此如果您想要一个0 t0 9之间的随机数,无论输入如何,您都可以使用public int nextInt (int n)方法获取它:

Random r= new Random();
int digit1 = r.nextInt(10);