I want make to make hours and minutes arrays which for 19:49 should contain
hours[0] = 1
hours[1] = 9
minutes[0] = 4
minutes[1] = 9
Problem is that when I execute code:
Calendar rightNow = Calendar.getInstance();
String hour[] = String.valueOf(rightNow.get(Calendar.HOUR_OF_DAY)).split("");
String minute[] = String.valueOf(rightNow.get(Calendar.MINUTE)).split("");
and when I print this
System.out.println(hour[0] + ""+hour[1] + ":" + minute[0] +""+minute[1]);
I have this output 1:4, but it should be 19:49
Update: I am using 1.7 JDK and form what I see hour[2] contains 9 and minute[2] 9.
Problem in pre-Java-8 is that when we split(delimiter) string like
delimiter[Data]delimiter[Data]delimiter[Data]
we will get as result array
"", "[Data]", "[Data]", "[Data]"
In your case delimiter is empty string "", and empty string exists not only inbetween characters, but also at start and end of string.
To solve this problem you could use split("(?!^)") which will split on each place as long it doesn't have start of string (^) after it (which excludes empty string at start of your text).
In Java 8 this behaviour changed: Why in Java 8 split sometimes removes empty strings at start of result array?
Well I guess what you are looking for is something like this
int[] hour = new int[2];
int[] minute = new int[2];
Calendar rightNow = Calendar.getInstance();
int tempHour = rightNow.get(Calendar.HOUR_OF_DAY);
int tempMin = rightNow.get(Calendar.MINUTE);
hour[0] = (int)Math.floor(tempHour/10);
hour[1] = tempHour%10;
minute[0] = (int)Math.floor(tempMin/10);
minute[1] = tempMin%10;
System.out.println(hour[0] + "" + hour[1] + ":" + minute[0] + "" + minute[1]);
Related
I need some help with these strings. My code is:
String string = database.getCurrentDate();;
String[] array = string.split("[.]", 0);
String date = array[0] + "." + array[1];
String string1=database.getCurrentHour();
String[] array1=string1.split("[:]",0);
String hour=array1[0]+":"+array1[1];
String finalString=date+hour;// finalString is 28.0310:45
I need that finalString to be:
date
hour//on next line
example:
28.03//date
10:45//hour
The point is that I need the hour to be displayed on the next line, under date.
Thank you!
String finalString = date + "\n" + hour
Don't work if you display this?
I am trying to write a program that loads a movie data base file, and then splits up that information into the movie title, year, and all of the associated actors. I split up all of the info, but I am having issues converting the year, which is in a string, to an int. The format of the year string is (****) with the * being a year, such as 1999. When I try to use parse I get a number format exception. I have tried replacing the parentheses, but it just gave me more errors! Any ideas?
public class MovieDatabase {
ArrayList<Movie> allMovie = new ArrayList<Movie>();
//Loading the text file and breaking it apart into sections
public void loadDataFromFile( String aFileName) throws FileNotFoundException{
Scanner theScanner = new Scanner(aFileName);
theScanner = new Scanner(new FileInputStream("cast-mpaa.txt"));
while(theScanner.hasNextLine()){
String line = theScanner.nextLine();
String[] splitting = line.split("/" );
String movieTitleAndYear = splitting[0];
int movieYearIndex = movieTitleAndYear.indexOf("(");
String movieYear = movieTitleAndYear.substring(movieYearIndex);
System.out.println(movieYear);
//this is where I have issues
int theYear = Integer.parseInt(movieYear);
String movieTitle = movieTitleAndYear.substring(0, movieYearIndex);
ArrayList<Actor> allActors = new ArrayList<Actor>();
for ( int i = 1; i < splitting.length; i++){
String[] names = splitting[i].split(",");
String firstName = names[0];
Actor theActor = new Actor(firstName);
ArrayList<Actor> allActor = new ArrayList<Actor>();
allActor.add(theActor);
}
Movie theMovie = new Movie(movieTitle, theYear, allActors);
allMovie.add(theMovie);
}
theScanner.close();
}
output:
(1967)
Here is the errors I am getting:
Exception in thread "main" java.lang.NumberFormatException: For input string: "(1967)"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:527)
at MovieDatabase.loadDataFromFile(MovieDatabase.java:27)
You have brackets around the numbers. You could either correct your file or you could remove brackets using:
String str = "(1967)";
System.out.println(str.substring(1, str.length()-1));
Output:
1967
In your code, you used:
int movieYearIndex = movieTitleAndYear.indexOf("(");
String movieYear = movieTitleAndYear.substring(movieYearIndex);
So if my movieTitleAndYear string is "hi (1947)", indexOf will give me index of "(" as 3 and substring will start reading string from index 3 which includes "(". One way you could avoid opening bracket is to change your substring line to:
String movieYear = movieTitleAndYear.substring(movieYearIndex + 1);//but still you have closing bracket.
If you are sure it's always going to be of four digit, then you could do something like:
String movieYear = movieTitleAndYear.substring(movieYearIndex + 1, movieYearIndex + 5);
You need to add indexof for ")".
Code snippet:
int movieYearOpenBracesIndex = movieTitleAndYear.indexOf("(");
int movieYearCloseBracesIndex = movieTitleAndYear.indexOf(")");
String movieYear = movieTitleAndYear.substring(movieYearOpenBracesIndex + 1, movieYearCloseBracesIndex);
System.out.println(movieYear);
This will give the exact year. e.g. 1967
Your substring call currently gets a year enclosed by brackets, e.g., (1967). You can avoid this by calling the substring variant that accepts an endIndex, and just get the year's four digits:
String movieYear =
movieTitleAndYear.substring(movieYearIndex + 1, // to get rid of "("
movieYearIndex + 5 // to get rid of ")"
);
I am working with this piece of code:
start = str.indexOf('<');
finish = str.indexOf('>');
between = str.substring(start + 1, finish);
replacement = str.substring(start, finish + 1);
System.out.println(between + " " + replacement); //for debug purposes
forreplacement = JOptionPane.showInputDialog(null, "Enter a " + between);
System.out.println(forreplacement); //for debug purposes
counter = counter - 1;
where "str" is the String that is being worked with. How do I replace the substring "replacement" with the string "forreplacement" (what is entered into the popup box) within the string str?
Not sure if that is what you want but maybe take part before start, add forreplacemeent and after that add part after finish like
String result = str.substring(0, start)+forreplacement+str.substring(finish+1);
Or if you want to replace all occurrences of replacement with forreplacement you can also use
String result = str.replace(replacement, forreplacement)
Your question is not clear. If you want to replace, you can do something like-
String str = "Hello World!";
String replacement = "World";
String stringToReplaceWith = "Earth";
str = str.replace(replacement, stringToReplaceWith);
System.out.println(str); // This prints Hello Earth!
I have a String which contains a date, for example "01-01-2012", then an space and then the time "01:01:01". The complete string is: "01-01-2012 01:01:01"
I would like to extract only the date from this string so at the end I would have "01-01-2012" but don't know how to do this.
Four options (last two added to make this one answer include the options given by others):
Parse the whole thing as a date/time and then just take the date part (Joda Time or SimpleDateFormat)
Find the first space using indexOf and get the leading substring using substring:
int spaceIndex = text.indexOf(" ");
if (spaceIndex != -1)
{
text = text.substring(0, spaceIndex);
}
Trust that it's valid in the specified format, and that the first space will always be at index 10:
text = text.substring(0, 10);
Split the string by spaces and then take the first result (seems needlessly inefficient to me, but it'll work...)
text = text.split(" ")[0];
You should consider what you want to happen if there isn't a space, too. Does that mean the data was invalid to start with? Should you just continue with the whole string? It will depend on your situation.
Personally I would probably go with the first option - do you really want to parse "01-01-2012 wibble-wobble bad data" as if it were a valid date/time?
String input = "01-01-2012 01:01:01";
String date = d.split(" ")[0];
Try this:
String date = s.substring(0, s.indexOf(" "));
Or even (because the length is fixed):
String date = s.substring(0, 10);
Or use StringUtils.substringBefore():
String date = StringUtils.substringBefore(s, " ");
Lots of ways to do this, a very simple method is to split the String at the space and use the first part (which will be the date):
String dateTime = "01-01-2012 01:01:01";
String date = dateTime.split(" ")[0];
You can use String.split() and take only the relevant String in your resultng String[] [in your example, it will be myString.split(" ")[0]
In that case where only one space is in the string, you can use String.split(" "). But this is a bad practice. You should parse the date with a DateFormat
.
You can use substring to extract the date only:
String thedatetime = "01-01-2012 01:01:01";
String thedateonly = thedate.substring(0, 10);
You should really read through the javadoc for String so you are aware of the available functions.
If you know in advance this is the format of the string, I'd do this:
public String getDateOnly(String fullDate){
String[] spl = fullDate.split(" ");
return spl[0];
}
You can do it either using string manipulation API:
String datetime = "01-01-2012 01:01:01";
int spacePos = datetime.indexOf(" ");
if (spacePos > 0) {
String date = datetime.substring(0, spacePos - 1);
}
or using regular expression:
Pattern p = Pattern.compile("(\\d{2}-\\d{2}-\\d{4})");
String datetime = "01-01-2012 01:01:01";
Matcher m = p.matcher(datetime);
if(m.find()) {
String date = m.group(1);
}
or using SimpleDateFormat
DateFormat fmt = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date date = fmt.parse(datetime);
Calendar c = Calendar.getInstance();
c.setTime(date);
String date = c.getDayOfMonth() + "-" + c.getMonth() + "-" + c.getYear();
Use String.substring(int, int). If you are interested in the value of the date and time, then use SimpleDateFormatter to parse your string.
myString.substring(0,10);
If your string is always in that format (2 digits, minus, 2 digits, minus, 4 digits, space etc...) then you can use substring(int beginIndex, int endIndex) method of string to get what you want.
Note that second parameter is the index of character after returning substring.
If you want to explode the complete date from the string use this method.
/**
* #param dateTime format string
* #param type type of return value : "date" or "time"
* #return String value
*/
private String getFullDate(String dateTime, String type) {
String[] array = dateTime.split(" ");
if (type == "time") {
System.out.println("getDate: TIME: " + array[1]);
return array[1];
} else if (type == "date") {
System.out.println("getDate: DATE: " + array[0]);
return array[0];
} else {
System.out.println("NULL.");
return null;
}
}
Otherwise if you want only the date for explample 01-01-2012
use this:
/**
* #param datetime format string
* #return
*/
private String getOnlyDate(String datetime) {
String array[] = datetime.split("-");
System.out.println("getDate: DATE: " + array[0]);
return array[0];
}
I hope my answer will help you.
time 12:45
i want to remove : in java .. i just need 1245 ..How can i do that?
String time = "12:45".replace( ":", "" ); // "1245"
If you have Apache Coomons Lang in your classpath, and you are not sure that time is not null, you could use StringUtils:
time = StringUtils.remove( time, ":" );
this way is more compact than writing
if ( time != null ) {
time = time.replace( ":", "" );
}
There is the "replace" method.
s = s.replace(':','');
If you want to get fancy:
s = s.replaceAll("[^a-zA-Z0-9]", "");
This will remove all non-alpha numeric characters (including your ':')
All right there in the JavaDoc.
If "12:45" is a string, then just use "12:45".replaceAll(":", "").
String strTime = "12:45";
strTime.replace(':','');
For the easiest method, use replace:
String time = "12:45";
time = time.replace(':', "");
but you can use regular expressions:
Pattern pattern = new Pattern("(\\d{1,2}):(\\d{1,2})");
Matcher matcher = pattern.matcher("12:45");
String noColon = matcher.group(1) + matcher.group(2);
or the String API:
String time = "12:45";
int colonIndex = time.indexOf(':"';
String noColon = time.substring(0, colonIndex) +
time.substring(colonIndex + 1, time.length);
Like what others told, a method as simple as String's replace should suffice, but since i suspect your input is a date, have a look at SimpleDateFormat too.