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());
}
});
}
}
Related
In my app, i want to be able to format numbers to string (with commas) in a TextView e.g 123456.000 to 123,456.000. But the problem is when i type zero (0) as the last number after the decimal point, it shows nothing until i type another number. For example, if i type 123456.000, i get 123,456. The zeros doesn't show until i type another number like "1" then i get 123,456.0001. Please how do i make zeros show as last number after decimal point? Below are some sample codes.
I apologise for the clumsiness of the code. I manually typed it with my phone.
TextView txtView;
boolean NumberClicked = false;
String number = "";
// format pattern
DecimalFormat formatter = new DecimalFormat("#,###.#########");
// input dot (decimal point)
dot.setOnClickListener (new View.OnClickLstener() {
public void onClick(View view) {
if (!txtView.getText.toString.contains(".") {
input(".");}}});
// input zero (0)
zero.setOnClickListener (new View.OnClickLstener() {
public void onClick(View view) {
input("0");
}});
// input one (1)
one.setOnClickListener (new
View.OnClickLstener() {
public void onClick(View view) {
input("1");}});
// input method
public void input (String view) {
if (!numberClicked) {
number = view;
numberClicked = true;
} else {
number = number + view;
}
// print the entered numbers to
//the TextView after formatting
if (!number.endsWith(".")) { txtView.setText(formatter.format(Double.parseDouble(number)));}}
enter code here
You may try this code snippet:
DecimalFormat df = new DecimalFormat("#,##0.0#");
df.setMinimumFractionDigits(3);
String value = df.format(123456.000);
Output: 123,456.000
For more info pls click here.
Try with:
String.format("%,.03f", 123456.000)
I am building a calculator app and everything is working properly but I don't know the code for backspace.
public class MainActivity extends AppCompatActivity {
// UI Elements
private TextView num_input;
private TextView num_input;
private ImageButton num_backspace;
private float input, input2 ;
boolean Addition, Subtract, Multiplication, Division, mRemainder, decimal, add_sub;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing
num_input = findViewById(R.id.num_input);
num_output = findViewById(R.id.num_output);
num_backspace = findViewById(R.id.num_backspace);
num_backspace.setOnClickListener(new View.OnClickListener() {
#Override
//TODO: the backslash code goes here.
});
}
}
I tried doing this👇🏻
num_backspace.setOnClickListener(new View.OnClickListener() {
#Override
input = Float.parseFloat(num_input.getText() + "");
String sample_input = Float.toString(input);
sample_input = sample_input.substring(0,sample_input.length() - 1);
});
Some help would be great!
thanks in advance
It's better to store input as a String, not float. Because before you start doing mathematical calculations it's just a String input, and "backspace" means basically removing one character, it's not a mathematical operation. So, provided input is a String, backspace code will be:
input = input(0, input.length() - 1);
num_input.setText(input);
And before doing calculations convert your String input into float via
float operand = Float.parseFloat(input);
Put this code inside your setOnClickListener
String value = num_input.getText().toString();
if (value != null && value.length() > 0 ) {
value = value.substring(0, value.length() - 1);
}
num_input.setText(value);
How this is usually done is getting the current value (entered number) in the TextView, remove the last character from the string and writing it back to the TextView.
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);
}
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.
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));