Convert String to a String having a date format - java

I want to write a java method that takes a string in input and outputs another string following this rule:
input output
"123456" "12:34:56"
"23456" "02:34:56"
"3456" "00:34:56"
"456" "00:04:56"
"6" "00:00:06"
Any help would be appreciated. Thanks.

I would advice to use DateFormat as below. This will take care of all the burdens of conversion.
DateFormat formatFrom = new SimpleDateFormat("HHmmss");
DateFormat formatTo = new SimpleDateFormat("HH:mm:ss");
String origTimeString = "456";
String newDateString = null;
try {
String formattedString =
String.format("%06d", Integer.parseInt(origTimeString));
Date date = formatFrom.parse(formattedString);
newDateString = formatTo.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("Updated string : " + newDateString);

Copy this method and use it.
1) If string length is more than 6, it's going to return "ERROR".
2) First fixes the String with '0'
3) Second fixes the String with ':'
4) StringBuilder is used for concat. Avoid using '+' operator for concat.
5) Method 'getDate' is static because of 'main' method is static, too.
public static String getDate(String variable){
StringBuilder aux= new StringBuilder();
StringBuilder string= new StringBuilder();
int length = variable.length();
if(length>6 || length<=0){
return "ERROR";
}else{
//first to fill blanks with 0
for(int i=0;i<6-length;i++){
aux.append("0");
}
variable = aux.append(variable).toString();
//second to put :
for(int i=0;i<6;i++){
if(i%2==0 && i!=0){
string.append(":");
}
string.append(variable.charAt(i));
}
return string.toString();
}
}
public static void main(String[] args) {
System.out.print(getDate("464"));
}

Related

Java error not a statement

When I try to compile my code I get the message
Main.java:31: error: not a statement
String bed = f.split(" ")
and also
error: ';' expected
String bed = f.split(" ");
I don't understand what's going on. I need to assign part of a file to a string.
Here's the code :
import java.util.Scanner;
import java.io.*;
public class Main{
public static void main(String[] args){
if ( args[0] == null){
System.out.println("File not Found");
return;
}
try {
File driver = new File (args[0]);
Scanner j = new Scanner( driver );
int i = 0;
while( j.hasNextLine()) {
String f = j.nextLine();
if (f.isEmpty() || f.startsWith("/")){ //If the String f is empty or has / it will continue reading the nextline after the / or space
continue;
if (f.startsWith("d")) {
String d = f.split(" ");
}
if (f.startsWith("b")) {
String b = f.split(" ");
}
if (f.startsWith("bed"))
String bed = f.split(" ");
}
System.out.println(f);
}
}
catch(FileNotFoundException e) {
System.out.println(e.getMessage());
}
catch (Exception ex) {
System.out.println(ex.getMessage);
}
}
}
.split() method returns an array so you should store it in an array, not in a string. Your code should be string b[]=f.split(" ") rather than storing it in string b
The split method returns splits the string based on the regex and returns an String array.
What you have here is String d = f.split(" ");, here you are trying to assign a string array to a string, and that is wrong.
It should instead say String[] d = f.split(" ");
I had this error.
I found a solution like below.
Error code
String a = "I goto the school";
String [] b = a.split("\\\s"); // error not a statement
Run code
try
{
String a = "I goto the school";
String [] b = a.split("\\\s");
}
catch(exception e)
{
}

Java reading from text file and remove dash in string

I have a text file:
John Smith 2009-11-04
Jenny Doe 2009-12-29
Alice Jones 2009-01-03
Bob Candice 2009-01-04
Carol Heart 2009-01-07
Carlos Diaz 2009-01-10
Charlie Brown 2009-01-14
I'm trying to remove the dashes and store them as separate types: first, last, year,month,day and then add it to a sortedset/hashmap. But for some reason. It's not working right.
Here is my code:
public class Test {
File file;
private Scanner sc;
//HashMap<Name, Date> hashmap = new HashMap<>();
/**
* #param filename
*/
public Test(String filename) {
file = new File(filename);
}
public void openFile(String filename) {
// open the file for scanning
System.out.println("Test file " + filename + "\n");
try {
sc = new Scanner(new File("birthdays.dat"));
}
catch(Exception e) {
System.out.println("Birthdays: Unable to open data file");
}
}
public void readFile() {
System.out.println("Name Birthday");
System.out.println("---- --------");
System.out.println("---- --------");
while (sc.hasNext()) {
String line = sc.nextLine();
String[] split = line.split("[ ]?-[ ]?");
String first = split[0];
String last = split[1];
//int year = Integer.parseInt(split[2]);
//int month = Integer.parseInt(split[3]);
//int day = Integer.parseInt(split[4]);
Resource name = new Name(first, last);
System.out.println(first + " " + last + " " + split[2] );
//hashmap.add(name);
}
}
public void closeFile() {
sc.close();
}
public static void main(String[] args) throws FileNotFoundException,
ArrayIndexOutOfBoundsException {
try {
Scanner sc = new Scanner( new File(args[0]) );
for( int i = 0; i < args.length; i++ ) {
//System.out.println( args[i] );
if( args.length == 0 ) {
}
else if( args.length >= 1 ) {
}
// System.out.printf( "Name %-20s Birthday", name.toString(), date.toString() );
}
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Usage: Birthdays dataFile");
// Terminate the program here somehow, or see below.
System.exit(-1);
} catch (FileNotFoundException e) {
System.err.println("Birthdays: Unable to open data file");
// Terminate the program here somehow, or see below.
System.exit(-1);
}
Test r = new Test(args[0]);
r.openFile(args[0]);
r.readFile();
r.closeFile();
}
}
Your splitting on dashes but your is program is build around a split using spaces.
Try just splitting on spaces
String[] split = line.split("\\s");
So "John Smith 2009-11-04".split("[ ]?-[ ]?"); results in ["John Smith 2009", "11", "04"] When what you want is for it to split on spaces ["John", "Smith", "2009-11-04"]
I would do this differently, first create a domain object:
public class Person {
private String firstName;
private String lastName;
private LocalDate date;
//getters & setters
//equals & hashCode
//toString
}
Now create a method that parses a single String of the format you have to a Person:
//instance variable
private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
public Person parsePerson(final String input) {
final String[] data = input.split("\\s+");
final Person person = new Person();
person.setFirstName(data[0]);
person.setLastName(data[1]);
person.setDate(LocalDate.parse(data[2], dateTimeFormatter));
return person;
}
Note that the DateTimeFormatter is an instance variable, this is for speed. You should also set the ZoneInfo on the formatter if you need to parse dates not in your current locale.
Now, you can read your file into a List<Person> very easily:
public List<Person> readFromFile(final Path path) throws IOException {
try (final Stream<String> lines = Files.lines(path)) {
return lines
.map(this::parsePerson)
.collect(toList());
}
}
And now that you have a List<Person>, you can sort or process them however you want.
You can even do this while creating the List:
public List<Person> readFromFile(final Path path) throws IOException {
try (final Stream<String> lines = Files.lines(path)) {
return lines
.map(this::parsePerson)
.sorted(comparing(Person::getLastName).thenComparing(Person::getFirstName))
.collect(toList());
}
}
Or have your Person implements Comparable<Person> and simply use natural order.
TL;DR: Use Objects for your objects and life becomes much simpler.
I would use a regex:
private static Pattern LINE_PATTERN
= Pattern.compile("(.+) (.+) ([0-9]{4})-([0-9]{2})-([0-9]{2})");
...
while (sc.hasNext()) {
String line = sc.nextLine();
Matcher matcher = LINE_PATTERN.matcher(line);
if (!matcher.matches()) {
// malformed line
} else {
String first = matcher.group(1);
String last = matcher.group(2);
int year = Integer.parseInt(matcher.group(3));
int month = Integer.parseInt(matcher.group(4));
int day = Integer.parseInt(matcher.group(5));
// do something with it
}
}
You are splitting on spaces and a hyphen. This pattern does not exist.
String[] split = line.split("[ ]?");
String first = split[0];
String last = split[1];
line = split[2];
//now split the date
String[] splitz = line.split("-");
or something like this might work:
String delims = "[ -]+";
String[] tokens = line.split(delims);
If i understood your question right then Here is answer. Check it out.
List<String> listGet = new ArrayList<String>();
String getVal = "John Smith 2009-11-04";
String[] splited = getVal.split("[\\-:\\s]");
for(int j=0;j<splited.length;j++)
{
listGet.add(splited[j]);
}
System.out.println("first name :"+listGet.get(0));
System.out.println("Last name :"+listGet.get(1));
System.out.println("year is :"+listGet.get(2));
System.out.println("month is :"+listGet.get(3));
System.out.println("day is :"+listGet.get(4));
OP :
first name :John
Last name :Smith
year is :2009
month is :11
day is :04

Finding Correct exception to catch

Which exception can i use to check if the input has the right number of "/"
The input should be like DD/MM/YYYY
try{
String str = text.getText();
StringTokenizer st = new StringTokenizer(str);
String DD = st.nextToken("/");
String MM = st.nextToken("/");
String YYYY = st.nextToken();
}
catch( ???){
}
You will find it in the javadoc of nextToken.
It says it will throw a NoSuchElementException when there is no more token.
That said you should better not use the try/catch but test it using the hasMoreTokens method.
You can use Custom Exception for this but for that you need to declare method which validate your date (No of slashes).
Try Like this
public class Demo
{
public static void main (String[] args) {
try {
new MyClass().metToValidate("01/12/2014");
} catch (A e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class A extends Exception{}
class MyClass{
public void metToValidate(String dateText) throws A{
if( dateText.charAt(2) == '/'&& dateText.charAt(5) == '/' )
System.out.println("DATE IS OK");
else
throw new A();
}
}
The exception throws by nextToken is NoSuchElementException.
String str = "12/21223";
int counter = 0;
for( int i=0; i<str.length(); i++ ) {
if( str.charAt(i) == '/' ) {
counter++;
}
}
if(counter == 3){
StringTokenizer st = new StringTokenizer(str);
String DD = st.nextToken("/");
String MM = st.nextToken("/");
String YYYY = st.nextToken();
System.out.println(str);
}else{
System.out.println("Exception");
}

How do I call a non-static method from another class in a non-static method? (java)

import java.util.*;
import java.io.*;
public String recToString (boolean format) {
Date date = new Date();
File inputFile = new File ("records.txt");
Scanner sc = new Scanner(inputFile);
if (format == true){
format = Date1.usFormat();
format = Date1.usFormat();
} else {
format = Date1.euFormat();
}
}
I plan to call the usFormat and euFormat.
import java.util.*;
import java.io.*;
class Date1 {
String month = "";
String day = "";
String year = "";
public Date1 (String date) {
StringTokenizer st = new StringTokenizer(date, "/");
month = st.nextToken();
day = st.nextToken();
year = st.nextToken();
} //end constructor
public String usFormat () {
String date = month + "/" + day + "/" + year;
return date;
} //end usFormat
public String euFormat () {
String date = day + "/" + month + "/" + year;
return date;
} //end euFormat
} //end class
Try to ignore any other mistakes please. But if it screws up this and I have to change it to get it, please do tell :)
Thanks.
You need to construct a Date1 object and call the methods on that. You need to do something like
...
String dateString = ...
Date1 date1 = new Date1(dateString);
if (format){
format = date1.usFormat();
} else {
format = date1.euFormat();
}
In this case i'd typically do the following
format = new Date1(date.toString()).usFormat();
format = new Date1(date.toString()).usFormat();
Not sure why you are not making them static though.
You're calling:
Date1.usFormat();
like usFormat is a static method. But, as you already said, it's not. You need to create an instance of Date1 by doing:
Date1 myDate1 = new Date1("01/01/2001");
After that you can call either format method with the myDate1 object like:
format = myDate1.usFormat();

split variables from texte

this method runs an exception and i didn't find why.
private void loadTrace () {
BufferedReader reader = new BufferedReader(
new StringReader(logTextArea.getText()));
String str;
try {
while(reader != null)
{
str =reader.readLine();
String [] splitted = str.split("\\|");
String b = splitted[1].trim();
String c = splitted[2].trim();
String d = splitted[3].trim();
String Chemin;
String Type = "action" ;
String Description;
if (d!=null) {
Description=d;
}
else Description ="Afficher onglet";
if (c!= null) {
Chemin= b+"."+c;
}
else Chemin =b;
String trace =Type+" "+Description +" "+Chemin ;
ArrayList<String> p = new ArrayList<String>();
p.add(trace);
System.out.println(p);
}
}
catch(IOException e) {
e.printStackTrace();
}
}
Without knowing the exception I can guess one of the potential issue is in these lines:-
String [] splitted = str.split("\\|");
String b = splitted[1].trim();
String c = splitted[2].trim();
String d = splitted[3].trim();
You are accessing splitted without checking if it is null or size so you may run into ArrayIndexOutOfBound exception if splitted length is less than 3. So modify the code this way-
String [] splitted = str.split("\\|");
if(splitted!=null && splitted.length==3){
String b = splitted[0].trim();
String c = splitted[1].trim();
String d = splitted[2].trim();
}
The NullPointerException you get now that you've fixed the ArrayIndexOutOfBound is because of the test you use in your while loop:
while(reader != null)
{
...
}
reader will always be non-null so this loop will never end. You need to test if
reader.readLine()
returns null (indicating EOF).
I guess you get an ArrayIndexOutOfBoundException, right?
(You need to tell us, what Exception you receive)
The problem could be in the following lines. You should check the size of the array and not just "hope" that it has three parts.
String b = splitted[1].trim();
String c = splitted[2].trim();
String d = splitted[3].trim();

Categories