My app has unfortunately stopped [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
This is my code
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
if (myswitch.isChecked()) {
editText.setHint("IDR");
editText1.setHint("USD");
double Rupiah = Double.valueOf(editText.getText().toString());
double convusd = Rupiah / 13698;
DecimalFormat dformat = new DecimalFormat("####,###,###.00");
editText1.setText(String.format("$" + dformat.format(convusd)));
} else {
editText.setHint("USD");
editText1.setHint("IDR");
double USD = Double.valueOf(editText.getText().toString());
double convidr = USD * 13698;
DecimalFormat dformat = new DecimalFormat("####,###,###.00");
editText1.setText(String.valueOf("Rp." + dformat.format(convidr)));
}
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
}
});`
My app has an error if the EditText is empty when I press the Button.

Your code has a few problems:
Why are you setting hints after the click and in the same event you try to convert to values? shouldn't the user first see the hint, enter the values and only then you convert the input?
When you attempt to convert the input, you should check if there is actually a value inside, e.g:
String inputVal = editText.getText();
if(inputVal != null && !inputVal.isEmpty())
{
//do some stuff
}
If there is a value, make sure it what you expect it to be.
Set your input type to your EditText:
android:inputType="numberDecimal"
and to be extra sure you should do somthing like this:
double d;
try {
d = Double.parseDouble(inputVal);
}
catch (NumberFormatException e) {
// The input is not what you thought it was, handle it
}

Change code as like below
String a=editText.getText().toString();
if(a!=null&&!a.isEmpty())
{
double Rupiah = Double.valueOf(a);
}

Add empty check When you click the button. you might be trying to convert empty string to double
if(!editText.getText().toString().isEmpty){
double Rupiah = Double.valueOf(editText.getText().toString());
...
}

button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
if (myswitch.isChecked()) {
editText.setHint("IDR");
editText1.setHint("USD");
double Rupiah = Double.valueOf(editText.getText() ==null ? "":editText.getText().toString());
double convusd = Rupiah / 13698;
DecimalFormat dformat = new DecimalFormat("####,###,###.00");
editText1.setText(String.format("$" + dformat.format(convusd)));
} else {
editText.setHint("USD");
editText1.setHint("IDR");
double USD = Double.valueOf(editText.getText() ==null ? "":editText.getText().toString());
double convidr = USD * 13698;
DecimalFormat dformat = new DecimalFormat("####,###,###.00");
editText1.setText(String.valueOf("Rp." + dformat.format(convidr)));
}
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
}
});`

Related

String data still remains? (Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string)

I am trying out to code a simple arithmetic game in Java but I faced an error like: Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string. This happens when I clicked on number buttons and cleared them to enter a new number but it seems that the string still contains the previous number I clicked. (For example, I clicked 5 and deleted it so I could enter 9 instead and now the string seems to register it as 59 instead of just 9.) I used .setText('') to clear the text area.
This is my code for when the buttons are pressed:
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("one"))
{
answerText.append("1");
userAnswer = userAnswer + "1";
}
// same code for two, three, four... to nine.
if(e.getActionCommand().equals("enter"))
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score++;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
}
The answer variable and delete button is :
answerText = new JTextArea();
answerText.setEditable(false);
clearbtn = new JButton("Clear");
clearbtn.setActionCommand("clear");
clearAnswer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
answerText.setText("");
}
});
How do I make sure that my answerText is completely clear?
Your error message:
java.lang.NumberFormatException: For input string
This means that you are trying to parse a string into a number, but the string contains something that cannot be parsed into a number. Java prints the content of the string after the text For input string. In this case there's nothing after that text, because the string that you are trying to parse is the empty string - that you set in the text box by calling answerText.setText("");
Solution: Check if the string you are trying to parse is empty before you try to parse it into a number. For example:
if (e.getActionCommand().equals("enter"))
{
if (!"".equals(userAnswer)) // Check if userAnswer is not empty
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score++;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
else
{
JOptionPane.showMessageDialog(this, "Please enter a number before pressing Enter.");
}
}
The variable userAnswer doesn't get cleared when answerText is cleared. This might cause issues.
The exception you are having is probably being cause because int userValue = new Integer(userAnswer); is called at a point where userAnswer is empty (because it can't make a number out of nothing).

Radio Button Unchecked mark didn't reduced using Java Mysql

I am creating a simple exam system in Java and Mysql. When I start the exam all the question displayed from the database successfully, if I read the question and answer it then click next button it will be moving to the next question. It is working fine. If the answer is clicked correctly marks added 1. unless unchecked the answer answer become 0 I want it. my problem is if I click correct answer on the radio button marks changes as one. The same question again I select as wrong answer it didn't changes 0, it still mark become 1. How to solve the problem I clear the radio buttons it won't clear. What I tried so far I attached below.
Click Correct answer . mark displayed 1 correctly
enter image description here
after that same question answer change as wrong answer. Mark displayed
1.I need to display if we select wrong answer second time marks become decrement. I need to change as 1 become 0
enter image description here
Code what tried so far I attached below.
Click the Answer
public void answercheck()
{
String studentanswer="";
if(r1.isSelected())
{
if(r1.isSelected() == true)
{
studentanswer = r1.getText();
r2.setSelected(false);
r3.setSelected(false);
r4.setSelected(false);
}
else
{
studentanswer="";
r1.setSelected(false);
r2.setSelected(true);
r3.setSelected(true);
r4.setSelected(true);
}
}
else if(r2.isSelected())
{
if(r2.isSelected() == true)
{
studentanswer = r2.getText();
r1.setSelected(false);
r3.setSelected(false);
r4.setSelected(false);
}
else
{
studentanswer="";
r2.setSelected(false);
r1.setSelected(true);
r3.setSelected(true);
r4.setSelected(true);
}
}
else if(r3.isSelected())
{
if(r3.isSelected() == true)
{
studentanswer = r3.getText();
r1.setSelected(false);
r2.setSelected(false);
r4.setSelected(false);
}
else
{
studentanswer="";
r3.setSelected(false);
r1.setSelected(true);
r2.setSelected(true);
r4.setSelected(true);
}
}
else if(r4.isSelected())
{
if(r4.isSelected() == true)
{
studentanswer = r4.getText();
r1.setSelected(false);
r2.setSelected(false);
r4.setSelected(false);
}
else
{
studentanswer="";
r4.setSelected(false);
r1.setSelected(true);
r2.setSelected(true);
r4.setSelected(true);
}
}
if(studentanswer.equals(answer))
{
marks = marks + 1;
String marks1 = String.valueOf(marks);
txtc.setText(marks1);
}
}
Load all question from the database
public void Connection()
{
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/onlineex","root","");
stat = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs = stat.executeQuery("select id,question,option1,option2,option3,option4,answer from questions order by id DESC");
while(rs.next())
{
txtqu.setText(rs.getString("id"));
txtques.setText(rs.getString("question"));
r1.setText(rs.getString(3));
r2.setText(rs.getString(4));
r3.setText(rs.getString(5));
r4.setText(rs.getString(6));
answer = rs.getString(7);
}
} catch (ClassNotFoundException ex) {
} catch (SQLException ex) {
}
}
Next Click Button
if(!rs.isFirst())
{
rs.previous();
txtqu.setText(rs.getString("id"));
txtques.setText(rs.getString("question"));
r1.setText(rs.getString(3));
r2.setText(rs.getString(4));
r3.setText(rs.getString(5));
r4.setText(rs.getString(6));
answer = rs.getString(7);
answercheck();
}
Previous Click Button
if(!rs.isLast())
{
rs.next();
txtqu.setText(rs.getString("id"));
txtques.setText(rs.getString("question"));
r1.setText(rs.getString(3));
r2.setText(rs.getString(4));
r3.setText(rs.getString(5));
r4.setText(rs.getString(6));
answer = rs.getString(7);
}

Get double value from currency frormatted string

I'm using NumberFormat in my app to get the currency formatted Strings. Like if a user inputs 12.25 in the field then it will be changed to $12.25 based on locale. Here the Locale is en-US.
Now I want to get the 12.25 value as double form the formatted string.
To do that I have used:
NumberFormat.getCurrencyInstance().parse("$12.25").doubleValue();
Above line giving me the result of 12.25 which is my requirement. But suppose a user changed his locale to something else en-UK. Now for that locale above statement is giving me parseException. Because for the locale en-UK, currency string $12.25 is not parsable.
So is there any way to get the double value from currency formatted string irrespective of what the locale is?
I don't know either the below solution is perfect or not but it is working according to my requirement.
try {
return NumberFormat.getCurrencyInstance().parse(currency).doubleValue();
} catch (ParseException e) {
e.printStackTrace();
// Currency string is not parsable
// might be different locale
String cleanString = currency.replaceAll("\\D", "");
try {
double money = Double.parseDouble(cleanString);
return money / 100;
} catch (Exception ex) {
ex.printStackTrace();
}
}
return 0;
What about
new Double(NumberFormat.getCurrencyInstance().parse("$12.25").doubleValue());
and also you could use
Double.valueOf() creates a Double object so .doubleValue() should not be necessary.
also Double.parseDouble(NumberFormat.getCurrencyInstance().parse("$12.25"));
could work
Here's a little algorithm that may help you :
public static void main(String[] args) {
String cash = "R$1,000.75"; //The loop below will work for ANY currency as long as it does not start with a digit
boolean continueLoop = true;
char[] cashArray = cash.toCharArray();
int cpt = 0;
while(continueLoop){
try
{
double d = Double.parseDouble(cashArray[cpt]+"");
continueLoop = false;
}catch(NumberFormatException nfe){
cpt += 1;
}
}
System.out.println(cpt);
//From here you can do whatever you want....
String extracted = cash.substring(cpt);
NumberFormat format = NumberFormat.getInstance(Locale.US); //YOUR REQUIREMENTS !!!! lol
try {
Number youValue = format.parse(extracted);
System.out.println(youValue.doubleValue());
} catch (ParseException ex) {
//handle your parse error here
}
}
You should get as result here in the output:
2
1000.75

How to convert %02d:%02d:%02d in to double?

I am setting time on a TextView using
Min_txtvw.setText(String.format(mTimeFormat, hour, min, sec));
Now
average=distance*60*60/seconds // my function for finding average
for seconds i have to get time from Min_txtvw
I done it like below but it gives NumberformatException,
try {
String s = Min_txtvw.getText().toString();
double d = Double.valueOf(s.trim()).doubleValue();
System.out.println("average distance is"+d);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
How i convert that TextView value and convert it in double ?
You are getting NumberformatException because your variable S contains ":" String value, you need to replace those values by using replaceAll() method.
Try following way,
try {
String s = Min_txtvw.getText().toString();
s.replaceAll ( ":","" );
double d = Double.valueOf(s.trim()).doubleValue();
System.out.println("average distance is"+d);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}

Creating multiple identical text verify listeners in eclipse-rcp/swt

I'm trying to validate the input of multiple text boxes (i.e. they should be a number), and found the useful code snippet below here.
However, if I have three text boxes (text, moreText and evenMoreText), how can I apply a verify listener with the same functionality to each, without having to repeat the (.addVerifyListener(new VerifyListener() {...) code three times?
I don't want to implement a switch statement or similar (to decide which text box to apply it to), I want something more generic (that I can perhaps make available for other classes to use in the future).
text.addVerifyListener(new VerifyListener() {
#Override
public void verifyText(VerifyEvent e) {
final String oldS = text.getText();
final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
try {
BigDecimal bd = new BigDecimal(newS);
// value is decimal
// Test value range
} catch (final NumberFormatException numberFormatException) {
// value is not decimal
e.doit = false;
}
}
});
Define the VerifyListener beforehand and get the actual Text from the VerifyEvent:
VerifyListener listener = new VerifyListener()
{
#Override
public void verifyText(VerifyEvent e)
{
// Get the source widget
Text source = (Text) e.getSource();
// Get the text
final String oldS = source.getText();
final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
try
{
BigDecimal bd = new BigDecimal(newS);
// value is decimal
// Test value range
}
catch (final NumberFormatException numberFormatException)
{
// value is not decimal
e.doit = false;
}
}
};
// Add listener to both texts
text.addVerifyListener(listener);
anotherText.addVerifyListener(listener);
If you want to use it in other places as well, create a new class:
public class MyVerifyListener implements VerifyListener
{
// The above code in here
}
and then use:
MyVerifyListener listener = new MyVerifyListener();
text.addVerifyListener(listener);
anotherText.addVerifyListener(listener);

Categories

Resources