Editable to string Crash - java

I made this code and the program crashes when I try to convert the editable's value to an integer since the texted it type is decimal, and I suspect it's at the point when the application must change the editable to string, due to the fact when the edit text is empty after editing the text it crashes.
EditText Y = (EditText) findViewById(R.id.y);
Y.addTextChangedListener(new TextWatcher(){
#Override
public void afterTextChanged(Editable s) {
if(s != null){
int Yvalue = Integer.parseInt(s.toString());
}
}

It looks more likely to me that the NumberFormatException should be occurring while parsing the String to an Integer. Try enclosing it within the try/catch for that exception.
try {
Yvalue = Integer.parseInt(number);
} catch (NumberFormatException e) {
Yvalue = defaultVal; // or do whatever necessary
}

try to parse the value of string to float and get it in float variable
float Yvalue = Float.parseFloat(s.toString());

Assuming you want integers only, try something like this:
#Override
public void afterTextChanged(Editable s) {
if (s.length() == 0) {
// complain about no input
} else {
try {
int yValue = Integer.parseInt(s.toString());
// ...
} catch (NumberFormatException e) {
// complain about invalid input
}
}
}
I'm not an Android developer, but I'd be surprised if there wasn't a way to add a mask to your input field that prevents anything other than integers being input.

Related

Showing 0 after decimal separator in java

i'm doing a calculator app and i'm using Decimal Format to format my number.
My problem is i want it to show number like 0,003. But 2 zero after the comma didn't show up until I typing 3. Please help me fix this
Here my code
DecimalFormatSymbols formatSymbolsGermany = DecimalFormatSymbols.getInstance(Locale.GERMANY);
DecimalFormat decimalFormat = new DecimalFormat("#,###,###.########", formatSymbolsGermany);
My code to add "0"
private void zeroOnClick() {
if (tvNumber.getText().toString().length() < 11) {
convertNumber("0");
}
}
private void convertNumber(String number) {
number1 += number;
try {
double a = Double.parseDouble(number1.replace(',', '.'));
tvNumber.setText(decimalFormat.format(a));
delete = true;
} catch (Exception e) {
e.printStackTrace();
}
}
private void addComma(){
if (comma) {
//do nothing
} else {
number1 += ",";
tvNumber.setText(number1);
comma = true;
}
}
The simplest solution would be to just tvNumber.setText(number1); directly without the back-and-forth conversion while editing and display it in the proper format only after the editing is done.
Another possibility would be to artificially append a digit before the conversion if the number contains a decimal point and then remove it afterwards.
String res = number1.replace(',', '.'); // shouldn't this be decimalFormat dependent ?
if( number1.contains(".") ) {
res = decimalFormat.format( Double.parseDouble(res+"5"));
res = res.substring(0,res.length()-1);
} else {
res = decimalFormat.format( Double.parseDouble(res) );
}

JTextfield Validation for numbers?

I am trying to validate my roll no (input of integer value) from JTextField. Well my code is compiling but while running it is giving me an error NumberFormatException.
Here is my validation code
public int rno_vd() {
int a=0,b=0,c=0,x=0,y=0;
int vrno =Integer.parseInt(txtRno.getText());
String r = String.valueOf(vrno);
if (r.isEmpty()) {
JOptionPane.showMessageDialog(null,"rno should not be empty");
a=1;
}
else if (Pattern.matches("[a-zA-Z]+",r)) {
JOptionPane.showMessageDialog(null,"rno should be in digits");
b=1;
}
else if (vrno < 0) {
JOptionPane.showMessageDialog(null,"rno cannot be negative");
c=1;
}
System.out.println(a + b + c);
if (a==1 || b==1 || c==1) {
x=1;
return x;
}
else {
y=0;
return y;
}
}
error
C:\Users\Hp\Desktop\jproject>javac -cp hibernatejar\* *.java
Note: DBHandler.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
C:\Users\Hp\Desktop\jproject>java -cp hibernatejar\*;. Sms
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at AddFrame.lambda$new$1(AddFrame.java:80)
at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1967)
at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2308)
at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
It is getting NumberFormatException, when text field has empty value.
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
Could you please try to validate the text first, and then parse the string?
// Validating text input first
String r = txtRno.getText();
if (r.isEmpty())
{JOptionPane.showMessageDialog(null,"rno should not be empty");
a=1;}
else if (Pattern.matches("[a-zA-Z]+",r))
{JOptionPane.showMessageDialog(null,"rno should be in digits");
b=1;}
else if (vrno < 0)
{JOptionPane.showMessageDialog(null,"rno cannot be negative");
c=1;}
// Converting to int, if validation is successful
int vrno =Integer.parseInt(txtRno.getText());
Komal here as I can see you want to validate JTextField for roll numbers ie should only contain integers, any other character instead of numbers should not be accepted...
Well, I suggest you to try validating on every keyReleased using KeyListener of KeyEvent.
Every key you press is validated if its number its good to go if its not it will show Dialog box saying "only numbers accepted".
I am sharing my code I hope it might help
//********function to check if value is numric or not*********
public static boolean isNumeric(String str) {
try {
Integer.parseInt(str);
return true;
}
catch(NumberFormatException e){
return false;
}
}
//************************function ends******************************
//txtRno is my JTextField
txtRno.addKeyListener(new KeyListener(){
public void keyPressed(KeyEvent e)
{
//code
}
public void keyReleased(KeyEvent e)
{
String value = txtRno.getText();
int l = value.length();
if(!isNumeric(value) && l>0){//if not numric it will not allow you to edit JTextField and show error message
txtRno.setEditable(true);
JOptionPane.showMessageDialog(c,"You need to enter number","ERROR",JOptionPane.ERROR_MESSAGE);
txtRno.requestFocus();
txtRno.setText("");
txtRno.setEditable(true);
lblError.setText("");
}
else { //else it will take the input as it already number or integer
txtRno.setEditable(true);
lblError.setText("");
}
}
public void keyTyped(KeyEvent e)
{
//code
}
});

how to compare a Double Value in if statement in java?

I have a desktop application with textboxs that contain a price values. As an example if i input 25000
Double priceSec = Double.parseDouble(cusPrice.getText());
i'm passing that 25000 as a double value
so now i want to compare that value and check whether it is empty or not?
if(cusPrice2.getText()==null || cusPrice2.getText().isEmpty()){
Double priceSec=0.0;
}
i know i can create an else condition for
if textbox !=null
total=txtbox1+txtbox2+txtbox3;
if textbox value is empty or not empty. value should be there in total.
but in my code ,it displays as null.
Do i have any other way to do that?
can you tell me a way to do that.
here is my full code
private void cusOkBtnActionPerformed(java.awt.event.ActionEvent evt) {
Double priceSec = Double.parseDouble(cusPrice2.getText());
Double priceThird = Double.parseDouble(cusPrice3.getText());
Double priceFourth = Double.parseDouble(cusPrice4.getText());
Double priceFifth = Double.parseDouble(cusPrice5.getText());
if(cusPrice2.getText()==null || cusPrice2.getText().isEmpty() || cusPrice2.getText() !=null ){
priceSec=0.0;
costCls.setItemPrice(priceSec);
}
else if(cusPrice3.getText()==null || cusPrice3.getText().isEmpty()){
priceThird=0.0;
}
else if(cusPrice4.getText()==null || cusPrice4.getText().isEmpty()){
priceFourth=0.0;
}
else if(cusPrice5.getText()==null || cusPrice5.getText().isEmpty()){
priceFifth=0.0;
}
Double setItemTotal = priceCus+priceSec+priceThird+priceFourth+priceFifth;
}
You should rather use Exceptions.
try {
Double priceSec = Double.parseDouble(cusPrice.getText());
} catch (NullPointerException e1) {
//null somewhere
} catch (NumberFormatException e2) {
//not a number - on controlled input - empty field.
}
double is the primitive type for floating point, Double is the Object child that wraps a double value. So:
double priceSec = Double.parseDouble(cusPrice.getText());
double price2Sec = cusPrice2.getText().isEmpty())
? 0.0
: Double.parseDouble(cusPrice.getText());
if (priceSec == price2Sec) { ...
However for financial data a double has small approximation errors, that can become visible - especially with ==. Hence one might better use BigDecimal, which does fixed point arithmetic.
BigDecimal priceSec = new BigDecimal(cusPrice.getText());
if (priceSec.compareTo(price2Sec) == 0) { ...
With a bit ugly API doing calculations:
x = x.add(y.divide(new BigDecimal("12.50")));
you can try this
private void cusOkBtnActionPerformed(java.awt.event.ActionEvent evt) {
Double priceSec=0.0,priceThird=0.0,priceFourth=0.0,priceFifth=0.0;
costCls.setItemPrice(0.0);
if(cusPrice2.getText()!=null && !cusPrice2.getText().isEmpty() ){
priceSec = Double.parseDouble(cusPrice2.getText());
costCls.setItemPrice(priceSec);
}
else if(cusPrice3.getText()!=null && !cusPrice3.getText().isEmpty()){
priceThird = Double.parseDouble(cusPrice3.getText());
}
else if(cusPrice4.getText()!=null && !cusPrice4.getText().isEmpty()){
priceFourth = Double.parseDouble(cusPrice4.getText());
}
else if(cusPrice5.getText()!=null && !cusPrice5.getText().isEmpty()){
priceFifth = Double.parseDouble(cusPrice5.getText());
}
Double setItemTotal = priceCus+priceSec+priceThird+priceFourth+priceFifth;
}
It is better to use the built-in Exception semantics already available within the Double.parseDouble(String s) implementation. (IMHO: Don't check up-front as you are making the exceptional-situation part of the normal flow)
Use a function like
private static double getValue(String str) {
try {
return Double.parseDouble(str);
} catch (NumberFormatException e) {
return 0d;
}
}
You would then use it like:
String priceStr = cusPrice.getText();
double d = getValue(priceStr);

How would I get a specific number range from a textfield?

I'm currently working on a search method in school and I'm stuck in a newbie mistake.
I havent been programming for long and I tried searching the internet for solutions but couldnt find any. I would need to get a number range from 1-10 from the textfield and then put it as an int. Once I've done that I would have to send it to my search method which I am working on. Thanks in advance peeps.
String Value = txfSort.getText();
int NumberValue = Integer.valueOf(Value);
Probably you should first limit the input of textFields to nummeric values. You can help your self with question here: What is the recommended way to make a numeric TextField in JavaFX?
public class NumberTextField extends TextField
{
#Override
public void replaceText(int start, int end, String text)
{
if (validate(text))
{
super.replaceText(start, end, text);
}
}
#Override
public void replaceSelection(String text)
{
if (validate(text))
{
super.replaceSelection(text);
}
}
private boolean validate(String text)
{
return text.matches("[0-9]*");
}
}
Code by: Burkhard
Above code would automaticly check on entry if input is ok. So then you just check, if value is > 0 and < 10. If that is true you just call your method and use value of textField.
One way of doing described would be this:
int value = Integer.valueOf(txfSort.getText());
if(value > 0 && value < 10)
{
myMethod(value);
}
try that one:
textField.addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent e) {
char caracter = e.getKeyChar();
if (((caracter < '0') || (caracter > '9')) // for numbers only
&& (caracter != '\b')) {
e.consume();
}
if (Integer.valueOf(textField.getText() + caracter) > 10) {
e.consume(); // if on the text field the numbers are bigger
// than 10, consumes the last number typed
}
}
});

Getting text from a Textview and adding it to an ArrayList?

So here's my problem its been bugging me for a while but when I try to get the text from a textview (custom number picker) and add it as an array value, the array won't let me input the textview value (sonyR).
Custom number picker widget :
#Override
public void onClick(View v) {
String getString = String.valueOf(tvSony.getText());
int current1 = Integer.parseInt(getString);
if (v == btnUp1) {
if (current1 < nEnd) {
current1++;
tvSony.setText(String.valueOf(current1));
}
}
if (v == btnDown1) {
if (current1 > nStart) {
current1--;
tvSony.setText(String.valueOf(current1));
}
}
sonyR = current1;
Log.i("sonyR ouput =", String.valueOf(sonyR));
Array, if value has been entered before, find the value and display it. if not make a new array value
private void sun32() {
ArrayList<Integer> sun32A = new ArrayList<Integer>();
if (sun32A.contains(sonyR)) {
sun32A.get(Integer.valueOf(sonyR));
tvSony.setText(sonyR);
} else {
tvSony.getText(Integer.valueOf(sonyR));<-----here is the error
sun32A.add(sonyR);
}
return;
}
EDIT : Just to confirm here is an image of the UI layout
One problem in your posted code is that getText() shouldn't take any arguments.
Also, TextView.getText() returns a CharSequence, not a String. You should convert it by doing toString() before calling Integer.valueOf(). Try this code and see if it works:
ArrayList<Integer> sun32A = new ArrayList<Integer>(); <---- Variable moved to outside of method.
private void sun32() {
if (sun32A.contains(sonyR)) {
// removed irrelevant code line
tvSony.setText(String.valueOf(sonyR)); <----- Convert the int to String before setting text.
} else {
int myInt = Integer.valueOf(tvSony.getText().toString()); <----- fixed code
sun32A.add(myInt);
}
return;
}

Categories

Resources