简体   繁体   中英

String using operator > and < java to limit the number of numbers

I am new to android and java. I need help. I need to use String for a method isValid as shown below. But strings can't use the operator > and <. I am using it to restrict the user from putting invalid number which is more than 9 numbers. Thanks in advance.

package com.Elson.ProjectVersion;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar; 

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class EnterContactsActivity extends Activity {

private Button saveButton;
private EditText NameEditText;
private EditText PhoneEditText;
private Button ExitButton;
private EditText EmailEditText;
private TextView date;


private int month;//private within class
private int day;
private int year;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_addcontacts);

    setUpViews();

    Calendar calendar =Calendar.getInstance();
    year = calendar.get(Calendar.YEAR);
    month = calendar.get(Calendar.MONTH);
    day = calendar.get(Calendar.DAY_OF_MONTH);

    Date today = calendar.getTime();
    DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
    String cs = df.format(today);
    date.setText(cs);
}


public void saveClickHandler(View v){

    String ContactsScore;
    ContactsScore= NameEditText.getText().toString();
    String name = String.format(ContactsScore);
    ContactsScore= PhoneEditText.getText().toString();
    String Phone = String.format(ContactsScore);


    Log.d("EnterContacts" , "I hear the Save Button");

    if ( isValid(Phone) ){
        Contacts contacts;
        Date dateofGames= new GregorianCalendar(year,month,day).getTime();
        contacts = new Contacts (name , Phone ,  dateofGames);

        ContactsActivityApplication app  = (ContactsActivityApplication) getApplication();
        //might be wrong

        Log.d("DeBUGGING", "app is this type: " + app.getClass().getName());
        //need add the function addBowlingScores
        app.addallContacts(contacts);

        Toast.makeText(getApplicationContext(), "Your Contact has been Saved!", Toast.LENGTH_SHORT).show();

}
    if( name == null)  {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Please enter your name")
               .setMessage("Phone numbers cannot have more than 8 numbers")
               .setCancelable(false)
               .setPositiveButton("OK", 

                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.cancel(); 
                    }
                });

        AlertDialog alert = builder.create();
        alert.show();
    }



    }



//error is here
private boolean isValid() {

    if (Phone > 0 && Phone < 100000000)
        return true;
    return false;
    // TODO Auto-generated method stub
}





private void setUpViews()
{
    ExitButton = (Button) findViewById(R.id.BtnExit);
    saveButton =(Button) findViewById(R.id.BtnSave);
    NameEditText= (EditText) findViewById(R.id.NameEditText);
    PhoneEditText= (EditText) findViewById(R.id.PhoneEditText);
    EmailEditText= (EditText) findViewById(R.id.EmailEditText);
    date = (TextView) findViewById(R.id.DateTextView);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.addcontacts, menu);
    return true;
}

}

Contacts

 package com.Elson.ProjectVersion;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;


public class Contacts implements Comparable<Contacts> {

    private long id;
    private String name;
    private String Phone;
    private int Email;
    private Date date;
    private double runningAverage;




    public Contacts(String name, String Phone,  Date date) {
        this.name = name;
        this.Phone = Phone;
        this.date = null;
    }

    public Contacts(long id, String name,String Phone) {
        this.id=id;
        this.Phone=Phone;
        this.name= (name);

    }


    public long getId() {

        return id;
    }
    public void setId(long id) {
        this.id = id;
    }

    public String getPhone() {
        return Phone;
    }
    public void setPhone(String Phone) {
        this.Phone = Phone;
    }
    public String getname() {
        return name;
    }
    public void setname(String name) {
        this.name = name;
    }
    public Date getDate() {
        return null;
    }

    public long getDateEpoch(){
        return date.getTime()/1000;
    }
    public void setDateEpoch(long seconds){
        date= new Date (seconds*1000);
    }
    public void setDate(Date date) {
        this.date = date;
    }




    public void setRunningAverage(double runningAverage) {
        this.runningAverage = runningAverage;
    }
    public boolean equals(Object that){
        Contacts bs = (Contacts) that;

        return this.date.equals(bs.date);
      }


    @Override



    public String toString() {
        String result;

        if(date != null) {
            DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
            result = df.format(date) + "" + name + "" + Phone ; 
    }
    else {
          result = name + "" + Phone ; 
    }
        return result;
    }





    @Override
    public int compareTo(Contacts another) {    
        // TODO Auto-generated method stub
        return 0;
    }

}

You need to convert the String to a representation which supports comparisons with an int : another number.

You can do it by using Long.parseLong(String string) :

long phoneNumber = Long.parseLong(Phone);
if (phoneNumber > 0 && phoneNumber < 10000000)

Mind that this can throw a NumberFormatException if you try to parse a string which is not a representation of number, so you should enclose the code in a try/catch block and return false if the exception is thrown.

There is nothing strange in the fact that a String doesn't directly support comparisons with < and > with a number. They are different types which are not implicitly convertible to each other.

The question

is "foobar" lesser than 6141 ?

doesn't make any sense.

Don't use comparisons, use a regex:

if(phone.matches("[0-9]{1,9}")){
     //Do soemthing
}

If you need a numerical value, do

long phNum= Long.parseLong(phone);

Then do whatever you need with phNum . Don't forget to wrap this in a try block and catch NumberFormatException .

您只需要首先将字符串转换为int即可。

int foo = Integer.parseInt("1234");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM