I want to create a program that has the capability to check a string if it is valid to be as a person's name. But I am struggling to use regular expression for validating the string if its acceptable to be a person's name or not. Can you help me to implement the right conditions in my code? A string will be considered as a person's name if the following conditions are fulfilled:
no space before first word
no non-word character
no 2 or more consecutive spaces
I would also like to remove a space if it exists after the last word in my string. I am doing all of this just to force a user to input the right format of text that I will post soon on my JSON. That's why everything should be validated at the first place. No problem about whitespaces because I already defined the right inputType of my EditText on my XML file.
This is the code that I tried to implement:
public boolean isFirstnameValid(String regex, String text){
Pattern checkRegex = Pattern.compile(regex);
Matcher regexMatcher = checkRegex.matcher(text);
while(regexMatcher.find()){
if(regexMatcher.group().length()!=0){
Log.e("searched",regexMatcher.group().trim());
}
}
return false;
// I returned false because, I'm still confused about what conditions should I implement.
}
This is the main method where my actual parameter is implemented:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// String firstname = "Kirby Aster";
// String lastname = "Abadilla";
et =(EditText) findViewById (R.id.editText1);
b = (Button) findViewById (R.id.button1);
b.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String text = et.getText().toString();
isFirstnameValid("[A-Za-z]{1,}", text);
}
});
}
I don't like the implementation of isFirstnameValid method. I think you are making it a bit complex than it should be. I would use simple String.matches to do the job, eg :
public boolean isFirstnameValid(String text){
return text..matches("^([A-Za-z]+)(\\s[A-Za-z]+)*\\s?$");
}
The above regex meets all your conditions including allowing a space at the end. You may consider another condition of capital letter at the first of each word(regex will change a little). Then call it like :
if( isFirstnameValid(text) ){
text = text.trim();
} else {
// define your failing condition here
}
If you have any query feel free to ask.
Related
import java.util.Scanner;
public class Test{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
input.useDelimiter(".");
String given = input.next();
System.out.println(given);
}
}
When I run the above code and type in asdf. then enter, I get nothing.
It works fine with "," ";" "\"" "\\\\" or whatever, but just not with "."... So is there something about a dot or is it just a problem with Eclipse IDE or whatever?
Scanner is using regular expression (regex) as delimiter and dot . in regex is special character which represents any character except line separators. So if delimiter is any character when you write asdf. each of its character will be treated as delimiter, not only dot. So each time you will use next() result will be empty string which exists in places I marked with |
a|s|d|f|.
To create dot literal you need to escape it. You can use \. for that. There are also other ways, like using character class [.].
So try with
input.useDelimiter("\\.");
/This could be another helpful example, that how the use of Delimeter?
The scanner detects DOTs in any string then it will simply separate and store the string data in ArrayList by the help of any LOOP./
/If it is helped Hit the UP button./
public class MainActivity extends AppCompatActivity {
EditText et_ip_address;
TextView txt_1st;
TextView txt_2nd;
TextView txt_3rd;
TextView txt_4th;
Button btn_getResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_getResult = findViewById(R.id.button);
et_ip_address = findViewById(R.id.et_ip_address);
txt_1st = findViewById(R.id.txt_1st);
txt_2nd = findViewById(R.id.txt_2nd);
txt_3rd = findViewById(R.id.txt_3rd);
txt_4th = findViewById(R.id.txt_4th);
final ArrayList data = new ArrayList();
//Click on this button execute the code to separate Strings
btn_getResult.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
data.clear();
Scanner fromString = new Scanner(et_ip_address.getText().toString());
fromString.useDelimiter("\\."); //this is how we should use to detects DOT
while(fromString.hasNext()){
String temp = fromString.next();
data.add(temp);
}
txt_1st.setText(data.get(0).toString());
txt_2nd.setText(data.get(1).toString());
txt_3rd.setText(data.get(2).toString());
txt_4th.setText(data.get(3).toString());
}
});
}
}
Okay so I have this code that I wrote for an Android App personality quiz in Android studio. My GUi window works correctly and it correctly links to my phone and looks good. However, when i click the submission button(upload to the force) a different picture does not show up like it should when I enter the correct responses. I know it isnt a problem with my pictures since if I take the ImageSetter out of the switch case it appears in the App. So the conclusion I have come to is that somehow my code for reading in the text from the EditText field box int he GUI window is not right or I am building the list of letters to check wrong. (Yes I know putting it in an arraylist just to make it into a string is redundant however I was doing it the first way I thought of. Any suggestions Ive spent hours on this and cant think of what is going wrong?? You guys are the best I appreciate it.
`
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
EditText nameTxt, answer2, answer3, answer4, answer5, answer6, answer7, answer8;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView imageview = (ImageView)findViewById(R.id.showCharacter);
//have to cast it into type (EditText) since by default is is a GUI container and an error
//will be generated if you do not again specify that the container is type EditText
nameTxt = (EditText) findViewById(R.id.inputA1);//links nameTxt to GUI editText field
answer2 = (EditText) findViewById(R.id.inputA2);//links nameTxt to GUI editText field
answer3 = (EditText) findViewById(R.id.inputA3);//links nameTxt to GUI editText field
answer4 = (EditText) findViewById(R.id.inputA4);//links nameTxt to GUI editText field
answer5 = (EditText) findViewById(R.id.inputA5);//links nameTxt to GUI editText field
answer6 = (EditText) findViewById(R.id.inputA6);//links nameTxt to GUI editText field
answer7 = (EditText) findViewById(R.id.inputA7);//links nameTxt to GUI editText field
answer8 = (EditText) findViewById(R.id.inputA8);//links nameTxt to GUI editText field
ArrayList<String> responses = new ArrayList<String>();//string array to hold temp responses
String respStr = "";//used for comparison to the answer key since it is easier than using an
//arraylist for comparison.
String character = "";// honestly this doesnt output anything or do anything except help me
//keep track of which key corresponds to which picture so I dont get confused
//creates a new button called addBtn and likes it to the GUI button btnAdd
final Button addBtn = (Button) findViewById(R.id.btnAdd);
if (addBtn != null) {//designed to not allow the submission button to be clickable unless
//the first field is filled out
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(),"Using the Force", Toast.LENGTH_SHORT).show();
}
}) ;
}
nameTxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
addBtn.setEnabled(String.valueOf(nameTxt.getText()).trim().length() > 0);
}
#Override
public void afterTextChanged(Editable s) {
}
});
//takes the input of the first question using getText() then it must convert getText which
//of type EditText to type string using toString. Then the variable is set to itself with
//no leading or trailing spaces using the .trim(0 and then made lowercase by using the
//toLowerCase. equalsIgnoreCase is used as a redundant wway to ensure that input from the
//user can be either upper or lower case.
String q1S = "";
q1S = nameTxt.getText().toString();
q1S = q1S.trim().toLowerCase();
if (q1S.equalsIgnoreCase("a")){
responses.add("a");
}
if (q1S.equalsIgnoreCase("b")){
responses.add("b");
}
if (q1S.equalsIgnoreCase("c")){
responses.add("c");
}
if (q1S.equalsIgnoreCase("d")){
responses.add("d");
}
if (q1S.equalsIgnoreCase("e")){
responses.add("e");
}
for(int i =0; 0>responses.size(); i++){
respStr += responses.get(i);
}
//takes the input of the second question using getText() then it must convert getText which
//of type EditText to type string using toString. Then the variable is set to itself with
//no leading or trailing spaces using the .trim(0 and then made lowercase by using the
//toLowerCase. equalsIgnoreCase is used as a redundant wway to ensure that input from the
//user can be either upper or lower case.
String q2S = "";
q2S = nameTxt.getText().toString();
q2S = q2S.trim().toLowerCase();
if (q2S.equalsIgnoreCase("a")){
responses.add("a");
}
if (q2S.equalsIgnoreCase("b")){
responses.add("b");
}
if (q2S.equalsIgnoreCase("c")){
responses.add("c");
}
if (q2S.equalsIgnoreCase("d")){
responses.add("d");
}
if (q2S.equalsIgnoreCase("e")){
responses.add("e");
}
//takes the input of the third question using getText() then it must convert getText which
//of type EditText to type string using toString. Then the variable is set to itself with
//no leading or trailing spaces using the .trim(0 and then made lowercase by using the
//toLowerCase. equalsIgnoreCase is used as a redundant way to ensure that input from the
//user can be either upper or lower case.
String q3S = "";
q3S = nameTxt.getText().toString();
q3S = q3S.trim().toLowerCase();
if (q3S.equalsIgnoreCase("a")){
responses.add("a");
}
if (q3S.equalsIgnoreCase("b")){
responses.add("b");
}
if (q3S.equalsIgnoreCase("c")){
responses.add("c");
}
if (q3S.equalsIgnoreCase("d")){
responses.add("d");
}
if (q3S.equalsIgnoreCase("e")){
responses.add("e");
}
//takes the input of the fourth question using getText() then it must convert getText which
//of type EditText to type string using toString. Then the variable is set to itself with
//no leading or trailing spaces using the .trim(0 and then made lowercase by using the
//toLowerCase. equalsIgnoreCase is used as a redundant way to ensure that input from the
//user can be either upper or lower case.
String q4S = "";
q4S = nameTxt.getText().toString();
q4S = q4S.trim().toLowerCase();
if (q4S.equalsIgnoreCase("a")){
responses.add("a");
}
if (q4S.equalsIgnoreCase("b")){
responses.add("b");
}
if (q4S.equalsIgnoreCase("c")){
responses.add("c");
}
if (q4S.equalsIgnoreCase("d")){
responses.add("d");
}
if (q4S.equalsIgnoreCase("e")){
responses.add("e");
}
//takes the input of the fifth question using getText() then it must convert getText which
//of type EditText to type string using toString. Then the variable is set to itself with
//no leading or trailing spaces using the .trim(0 and then made lowercase by using the
//toLowerCase. equalsIgnoreCase is used as a redundant way to ensure that input from the
//user can be either upper or lower case.
String q5S = "";
q5S = nameTxt.getText().toString();
q5S = q5S.trim().toLowerCase();
if (q5S.equalsIgnoreCase("a")){
responses.add("a");
}
if (q5S.equalsIgnoreCase("b")){
responses.add("b");
}
if (q5S.equalsIgnoreCase("c")){
responses.add("c");
}
if (q5S.equalsIgnoreCase("d")){
responses.add("d");
}
if (q5S.equalsIgnoreCase("e")){
responses.add("e");
}
//takes the input of the sixth question using getText() then it must convert getText which
//of type EditText to type string using toString. Then the variable is set to itself with
//no leading or trailing spaces using the .trim(0 and then made lowercase by using the
//toLowerCase. equalsIgnoreCase is used as a redundant way to ensure that input from the
//user can be either upper or lower case.
String q6S = "";
q6S = nameTxt.getText().toString();
q6S = q6S.trim().toLowerCase();
if (q6S.equalsIgnoreCase("a")){
responses.add("a");
}
if (q6S.equalsIgnoreCase("b")){
responses.add("b");
}
if (q6S.equalsIgnoreCase("c")){
responses.add("c");
}
if (q6S.equalsIgnoreCase("d")){
responses.add("d");
}
if (q6S.equalsIgnoreCase("e")){
responses.add("e");
}
//takes the input of the seventh question using getText() then it must convert getText which
//of type EditText to type string using toString. Then the variable is set to itself with
//no leading or trailing spaces using the .trim(0 and then made lowercase by using the
//toLowerCase. equalsIgnoreCase is used as a redundant way to ensure that input from the
//user can be either upper or lower case.
String q7S = "";
q7S = nameTxt.getText().toString();
q7S = q7S.trim().toLowerCase();
if (q7S.equalsIgnoreCase("a")){
responses.add("a");
}
if (q7S.equalsIgnoreCase("b")){
responses.add("b");
}
if (q7S.equalsIgnoreCase("c")){
responses.add("c");
}
if (q7S.equalsIgnoreCase("d")){
responses.add("d");
}
if (q7S.equalsIgnoreCase("e")){
responses.add("e");
}
//takes the input of the eigth question using getText() then it must convert getText which
//of type EditText to type string using toString. Then the variable is set to itself with
//no leading or trailing spaces using the .trim(0 and then made lowercase by using the
//toLowerCase. equalsIgnoreCase is used as a redundant way to ensure that input from the
//user can be either upper or lower case.
String q8S = "";
q8S = nameTxt.getText().toString();
q8S = q8S.trim().toLowerCase();
if (q8S.equalsIgnoreCase("a")){
responses.add("a");
}
if (q8S.equalsIgnoreCase("b")){
responses.add("b");
}
if (q8S.equalsIgnoreCase("c")){
responses.add("c");
}
if (q8S.equalsIgnoreCase("d")){
responses.add("d");
}
if (q8S.equalsIgnoreCase("e")){
responses.add("e");
}
//imageview.setImageResource(R.drawable.sidious);
switch(respStr){
case "aabaacaa":
character ="Sideous";
imageview.setImageResource(R.drawable.sidious);
break;
case "abdbadaa":
character ="Maul";
imageview.setImageResource(R.drawable.maul);
break;
case "aadccdab":
character ="Vader";
imageview.setImageResource(R.drawable.vader);
break;
case "bbbdcaaa":
character ="Boba Fett";
imageview.setImageResource(R.drawable.boba);
break;
case "abeeadba":
character ="Grevous";
imageview.setImageResource(R.drawable.grievous);
break;
case "aaacbabb":
character ="Windu";
imageview.setImageResource(R.drawable.windu);
break;
case "abacbbbb":
character ="Obi-Won-Kenobi";
imageview.setImageResource(R.drawable.kenobi);
break;
case "bacbcaab":
character ="Solo";
imageview.setImageResource(R.drawable.solo);
break;
case "bbaccaba":
character ="Clone";
imageview.setImageResource(R.drawable.trooper);
break;
case "aacbbabb":
character ="Anakin";
imageview.setImageResource(R.drawable.anakin);
break;
default:
character = "R2D2";
}
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
`
your for loop have a wrong condition.
your code:
for(int i =0; 0>responses.size(); i++){
respStr += responses.get(i);
}
should be:
for(int i=0; i<responses.size(); i++){
respStr += responses.get(i);
}
temp1 is "accountant"editText is "accountant"
but i checked with String.length();
temp1 is a string has 11 characters editText has 10 characters
I tried trim() method, i got the same result again.
Code sample:
if(temp1.equalsIgnoreCase(editText1.getText().toString().trim()))
{
//do someting
}
I solved.
I coverted source file to UTF-8 with "Notepad++" and get words from new source file. EqualsIgnoreCase works now.
Since temp1 is a string and has 11 characters, you must have placed a whitespace after the word accountant. (Either that or you flat out misspelled the word.) Accountant is only 10 characters long, so there must be whitespace. (Well, it's pretty guaranteed since you, yourself, created it.)
Either remove the whitespace from temp1, or trim temp1 before you compare.
Also, double-check temp1 to actually make sure you spelled the word correctly.
You may try this code :
//put this below public class activity
int index=0;
String [] answer ={"Accountant"};
and put this button code below setContentView
buttonanswer = (Button)findViewById(R.id.yourbutton);
buttonanswer.setOnClickListener(this);
and then put this code
#Override
public void onClick(View v) {
edittextanswer=(EditText)findViewById(R.id.youreditText);
if(v==buttonanswer) {
String myanswer=edittextanswer.getText().toString();
if(myanswer.equalsIgnoreCase(answer[index]))
{
//do someting
}
else
{
//do someting
}
I would like to change a TextView as a user adds things to a cart. The initial value is 0.00 and as the user adds items, this is added to the value. I have an AlertDialog that pops up when clicking a button that allows the user to choose an item.
My issue is a java.lang.StringToReal.invalidReal error. I think that I may not be getting the value of the TextVeiw properly but am not totally sure.
Thanks to anyone looking at this.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.pickItem);
builder.setItems(R.array.items, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
CartItems ci = new CartItems();
ci.setItem(which);
ci.setPrice(which);
cart.add(ci);
totalPriceTV = (TextView)findViewById(R.id.textView2);
double totalPrice = Double.parseDouble(totalPriceTV.toString());
totalPrice += ci.getPrice();
String newTotal = new Double(totalPrice).toString();
totalPriceTV.setText(newTotal);
}
});
builder.create();
builder.show();
}
});
}
In this line
double totalPrice = Double.parseDouble(totalPriceTV.toString());
Change totalPriceTV.toString() to totalPriceTV.getText().toString() and try again.
In order to change the text of a TextView in Android just use the ordinary geters and setters:
TextView.getText();
TextView.setText("text");
Since you deal with numbers i suggest you to use DecimalFormat when parsing a double to string. You can easily define the format of the number (i.e the number of digits after comma or the separator characters)
DecimalFormat df = new DecimalFormat("###,###.00");
String price = df.parse(someDouble);
textView.setText(price);
For these numbers: 234123.2341234 12.341123 the DecimalFormat would give you the following result:
234,123.23 and 12.34
Taken from page: http://developer.android.com/reference/android/view/View.html#toString()
Added in API level 1
Returns a string containing a concise, human-readable description of this object. Subclasses are encouraged to override this method and provide an implementation that takes into account the object's type and data. The default implementation is equivalent to the following expression:
getClass().getName() + '#' + Integer.toHexString(hashCode())
As a result you should use getText();
ie:
totalPriceTV.getText()
Just use totalPriceTV.setText(""+totalPrice);
or
totalPriceTV.setText(String.valueOf(totalPrice));
I have a method that checks for a null value from an editText on a click of a button like so:
public void myClickHandler09(View chv){
if (text9.equals("")){
text9.setText("0");
}else{
converter(text9);
}}
The
converter(text9);
method is as shown:
public void converter(View view){
switch (view.getId()) {
case R.id.Button09:
RadioButton RadioButtons = (RadioButton) findViewById (R.id.RadioButton901);
float inputValue = Float.parseFloat(text9.getText().toString());
if (RadioButtons.isChecked()) {
text9.setText(String
.valueOf(convertRadioButtons(inputValue)));
}
break;
}}
private double convertRadiobuttons(float inputValue){
return inputValue * 6.4516;
}
The method is larger but here i've only called one radiobutton to shorten it.
Right now though the if statement seems to do absolutely nothing and so non of the rest of the code works. If i remove the method and rename
converter(View view){
to
myClickHandler09(View view){
then the code works and until you enter a null value into the EditText (then it crashes)
What am I doing wrong exactly here?
NOTE: the method name "myClickHandler09" is linked to the button as android:onClick in the xml
You need to do if("".equals(text9.getText().toString())) { ...
The toString() is there because the TextView will return a CharSequence which may or may not be a String.
Right now you are comparing the TextView itself to "", and not the String it is showing.
Edit - As far as the crash goes, you also want to catch the NumberFormatException that Float.parseFloat() throws.
float inputValue = 1.0f; // some default value, in case the user input is bad.
try {
inputValue = Float.parseFloat(text9.getText().toString());
} catch (NumberFormatException e) {
// possibly display a red flag next to the field
}
Why not try
if ("".equals(text9.getText())) {
} else {
}
You essentially have to do a getText() from a TextView and not equals a String with a TextView.
One thing I don't understand with your code is that you call:
converter(text9);
passing in the EditText, but by replacing converter(View view) with the function name myClickHandler09 (like so):
myClickHandler09(View view) {
the button being pressed with call this function (if you defined it in the xml layout onClick paramter).
So to match this behaviour with your current code, try this out:
public void myClickHandler09(View btnView){
if (text9.equals("")){
text9.setText("0");
} else {
converter(btnView);
}
}
I may have missed the point of you're post, but I think that is part of your issue. Also in stead of .equals("") I prefer (text9.toString().length() > 0) just seems a bit more logical, but that's me being a bit pedantic.