Now,I have a string String time= "200hour 0minute 0second"
I want to track numbers in string and convert to second..As above string..I want to get value 200*3600..
My code:
//change from hour minute to second
public String changeSecond(String time)
{
String result;
int ind_hour=time.indexOf("hour");
int ind_minute=time.indexOf("minute");
int ind_second=time.indexOf("second");
int hour=Integer.parseInt(time.substring(0, ind_hour));
int minute=Integer.parseInt(time.substring(ind_hour+1, ind_minute));;
int second=Integer.parseInt(time.substring(ind_minute+1, ind_second));
result=String.valueOf(hour*3600+minute*60+second);
return result;
}
but when i run changeSecond(time).It don't work..How must I do.
public String changeSecond(String time)
{
String result;
int ind_hour=time.indexOf("hour");
int ind_minute=time.indexOf("minute");
int ind_second=time.indexOf("second");
int hour=Integer.parseInt(time.substring(0, ind_hour));
int minute=Integer.parseInt(time.substring(ind_hour+6, ind_minute));; // value 6 is length of minute
int second=Integer.parseInt(time.substring(ind_minute+6, ind_second));
int totalsec=((hour*60*60)+(minute*60)+second);
result=String.valueOf(totalsec);
return result;
}
You should make changes to the following lines:
int hour=Integer.parseInt(time.substring(0, ind_hour));
int minute=Integer.parseInt(time.substring(ind_hour+5, ind_minute));
int second=Integer.parseInt(time.substring(ind_minute+7, ind_second));
Its not the way to do it.But It will work.Try this,
String hour="200hour 0minute 0second";
String[] secondarray=hour.split("hour");
String second=secondarray[0]; //here "second" will have the value 200
You can split the tab into 3 parts : One will contains the hours, another the minutes and the last one the seconds.
public static String changeSecond(String time)
{
String tab[] = time.split(" ");
String result = "";
int ind_hour=tab[0].indexOf("hour");
int ind_minute=tab[1].indexOf("minute");
int ind_second=tab[2].indexOf("second");
int hour=Integer.parseInt(tab[0].substring(0, ind_hour));
int minute=Integer.parseInt(tab[1].substring(0, ind_minute));
int second=Integer.parseInt(tab[2].substring(0, ind_second));
result=String.valueOf(hour*3600+minute*60+second);
return result;
}
This is the cleanest solution I could come up with. Just split on " " then remove the text that's irrelevant.
public String changeSecond(final String time)
{
final String[] times = time.split(" ");
final int hour = Integer.parseInt(times[0].replace("hour", ""));
final int minute = Integer.parseInt(times[1].replace("minute", ""));
final int second = Integer.parseInt(times[2].replace("second", ""));
return String.valueOf(hour*3600+minute*60+second);
}
The initial code was throwing parsing errors since alpha characters were being passed to the Integer.parseInt method. The alpha characters were being included because the substring did not take into account the length of the terms hour, minute and second. I would recommend splitting the string to tidy things up.
public String changeSecond(String time) {
String[] tokens = time.split(" ");
tokens[0] = tokens[0].substring(0, tokens[0].indexOf("hour"));
tokens[1] = tokens[1].substring(0, tokens[1].indexOf("minute"));
tokens[2] = tokens[2].substring(0, tokens[2].indexOf("second"));
return String.valueOf(Integer.parseInt(tokens[0]) * 3600
+ Integer.parseInt(tokens[1]) * 60 + Integer.parseInt(tokens[2]));
}
Update your hours,minutes and seconds parsing as:
int hour=Integer.parseInt(time.substring(0, ind_hour));
int minute=Integer.parseInt(time.substring(ind_hour + "hour".length() + 1, ind_minute));
int second=Integer.parseInt(time.substring(ind_minute + "minute".length() + 1, ind_second));
Related
I am still relatively new to java but the problem that I am facing right now is that I keep getting a compile time error with what I currently have.
I'm not sure if there's a special logic structure that would take existing values from the file and convert the format of the numbers.
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.time.Duration;
public class Music {
// Method header
public static void main(String [] args) throws IOException{
// Variable declarations
String id;
String artistName;
String title;
String releaseName;
int year;
double endOfFadeIn;
double startOfFadeOut;
double loudness;
double duration;
// Scanner to read input from the user
Scanner keyboard = new Scanner(System.in);
// Scanner to read in the file that the user types.
System.out.print("Enter the name of the file: ");
String filename = keyboard.nextLine();
File inFile = new File(filename);
Scanner fileScan = new Scanner(inFile);
fileScan.useDelimiter(",|\\r?\\n");
fileScan.nextLine();
// Read from file using Scanner
while(fileScan.hasNext()) {
id = fileScan.next();
System.out.println(id);
id = formatID(id);
System.out.println(id);
artistName = fileScan.next();
System.out.println(artistName);
artistName = truncate(artistName);
title = fileScan.next();
System.out.println(title);
title = truncate(title);
releaseName = fileScan.next();
System.out.println(releaseName);
releaseName = truncate(releaseName);
year = fileScan.nextInt();
System.out.println(year);
endOfFadeIn = fileScan.nextDouble();
System.out.println(endOfFadeIn);
startOfFadeOut = fileScan.nextDouble();
System.out.println(startOfFadeOut);
loudness = fileScan.nextDouble();
System.out.println(loudness);
System.out.printf("%-10s %-20s %-20s %-20s%n", id, artistName, title,
releaseName);
}
}// end main
public static String formatID(String id) {
String newid;
newid = id.substring(0,7) + "-" + id.substring(7,9) + "-" + id.substring(9,18);
return newid;
}//end formatID
public static String truncate(String str){
if (str.length() > 20) {
return str.substring(0, 20-3) + "...";
} else {
return str;
}
}//end truncateStr
public static String formatTime(double duration) {
int days=0;
int hours=0;
int minutes=0;
int seconds=0;
String Result;
Result = System.out.printf("%03s:%02s:%02s:%02s", days, hours, minutes, seconds);
string.format
System.out.printf("%03s:%02s:%02s:%02s", days, hours, minutes, seconds);
duration = (int) duration;
duration = (startOfFadeOut - endOfFadeIn);
duration = Math.round(duration);
}//end formatTime
}//end class
The expected result is that when the values are read in from the file the output will display the time in this format DD:HH:MM:SS.
You didn't specify what the compile-time error was or which line of your code was causing it, but since you posted a MRE, I just needed to copy your code in order to discover what it was. It is this line:
String Result;
Result = System.out.printf("%03s:%02s:%02s:%02s", days, hours, minutes, seconds);
Method printf returns a PrintStream and not a String. If you want a String, use method format
So your code should be...
String Result;
Result = String.format("%03s:%02s:%02s:%02s", days, hours, minutes, seconds);
System.out.printf(Result);
Also, according to java coding conventions, variable names - like Result - should start with a lower-case letter, i.e. result.
public class CalendarUtil
{
private Calendar cal = null;
public String getRemId()
{
cal = Calendar.getInstance();
return "" + cal.get(Calendar.DATE) + (cal.get(Calendar.MONTH)+1) + cal.get(Calendar.YEAR);
}
}
How can we auto generate ID on a button click that will contain the concatenation of date,month,year and a 3 digit counter starting form 000 and display it in a textfield? for eg:- 28122012001, 28122012002, etc and so on. Code that i have been trying is as above
I think two static fieds can do it.
private static String lastUsedDatePrefix;
private static int counter;
If you want to nenerate a new ID, check if the dateprefix is the same as stored in lastUsedDatePrefix if yes, increment counter else set counter=0 and set lastUsedDatePrefixto actual date.
Untested implementation:
public class CalendarUtil{
private static String lastUsedDatePrefix = "";
private static int counter = 0;
public String getRemId(){
final String datePrefix = new SimpleDateFormat("ddMMyyy").format(new Date());
if (lastUsedDatePrefix.equals(datePrefix)) {
CalendarUtil.counter++;
}
else{
CalendarUtil.lastUsedDatePrefix = datePrefix;
CalendarUtil.counter = 0;
}
final String counterSuffix = ((100 <= CalendarUtil.counter) ? ""
: (10 <= CalendarUtil.counter) ? "0" : "00")
+ CalendarUtil.counter;
return datePrefix + counterSuffix;
}
}
All-
I have a TextWatcher that formats an EditText to currency format:
private String current = "";
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(!s.toString().equals(current)){
editText$.removeTextChangedListener(this);
String cleanString = s.toString().replaceAll("[$,.]", "");
double parsed = Double.parseDouble(cleanString);
String formated = NumberFormat.getCurrencyInstance().format((parsed/100));
current = formated;
editText$.setText(formated);
editText$.setSelection(formated.length());
editText$.addTextChangedListener(this);
}
}
This works great, the problem is that my EditText only needs whole numbers so I do not the user to be able to enter cents. So instead of 0.01 than 0.12 than 1.23 than 12.34, I want 1 than 12 than 123 than 1,234. How can I get rid of the decimal point but keep the commas? Thank you.
If you don't mind removing the period and trailing zeroes, you could do this:
mEditText.addTextChangedListener(new TextWatcher() {
private String current = "";
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().equals(current)) {
annualIncomeEntry.removeTextChangedListener(this);
String cleanString = s.toString().replaceAll("[$,]", "");
if (cleanString.length() > 0) {
double parsed = Double.parseDouble(cleanString);
NumberFormat formatter = NumberFormat.getCurrencyInstance();
formatter.setMaximumFractionDigits(0);
current = formatter.format(parsed);
} else {
current = cleanString;
}
annualIncomeEntry.setText(current);
annualIncomeEntry.setSelection(current.length());
annualIncomeEntry.addTextChangedListener(this);
}
}
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
});
This will set the number formatter's maximum fraction digits to zero, removing all trailing zeroes and the period. I also removed the division by 100 so that all entered numbers are integers.
Also make sure that your EditText's inputType is "number" or this will crash if the user tries to enter a non-numeric character.
Hexar's answer was useful but it lacked error detection when the user deleted all the numbers or moved the cursor. I built on to his answer and an answer here to form a complete solution. It may not be best practice due to setting the EditText in the onTextChanged() method but it works.
/* don't allow user to move cursor while entering price */
mEditText.setMovementMethod(null);
mEditText.addTextChangedListener(new TextWatcher() {
private String current = "";
NumberFormat formatter = NumberFormat.getCurrencyInstance();
private double parsed;
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().equals(current)) {
/* remove listener to prevent stack overflow from infinite loop */
mEditText.removeTextChangedListener(this);
String cleanString = s.toString().replaceAll("[$,]", "");
try {
parsed = Double.parseDouble(cleanString);
}
catch(java.lang.NumberFormatException e) {
parsed = 0;
}
formatter.setMaximumFractionDigits(0);
String formatted = formatter.format(parsed);
current = formatted;
mEditText.setText(formatted);
/* add listener back */
mEditText.addTextChangedListener(this);
/* print a toast when limit is reached... see xml below.
* this is for 6 chars */
if (start == 7) {
Toast toast = Toast.makeText(getApplicationContext(),
"Maximum Limit Reached", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
}
A quick way to ensure the user doesn't enter invalid information is to edit the xml. For my program, a limit of 6 number characters was set.
<!-- it says maxLength 8 but it's really 6 digits and a '$' and a ',' -->
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number|textVisiblePassword"
android:maxLength="8"
android:digits="0123456789"
android:id="#+id/mEditText"
android:hint="Price"/>
Why don't you format the amount using currencyFormat and then take out the .00 from the String.
private static final ThreadLocal<NumberFormat> currencyFormat = new ThreadLocal<NumberFormat>() {
#Override
protected NumberFormat initialValue() {
return NumberFormat.getCurrencyInstance();
}
};
currencyFormat.get().format( < your_amount_here > )
etProductCost.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().length() == 1){
//first number inserted.
if (s.toString().equals(getString(R.string.currency_symbol))){
//if it is a currecy symbol
etProductCost.setText("");
}else {
etProductCost.setText(getString(R.string.currency_symbol) + s.toString());
etProductCost.setSelection(s.toString().length());
}
return;
}
//set cursor position to last in edittext
etProductCost.setSelection(s.toString().length());
}
#Override
public void afterTextChanged(Editable s) {}
});
Code:
Iterator<String> termIncomeKeys = termIncome.keySet().iterator();
while(termIncomeKeys.hasNext()){
String month = termIncomeKeys.next();
System.out.println(month);
}
The month is printed as
Jan(2012) - Jan(2012)
Feb(2012) - Mar(2012)
Apr(2012) - May(2012)
Jun(2012) - Jun(2012)
Jul(2012) - Oct(2012)
What I want to achieve is I want to print the duration in terms of months between each of the entries. That is, Duration between first entry is 1 month, duration between second is 2 and so on.
I do not know if there is a ready-made class that could parse these strings for you, but the logic is simple:
convert the three-letter months to numbers (e.g. 0-11), and convert the years to numbers as well.
The difference is <year-diff>*12 + <month-diff>, where <month-diff> might be negative.
Assuming Same Year:
enum Month{
JAN(0),
FEB(1),
MAR(2),
APR(3),
....
DEC(11);
Month(int index){this.index = index;}
int index;
int getIndex() {return index;}
}
Iterator<String> termIncomeKeys = termIncome.keySet().iterator();
while(termIncomeKeys.hasNext()){
String month = termIncomeKeys.next();
String str[] = month.split("-");
String m0 = str[0], m1 = str[1];
String y0 = mo.substr(m0.indexOf('(')+1, mo.lastIndexOf(')'));
String y1 = m1.substr(m1.indexOf('(')+1, m1.lastIndexOf(')'));
int yr0 = Integer.parseInt(yo), yr1 = Integer.parseInt(y1);
m0 = m0.substr(0, mo.indexOf('(')).trim().toUpperCase();
m1 = m1.substr(0, m1.indexOf('(')).trim(),toUpperCase();
int duration = yr1 *Month.valueOf(m1).getIndex() - yr0 *Month.valueOf(m0).getIndex();
}
I have an string array that includes some minutes like "00:05", "00:30", "00:25" etc. I want to sum the values as time format? Can anyone help me how do I do this?
Total time in minutes:
int sum = 0;
final String[] mins = new String[] { "00:05", "00:30", "00:25" };
for (String str : mins) {
String[] parts = str.split(":");
sum += Integer.parseInt(parts[1]);
}
System.out.println(sum);
You don't specify exactly how you want this output formatted.
If there may be hour elements as well, then replace the second line of the loop with this:
sum += (Integer.parseInt(parts[0]) * 60) + Integer.parseInt(parts[1]);
I'll go for quick and dirty
Split each String on the ":"
Convert both parts to integer
Multiply the first time by 60 to convert hours to minutes, and add the second part
Do this for each value in your array, and count them together
This results in the total time in minutes, which you can convert to whatever format you like
You could substring it, and then call Integer.parseInt on the result. For the hours part, do the same and multiply it by 60.
Split the strings on ':', pars the values as ints and add 'em up.
this is my suggestion. Neither compiled, ran, tested, nor guaranteed.
long seconds = 0;
for ( String min : minutes )
{
seconds += Integer.parseInt(min.substring(0,1))*60 + Integer.parseInt(min.substring(3,4));
}
return new Date ( seconds / 1000 ) ;
An object oriented approach:
public static TimeAcumm sum(final String[] times) {
final TimeAcumm c = new TimeAcumm();
for (final String time : times) {
c.incrementFromFormattedString(time);
}
return c;
}
public class TimeAcumm {
private int hours = 0;
private int minutes = 0;
private int seconds = 0;
public int getHours() {
return hours;
}
public int getMinutes() {
return minutes;
}
public int getSeconds() {
return seconds;
}
public void incrementFromFormattedString(final String time) {
final String[] parts = time.split(":");
this.minutes += Integer.parseInt(parts[0]);
this.seconds += Integer.parseInt(parts[1]);
validate();
}
private void validate() {
if (this.minutes > 59) {
this.hours++;
this.minutes -= 60;
}
if (this.seconds > 59) {
this.minutes++;
this.seconds -= 60;
}
}
#Override
public String toString() {
final String s = hours + "H:" + minutes + "M:" + seconds + "S";
return s;
}
}