EditText does not take the value if entered a float value - java

Here's my code
if(numberbyUser.getText().toString().equals(""))
{
//Toast.makeText(getApplicationContext(), "Please Enter a Number", Toast.LENGTH_SHORT).show();
message = "Please Enter a Number !!";
DialogFunction();
}
If I enter a value for eg: 1.5 code goes into the above loop. But for values which are not decimal code just works fine.
Can somebody please tell me whats going wrong?

I suggest that make the EditText field as a text android:inputType="text" then do the conversion. Try this:
String sNumberByUser = numberbyUser.getText().toString();
Double number = 0.0;
try{
if(!sNumberByUser.equals("")){
// This will accept decimal and non-decimal number
number = Double.parseDouble(sNumberByUser);
//do your process here
}else{
throw new NumberFormatException();
}
//Catch if not a number.
}catch(NumberFormatException nfe){
message = "Please Enter a Number !!";
DialogFunction();
}

can you post the XML for the your edittext...it may be possible that you set the
inputType="number" instead of "decimal..."
<EditText
android:id="#+id/phone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="decimal" />
change inputType attribute to "decimal"

if(numberbyUser.getText().length() > 0) {
String numberString = numberByUser.getText().toString();
Double number = Double.parseDouble(numberString);
//To operation with entered number.
} else {
message = "Please enter number.";
DialogFunction();
}
And in your layout add android:inputType = "numberDecimal"
Hope this will help you.

Related

How to check the user input is an integer or not with Scanner?

I want the country codes are integer that input by the user. I want an error message to be show when user inputs a code which is not an integer. How can I do this? The program is to ask user to enter country name and country code. In which user will input the country code. But if user inputs a character I want a message to be shown saying Invalid Input.
System.out.println("Enter country name:");
countryName = in.nextLine();
System.out.println("Enter country code:");
int codeNumber = in.nextInt();
in.nextLine();
If the input is not an int value, then Scanner's nextInt() (look here for API) method throws InputMismatchException, which you can catch and then ask the user to re-enter the 'country code' again as shown below:
Scanner in = new Scanner(System.in);
boolean isNumeric = false;//This will be set to true when numeric val entered
while(!isNumeric)
try {
System.out.println("Enter country code:");
int codeNumber = in.nextInt();
in.nextLine();
isNumeric = true;//numeric value entered, so break the while loop
System.out.println("codeNumber ::"+codeNumber);
} catch(InputMismatchException ime) {
//Display Error message
System.out.println("Invalid character found,
Please enter numeric values only !!");
in.nextLine();//Advance the scanner
}
One simple way of doing it, is reading a line for the numbers as you did with the name, and then checking witha Regex (Regular Expression) to see if contains only numbers, with the matches method of string, codeNumber.matches("\\d+"), it returns a boolean if is false, then it's not a number and you can print your error message.
System.out.println("Enter country name:");
countryName = in.nextLine();
System.out.println("Enter country code:");
String codeNumber = in.nextLine();
if (codeNumber.matches("\\d+")){
// is a number
} else {
System.out.println("Please, inform only numbers");
}
You can do something like this, by first getting the input as a string, then try to convert the string to an integer, then outputs an error message if it can't:
String code= in.nextLine();
try
{
// the String to int conversion happens here
int codeNumber = Integer.parseInt(code);
}
catch (NumberFormatException nfe)
{
System.out.println("Invalid Input. NumberFormatException: " + nfe.getMessage());
}
You could instead check hasNextInt then call nextInt
int codeNumber;
System.out.println("Enter country code:");
if(in.hasNextInt())
{
codeNumber = in.nextInt();
}
else
{
System.out.println("Invalid Code !!");
}
If you are creating your own custom exception class, then use regex to check if the input string is an integer or not.
private final String regex = "[0-9]";
Then, check if the input follows the regex pattern.
if (codeNumber.matches(regex)) {
// do stuff.
} else {
throw new InputMismatchException(codeNumber);
}
You can use build in InputMismatchException if you are not creating your custom exception handler.

ChangePassword method in Java

I'm working on a Java project, building a simple system, and it has some methods, one of them is "Change PassWord", I put the user's information (username & password) in a text file called ("Users.txt").
Now this is the description of the method:
boolean ChangePassWord(): Asks the user to enter old password for
verification, the user has at maximum three tries to enter correct old
password; if not the password will not be changed and a message Box
will be shown for the user. If user entered correct old password then
he is authenticated to changer his password and asked to enter new
password and confirming the new. Once if confirmed correctly the old
password will be changed to the new one and a message box will be
shown if wrong confirmation the old password will not be changed and a
message box will be shown.
I wrote this code:
boolean changePassword(){
String pass=JOptionPane.showInputDialog(null, "Enter old password: ", "Input", JOptionPane.QUESTION_MESSAGE);
if(pass.equals(Password)) {
String newpass=JOptionPane.showInputDialog(null,
"Enter new password: ", "Input", JOptionPane.QUESTION_MESSAGE);
String connewpass=JOptionPane.showInputDialog(null,
"Enter confirming new password: ", "Input",
JOptionPane.QUESTION_MESSAGE);
if(newpass.equals(connewpass)){
Password= newpass;
JOptionPane.showMessageDialog(null, "password changed ", "message",
JOptionPane.INFORMATION_MESSAGE);
return true;
}
else
JOptionPane.showMessageDialog(null, "Wrong Conferm ", "message",
JOptionPane.INFORMATION_MESSAGE);
}
else
JOptionPane.showMessageDialog(null, "Wrong password ", "message",
JOptionPane.INFORMATION_MESSAGE);
return false;
}
but I think that it's wrong, and I need to use a loop I think.
I hope you help me!
A while loop is appropriate for your case. I will briefly explain how this while loop runs 3 times.
So, first n=3. The condition n-- > 0 means 2 things. Check if n is greater than zero and subtract the value of n by 1. These 2 things happen in that exact order.
So the condition checks that n is indeed greater than zero and enters the loop. At the same time n is also decreased by 1 and becomes 3-1=2.
This goes on 3 times. After the 3rd time, n becomes 0. And the condition 0 > 0 is false and therefore the while loop breaks.
boolean changePassword(){
String pass = ""; //get old password from user
int n = 3;
while (n-- > 0) {
if(pass.equals(Password)) {
String newPass = ""; // get new password from user
String conNewPass = ""; // confirm new password from user
if (newPass.equals(conNewPass)) {
Password = newPass;
// password changed
return true;
} else {
// wrong confirmation.. password not changed
return false;
}
}
else {
// tell user to enter the correct old password
pass = ""; // ask user for old password again
}
}
// show error message that user entered the old password 3 times incorrectly
// and return false
return false;
}

JOptionaPane Inputdialogbox and buttons

The below code is working perfecly
String input = JOptionPane.showInputDialog(null, "Enter Input",
"Dialog title",JOptionPane.QUESTION_MESSAGE);
Now I have Ok and Cancel buttons. I want to do something like
if(OK is selected){
String input1 = input
do something with input1
}
else if (cancel is selected){
System.dispose();
}
I'm clueless about what to write inside if condition. I know that for ShowOptionDialog I can get an int of selected option and use it but for inputdialog Im not sure how I can get both the selected option and input text.
Could you please help me
So the JavaDocs say
Returns:
user's input, or null meaning the user canceled the input
That mean that something like
String input = JOptionPane.showInputDialog(null, "Enter Input",
"Dialog title",JOptionPane.QUESTION_MESSAGE);
if (input != null) {
// User accepted
} else {
// User cancelled
}
Should work...

how can I input decimals in to input field - android

I'm just starting to play around with android app.
I have an text field to input numbers but somehow I can only type in regular integers without decimals.
any idea what I can do so I can input decimals too?
This is what I have..
public void onClick(View arg0) {
EditText edit = (EditText)findViewById(R.id.editText1);
TextView text = (TextView)findViewById(R.id.textView1);
String input = edit.getText().toString();
float num = 0;
try {
num = Integer.parseInt(input);
} catch (NumberFormatException e) {
input = "0";
}
double newNum = num * 1.12;
DecimalFormat df = new DecimalFormat("###.##");
text.setText(input + " * 12% = " + df.format(newNum));
Add the following attribute to your EditText in xml:
android:inputType="numberDecimal"
This will inform the keyboard to enter decimals.
if you want to get decimal number keyboard you should add inputType with value numberDecimal in EditText xml file:
android:inputType="numberDecimal"
And if you want to use comma and dot also, you should add digits also in EditText xml:
android:digits="0123456789.,"
and when you get that result in Java, don't forget to replace dot with comma because Double and Float can only parse dot separated text:
String test = "12,34";
String changed = test.replace(",",".")
float value = Float.parseFloat(changed)

Cancel button in showinputdialogbox

I have a few buttons on my panel and everytime I click on it an input dialog box appears. It has an inbuilt cancel button. Now, when i click on the cancel button in the beginning of the code without entering the quantity in the dialog box, it says, "This is an invalid" number. This line has to only appear if the user enters alphabets or symbols, and not on pressing cancel. Can we solve this?
First you need a way to decide if a String represents a number; the method below uses Double.valueOf() to decide.
private Double valueOf(String s) {
try {
return Double.valueOf(s);
} catch (NumberFormatException e) {
return null;
}
}
Here's an example of how you might use the method:
private void display() {
String input = JOptionPane.showInputDialog(
null, "Enter a number?", "Number", JOptionPane.QUESTION_MESSAGE);
Double value = valueOf(input);
JOptionPane.showMessageDialog(null, "The value " + input
+ " is " + (value != null ? "valid" : "invalid") + ".");
}
See also How to Make Dialogs.
Try doing,
String Input = JOptionPane.showInputDialog(null,"Enter the number?",
"Number", JOptionPane.QUESTION_MESSAGE);
if (Input.equals(""))
{
JOptionPane.showMessageDialog(null,"This is an invalid number");
}
The following link explains it even better: Simple Data Validation.
String Input = JOptionPane.showInputDialog(null,"Enter the number?",
"Number", JOptionPane.QUESTION_MESSAGE);
if
(Input.matches(("((-|\+)?[0-9]+(\.[0-9]+)?)+"))) {
JOptionPane.showMessageDialog(null,"valid number");
}
else{
JOptionPane.showMessageDialog(null,"This is an invalid number");
}

Categories