【问题标题】:String.charAt() is not returning values expectedString.charAt() 没有返回预期值
【发布时间】:2013-10-28 10:38:40
【问题描述】:

我正在使用 IF 语句来检查值 MobileNumber 是否以 07 开头。这是我的代码:

public void MobileNumberCheck(EditText MobileNumber_Text, TextView ErrorDisplay, Boolean Output) {
        Editable MobileNumber = MobileNumber_Text.getText();
        Output = false;
        ///This method only has to check that the mobile number starts with 07, as the XML specifies the number can only be number, and 11 digits long.
        if( (MobileNumber.charAt(0) != "0".charAt(0) ) || (MobileNumber.charAt(1) != "7".charAt(0)) ){
                ErrorDisplay.setText("Invalid UK mobile number");
        }
            else if( (MobileNumber.charAt(0) == "0".charAt(0)) && (MobileNumber.charAt(1) == "7".charAt(0)) ){

                    ///Do nothing
                    ErrorDisplay.setText("");
                    Output = true;


            }
            else
                ErrorDisplay.setText(MobileNumber.charAt(0) + MobileNumber.charAt(1));
    }





public void AddPeople_Save(View view){
    TextView ErrorDisplay = (TextView) findViewById(R.id.AddPeople_ErrorDisplay);
    EditText MobileNumber_ET = (EditText) findViewById(R.id.AddPeople_MobileNumber);
    Boolean WriteReady = false;
    MobileNumberCheck(MobileNumber_ET, ErrorDisplay, WriteReady); ///Runs the method specified above. Doesn't output, except into the TEXTVIEW ErrorDisplay.
    EditText Name_ET = (EditText) findViewById(R.id.AddPeople_Name);

    String AddPeople_PeopleFilename = "PartyApp_PeopleFile";
    String Person_Details = Name_ET.toString() + MobileNumber_ET.toString();
    FileOutputStream outputStream;
    if(WriteReady == true)
            try {
                outputStream = openFileOutput(AddPeople_PeopleFilename, Context.MODE_PRIVATE);
                outputStream.write(Person_Details.getBytes());
                outputStream.close();
            } catch (Exception e) {
      e.printStackTrace();
    }
    else{
        ///Do nothing. The error message is passed through METHOD MobileNumberCheck.
        ErrorDisplay.setText("AAA" + WriteReady);

    }

你能告诉我我做错了什么吗?我假设我的逻辑运算符 && 和 ||是错误的,或者string.CharAt() 执行错误。谢谢!!

【问题讨论】:

  • string.CharAt() 执行错误 ...你真的这么认为吗?
  • 请给我们一些输入和预期输出和当前输出
  • 不认为它被错误地实现了(在我的代码中)但是跟踪它,这是我不确定的一件事。输入以除“07”以外的任何内容开头的电话号码应停止将其写入文件,并在 ErrorDisplay 中显示一条消息

标签: android string operators logic charat


【解决方案1】:

此方法只需要检查手机号码是否以07开头,因为XML规定号码只能是数字,长度为11位。

我只会使用:

if(MobileNumber.toString().startsWith("07") && MobileNumber.length() <= 11){

}

【讨论】:

  • 谢谢,这已经奏效了!!我只需要使用 "MobileNumber.toString().startsWith("07") 因为我是在 Eclipse 中做的,并且可以设置 EditText 的长度。谢谢!!
【解决方案2】:

if(num.startsWith("0") &amp;&amp; num.startsWith("7", 1)) 要么 if(num.startsWith("07")) 会起作用。

【讨论】:

    猜你喜欢
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-05
    • 2020-06-30
    • 2018-08-17
    相关资源
    最近更新 更多