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

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();
}

Related

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

My app has unfortunately stopped [closed]

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());
}
}
});`

Java Parse Exception to Custom Exception

I'm new to Java and my problem here is a Simple Age Calculator. Here is my Code:
public class Client {
public int findAge(String birthDate) throws InvalidDateFormatException {
// InvalidDateFormatException is a custom defined
int age = 0;
try {
Calendar past = new GregorianCalendar();
Calendar present = Calendar.getInstance();
past.setTime(new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH).parse(birthDate));
age = present.get(Calendar.YEAR) - past.get(Calendar.YEAR);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (age >= 0) ? age : 0;
}
In main,
try {
System.out.println(c.findAge("08-09-1015"));
} catch (InvalidDateFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Now, this is throwing a ParseException every time i pass a String in the wrong Format. Is there any way in which I can make it throw an InvalidDateFormatException Exception instead?
Also, please leave a comment on the style and quality of my Code, provided I'm following the correct coding standards and adhering to best practices.
To answer your prime question, you need to throw the custom exception in the catch block:
try {
Calendar past = new GregorianCalendar();
Calendar present = Calendar.getInstance();
past.setTime(new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH).parse(birthDate));
age = present.get(Calendar.YEAR) - past.get(Calendar.YEAR);
} catch (ParseException e) {
throw new InvalidDateFormatException("invalid date: " + birthDate);
}
Regarding your code, I have a couple of suggestions:
Do not use new GregorianCalendar() and prefer Calendar.getInstance().
The way you calculate the age is broken: you don't take into account the month and the day (let's say we are 2015-09-20, and the birth date is 2014-12-01, your code will output 1 even if the baby is not 1 year old yet).
Consider giving a Date argument instead of a String argument. It should not be the responsibility of the findAge method to parse the birth date.
If you are using Java 8, consider using the new Java Time API.
Define Custom Exception class for InvalidDateFormatException as below:
public class InvalidDateFormatException extends RuntimeException {
private String errorMessage;
public InvalidDateFormatException(String errorMessage, Exception exe) {
super(errorMessage);
exe.printStackTrace();
}
}
Modify your catch block to throw the exception as below :
public class Client {
public int findAge(String birthDate) throws InvalidDateFormatException {
int age = 0;
try {
Calendar past = new GregorianCalendar();
Calendar present = Calendar.getInstance();
past.setTime(new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH).parse(birthDate));
age = present.get(Calendar.YEAR) - past.get(Calendar.YEAR);
} catch (ParseException e) {
throw new InvalidDateFormatException("Invalid Date Format while finding Age", e);
}
return (age >= 0) ? age : 0;
}
}
Also, I would suggest you go through the below site:
https://docs.oracle.com/javase/tutorial/essential/exceptions/creating.html

Android - Try Catch is not catching the exception and it's not displaying my toast message

I'm new to Android programming and taking a Coursera class. In my assignment app, I'm trying to catch any exceptions when the user does not enter or enters incorrect time information (HH:MM:SS).
My app crashes right after user error instead of displaying my Toast message or displaying a Log message to Logcat.
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
try {
Date dt = formatter.parse(MileTime);
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int hours = cal.get(Calendar.HOUR);
int minutes = cal.get(Calendar.MINUTE);
int seconds = cal.get(Calendar.SECOND);
int duration = 3600 * hours + 60 * minutes + seconds;
int steps_per_second = 3;
int running_rate = duration * steps_per_second;
//pleaseStop = false; //DouglasZare example, don't need this.
mHandler = new Handler(); // .os package class when importing
mLeftfoot = findViewById(R.id.leftfoot);
mRightfoot = findViewById(R.id.rightfoot);
mFootAnim = AnimationUtils.loadAnimation(this, R.anim.foot); //this looks to the foot.xml file for the animations
stepRecursive();
} catch (ParseException e) {
e.printStackTrace();
Log.e(TAG, "Invalid Mile Time Entry", e);
Toast.makeText(Assignment3MainActivity_V3_DouglasZare_AnimationCancel.this,
"Please Enter Valid Time Stamp HH:MM:SS", Toast.LENGTH_LONG).show();
}
The error log is here: http://pastebin.com/By7FWxLk.
This error makes perfect sense and is intentional.
Caused by: java.text.ParseException: Unparseable date: ""
What do I fix to get my catch statement to prevent this?
Fixed. Ugh. I changed ParseException to just Exception. It doesn't make any sense to me...The Exception I want to catch IS ParseException.
catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "Invalid Mile Time Entry", e);
Toast.makeText(Assignment3MainActivity_V3_DouglasZare_AnimationCancel.this,
"Please Enter Valid Time Stamp HH:MM:SS", Toast.LENGTH_LONG).show();
}
The reason is the exception being thrown is IllegalStateException not ParseException.
If you look at line 5 of your crash log, you'll see the exception that gets passed up to you is an IllegalStateException. This is because the ParseException is caught and then an IllegalStateException is re-thrown afterwards.
Here's an example of multiple catch blocks.
try {
//some code that can throw an exception
} catch (IllegalStateException e) {
//catch the IllegalStateExeption
} catch (Exception e) {
//catch all the ones I didn't think of.
}

increment date of data that filtered from the text file

public class Reader {
public static void main(String[] args) throws IOException, ParseException {
BufferedReader reader;
String animalName="cat";
String animal = null;
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream("C:/dila.txt")));
Map<String, Integer> result = new LinkedHashMap<String, Integer>();
Map<String, Integer> result2 = new LinkedHashMap<String, Integer>();
while (reader.ready()) {
String line = reader.readLine();
/split a line with spaces/
String[] values = line.split(",");
String key = null;
if(values[1].compareTo(animalName)==0){
key = values[0];
animal=""+values[1].compareTo(animalName);
int sum = 0;
int count = 0;
/get a last counter and sum/
if (result.containsKey(key)) {
sum = result.get(key);
count = result2.get(key);
} else{
}
/increment sum a count and save in the map with key/
result.put(key, sum + Integer.parseInt(values[2]));
result2.put(key, count + 1);
}
}
/interate and print new output/
for (String key : result.keySet()) {
Integer sum = result.get(key);
Integer count = result2.get(key);
System.out.println(key +" "+animalName+ " " + sum + "\t" + count);
}
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
i have below text file
11/2/2010,cat,6
11/2/2010,cat,3
11/2/2010,dog,4
11/2/2010,cat,11
11/3/2010,cat,1
11/3/2010,dog,3
11/3/2010,cat,8
11/3/2010,cat,80
in my java code it is filtered below output.
11/2/2010 cat 20 3
11/3/2010 cat 104 4
11/4/2010 cat 26 2
But i want below mention result.
11/01/2010
11/02/2010 cat 20 3
11/03/2010 cat 104 4
11/04/2010 cat 26 2
11/05/2010
11/06/2010
11/07/2010
11/08/2010
11/09/2010
11/10/2010
11/11/2010
11/12/2010
11/13/2010
11/14/2010
11/15/2010
11/16/2010
11/17/2010
11/18/2010
11/19/2010
11/20/2010
11/21/2010
11/22/2010
11/23/2010
11/24/2010
11/25/2010
11/26/2010
11/27/2010
11/28/2010
11/29/2010
11/30/2010
Above shows my java code...(i am new for this site thats why my question is little bit unclear to you. now i got the method. Now i again post my question. So please read this and give me the solution....)
Do this:
read the first line of txt file to get the month.
create a hashmap of size of the month. Populate it with java.util.date from 1st to the last of the dates in that month. Date as key and null as value.
read the text file, get the first of CSV in each line convert it to Date object
Do a lookup in Hashmap and insert the fomatted String as the value to corresponding date key. You can use Formatter for padding.
repeat #3 and #4 till EOF
Now, iterate in Hashmap and print out. For all the NULL values just print formatted Key (which is date)
Hope this helps.
1. use SimpleDateFormat to convert date String to date object
2. write a method that takes this date and returns maximum days in that month using java.util.Calendar.getMaximum
3. create a hashMap with Keys as Dates in that month and values as Null
4. now, read line by line and user SimpleDateFormat to convert first of CSV into date. Use this date as key and put the printable String as value.
5. Iterate throught this hashmap.keys() and to get the values one by one. If the value is null just print the key i.e. date.
:)
Can't help more.
Hope this method helps you in filling the keys.
public static String[] getDates(String date)
{
String[] dates=null;
SimpleDateFormat sdf=new SimpleDateFormat("MM/dd/yyyy");
try {
Date d=sdf.parse(date);
Calendar cal=GregorianCalendar.getInstance();
cal.setTime(d);
int month=cal.get(Calendar.MONTH);
int year=cal.get(Calendar.YEAR);
int startDate=cal.getActualMinimum(Calendar.DAY_OF_MONTH);
int endDate=cal.getActualMaximum(Calendar.DAY_OF_MONTH);
StringBuilder sb=new StringBuilder();
dates=new String[endDate];
for(int i=startDate;i<=endDate;i++)
{
sb=new StringBuilder();
sb.append(month+1);
sb.append("/");
sb.append(i);
sb.append("/");
sb.append(year);
dates[i-1]=sb.toString();
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dates;
}

Categories

Resources