Can't format the output the correct way - java

I have this code to read each line of a file of this type "603,The Matrix,1999-03-30,63000000,136,7.9,9079"
but I only need to read the first 3 parameters and the 3rd one each is a date needs to be read separately, therefor it needs to put the year in a var and the month in other var and then the day in another var but the output I get is this: "[603 | The Matrix | 03-603,The Matrix,1999-1999-03-30"
int i;
Scanner leitorFicheiroFilmes = new Scanner(ficheiroFilmes);
ArrayList<Filmes> filme = new ArrayList<>();
for (i = 0; leitorFicheiroFilmes.hasNextLine(); i++) {
String line = leitorFicheiroFilmes.nextLine();
String dados[] = linha.split(",");
if (dados.length == 7) {
int idFilme = Integer.parseInt(dados[0]);
String titulo = dados[1];
String dadosNew[] = line.split("-");
String ano = dados[2];
String mes = dadosNew[0];
String dia = dadosNew[1];
filme.add(new Filmes(idFilme, title, year, month, day, parseActoresFile(), parseGenerosFile(idFilme)));
}
}
this is the class with the constructor:
public class Filmes {
int idFilme;
String titulo;
ArrayList<Actores> actores = new ArrayList<Actores>();
ArrayList<GenerosCinematograficos> generos = new ArrayList<GenerosCinematograficos>();
String year, month, day;
public Filmes(int idFilme, String titulo, String year, String month, String day, ArrayList<Actores> actores, ArrayList<GenerosCinematograficos> generos) {
this.idFilme = idFilme;
this.titulo = titulo;
this.year = year;
this.month = month;
this.day = day;
this.actores = actores;
this.generos = generos;
}
public String toString() {
return idFilme + " | " + titulo + " | " + dia + "-" + mes + "-" + ano;
}
}

String dadosNew[] = line.split("-");
must be
String dadosNew[] = dados[2].split("-");
dadosNew array will be [1999,03,30] from which you can get the date, month and year by accessing the correct indices.

You are reading incorrect values to your variables when parsing the date
String dadosNew[] = line.split("-");
String ano = dados[2];
String mes = dadosNew[0];
String dia = dadosNew[1];
to
String dadosNew[] = dados[2].split("-");
String ano = dadosNew[0];
String mes = dadosNew[1];
String dia = dadosNew[2];

The problem is here :
String dadosNew[] = line.split("-");
With the input (line) being "603,The Matrix,1999-03-30,63000000,136,7.9,9079" The result wille be :
{"603,The Matrix,1999", "03", "30,63000000,136,7.9,9079"}
You want to split only the date, and this is contained in dados[2], so to correct it you have to do :
String dadosNew[] = dados[2].split("-");

Related

multiple String location find using a key in a tag

I want to parse an input eg: GH123FG12B1A58 .
'GH' / 'FG' / 'A' / 'B' will be there in all the tags in same order but different position . eg: GH14555523FG1555552B55551A55558
Need to find the value after every keys
I see this can be done by using patter , get start & end index ? Is there any other way to acomplish this ?
import java.util.Scanner;
public class Shipparse {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner Iname = new Scanner(System.in);
System.out.println("Enter the invoice :");
String Maintag = Iname.nextLine();
String GH = "GH";
String FG = "FG";
String AB = "AB";
String B = "B";
String A = "A";
int cus = Maintag.indexOf(GH);
int cys = Maintag.indexOf(FG);
int ats = Maintag.indexOf(AB);
int ss = Maintag.indexOf(B);
int se = Maintag.indexOf(A);
int tlength = Maintag.length();
StringBuilder str = new StringBuilder(Maintag);
String cnum;
if ( ats == -1) {
cnum = str.substring((cus +2) , cys);
System.out.println("Customer :" + cnum);
String cyn = str.substring((cys + 2), ss);
System.out.println("Agent :" + cyn);
} else {
cnum = str.substring((cus +2) , ats);
System.out.println("Customer :" + cnum);
String cyn = str.substring((ats + 2), ss);
System.out.println("Company:" + cyn);
}
String spoint = str.substring((ss +1) , se);
System.out.println("TYPE NUM:" + spoint);
String send = str.substring((se +1) , tlength);
System.out.println("FIELD NUM :" + send);
}
}

regex join line infos

I have to parse this package:
WGS AUFFUELLUNGEN
ADMIN1 23.03.
17:09 -20- 1500.00
17:10 JD20 560.00
17:11 -2.0- 112.00
ADMIN1 24.03.
14:51 JD50 500.00
ADMIN2 27.03.
08:58 JD50 500.00
----------------------
3172.00
Parsing the user and date is easy:
\r?\n(.*)\s+(\d\d\.\d\d\.)
Parsing the time, denomination and amount is easy too:
\r?\n(\d\d:\d\d)\s+(.*)\s+(\d+\.\d\d)
But I need a parsing that detects user, date, time, denomination and amount for every booking at once.
Any ideas?
You will need some kind of intermediate structure you can iterate over. If you cant change your java code maybe you can use a regex to first match a whole block of you example string. In a second step you match all the details.
public class RegexTestCase {
private static final String PACKAGE
= "WGS AUFFUELLUNGEN \n" +
"ADMIN1 23.03.\n" +
"17:09 -20- 1500.00\n" +
"17:10 JD20 560.00\n" +
"17:11 -2.0- 112.00\n" +
"ADMIN1 24.03.\n" +
"14:51 JD50 500.00\n" +
"ADMIN2 27.03.\n" +
"08:58 JD50 500.00\n" +
"----------------------\n" +
" 3172.00\n";
private static final String NL = "\\r?\\n";
private static final String USER_DATE_REGEX
= "(.*?)\\s+(\\d\\d\\.\\d\\d\\.)";
private static final String TIME_AMOUNT_REGEX
= "(\\d\\d:\\d\\d)\\s+(.*?)\\s+(\\d+\\.\\d\\d)";
private static final String BLOCK_REGEX
= USER_DATE_REGEX + NL + "((" + TIME_AMOUNT_REGEX + NL + ")+)";
#Test
public void testRegex() throws Exception {
Pattern blockPattern = Pattern.compile( BLOCK_REGEX );
Pattern timeAmountPattern = Pattern.compile( TIME_AMOUNT_REGEX );
int count = 0;
Matcher blockMatcher = blockPattern.matcher( PACKAGE );
while (blockMatcher.find() ) {
String name = blockMatcher.group( 1 );
String date = blockMatcher.group( 2 );
String block = blockMatcher.group( 3 );
Matcher timeAmountMatcher = timeAmountPattern.matcher( block );
while ( timeAmountMatcher.find() ) {
String time = timeAmountMatcher.group( 1 );
String denom = timeAmountMatcher.group( 2 );
String amount = timeAmountMatcher.group( 3 );
assertEquals( "wrong name", RESULTS[count].name, name );
assertEquals( "wrong date", RESULTS[count].date, date );
assertEquals( "wrong time", RESULTS[count].time, time );
assertEquals( "wrong denom", RESULTS[count].denom, denom );
assertEquals( "wrong amount", RESULTS[count].amount, amount );
count++;
}
}
assertEquals( "wrong number of results", 5, count);
}
private static final Result[] RESULTS
= { new Result("ADMIN1", "23.03.", "17:09", "-20-", "1500.00")
, new Result("ADMIN1", "23.03.", "17:10", "JD20", "560.00")
, new Result("ADMIN1", "23.03.", "17:11", "-2.0-", "112.00")
, new Result("ADMIN1", "24.03.", "14:51", "JD50", "500.00")
, new Result("ADMIN2", "27.03.", "08:58", "JD50", "500.00")
};
static final class Result {
private final String name;
private final String date;
private final String time;
private final String denom;
private final String amount;
Result( String name, String date, String time, String denom, String amount ) {
this.name = name;
this.date = date;
this.time = time;
this.denom = denom;
this.amount = amount;
}
}
}
Your second regex is too eager, have a look at this.
I suggest to change it into \r?\n(\d\d:\d\d)\s+(.*?)\s+(\d+.\d\d)
This regex would match user, date, time, denomination and amount for every booking at once, but I have added the multiline regex flag.:
(^(.*)\s+(\d\d\.\d\d\.)$|^(\d\d:\d\d)\s+(.*)\s+(\d+\.\d\d)$)+
Split the entire string by new line
Iterate over the each line and
a. look for username and date by regex1, if matches then extract userName and Date
b. if regex1 doesn't, then look for time, denomincation and amount regex2 . if it matches
then extract time, denomination and amount from this.
final String userRegex = "^(\\w+)\\s+(\\d+\\.\\d+\\.)$";
final String timeRegex = "^(\\d+:\\d+)\\s+([\\S]+)\\s+(\\d+\\.?\\d+)$";
Sample Source:
public static void main(String[] args) {
final String userRegex = "^(\\w+)\\s+(\\d+\\.\\d+\\.)$";
final String timeRegex = "^(\\d+:\\d+)\\s+([\\S]+)\\s+(\\d+\\.?\\d+)$";
final String string = "WGS AUFFUELLUNGEN\n"
+ "ADMIN1 23.03.\n"
+ "17:09 -20- 1500.00\n"
+ "17:10 JD20 560.00\n"
+ "17:11 -2.0- 112.00\n"
+ "ADMIN1 24.03.\n"
+ "14:51 JD50 500.00\n"
+ "ADMIN2 27.03.\n"
+ "08:58 JD50 500.00\n"
+ "----------------------\n"
+ " 3172.00\n";
String[] list = string.split("\n");
Matcher m;
int cnt=1;
for (String s : list) {
m=Pattern.compile(userRegex).matcher(s);
if (m.matches()) {
System.out.println("##### List "+cnt+" ######");
System.out.println("User Name:"+m.group(1));
System.out.println("Date :"+m.group(2));
cnt++;
}
else
{
m=Pattern.compile(timeRegex).matcher(s);
if(m.matches())
{
System.out.println("Time :"+m.group(1));
System.out.println("Denomination :"+m.group(2));
System.out.println("Amount :"+m.group(3));
System.out.println("---------------------");
}
}
}
}

Java set the tommorrow id number to one

My requirements:
ddmm + 2numbers
dd - day
mm - month
number - id number
Examples of my output
Today - 031201, 031202, 031203 ...
Tommorrow - 041201
Properties file: (idNumber.properties)
idNumber = 1;
Here is the java code I did:
public class Test{
public static void main(String[] args)
{
Test test = new Test();
test.generate();
}
public String generate()
{
DateFormat dateFormat = new SimpleDateFormat("ddMM");
Date date = new Date();
String currentDate = dateFormat.format(date);
String idNumber = generateIdNumber();
String complete = currentDate + idNumber;
return complete;
}
public String generateIdNumber(){
Properties idNoProp = new Properties();
InputStream idNoInput = new FileInputStream("idNumber.properties"); //java properties file
idNoProp.load(idNoInput);
String idNumber = idNoProp.getProperty("idNumber");
int idNo = Integer.valueOf(idNumber);
String result = "";
if (idNo < 10) {
result = "0" + idNo;
} else {
result = "" + idNo;
}
idNo++;
OutputStream output = new FileOutputStream("idNumber.properties");
idNoProp.setProperty("idNumber", "" + idNo);
idNoProp.store(output, null);
return result;
}
}
My question is how do I reset the tommorrow id number start from 01?
You can add a property LAST_VISIT to your properties file. When you want to save the properties file, set the current date to it. In this way
DateFormat dateFormat = new SimpleDateFormat("ddMM");
Date date = new Date();
String currentDate = dateFormat.format(date);
idNoProp.setProperty("LAST_VISIT", currentDate);
Now in generateIdNumber() first check the value of LAST_VISIT. If it dose not equal currentDate , you must reset idNo. It works for everyday and every tommorow.
Try to put a class static field to remember last used date for ids. Whenever you are in the next date relatively to the field you'll reset your idNo and update the last used date field (sorry for spelling)
You can store a Map<String,Integer> that would hold the last index for each String representation of date. This way, each date would have its own indices starting with 1.
You can run a scheduler which will reset the idNo at the start of each day, like at 00 hours. This will always gives you the consistent result, as if sometimes server/program restarts, it will not lead to any duplicate result.
if you want format a number with two number, example '01' you could do this:
String.format("%02d", Integer.valueOf(idNumber));
instead of:
int idNo = Integer.valueOf(idNumber);
String result = "";
if (idNo < 10) {
result = "0" + idNo;
} else {
result = "" + idNo;
}
public class Test{
public static void main(String[] args) throws IOException
{
Test test = new Test();
System.out.println(""+test.generate());
}
public String generate() throws IOException
{
DateFormat dateFormat = new SimpleDateFormat("ddMM");
Date date = new Date();
String currentDate = dateFormat.format(date);
String idNumber = generateIdNumber(currentDate);
String complete = currentDate + idNumber;
return complete;
}
public String generateIdNumber(String currentDate) throws IOException{
Properties idNoProp = new Properties();
InputStream idNoInput = new FileInputStream("idNumber.properties"); //java properties file
idNoProp.load(idNoInput);
String idNumber = idNoProp.getProperty("idNumber");
int idNo = Integer.valueOf(idNumber);
String strOnlyDay = currentDate.substring(0, 2);
System.out.println(strOnlyDay);// will return the first two characters of the day
String result = "";
if (idNo < 10) {
result = "0" + idNo;
} else {
result = "" + idNo;
}
idNo++;
OutputStream output = new FileOutputStream("idNumber.properties");
if (strOnlyDay.equals("01")){
idNo = 1;
}
idNoProp.setProperty("idNumber", "" + idNo);
idNoProp.store(output, null);
return result;
}
}
Try to pass the value of your current date into generateIdNumber than see the code. I hope this will help. Hoping you will preserve the value of idNo.

java regular expression check date format

private static String REGEX_ANY_MONTH = "January|Jan|February|Feb|March|Mar|April|Apr|May|June|Jun|"
+ "July|Jul|August|Aug|September|Sep|October|Oct|November|Nov|December|Dec";
private static String REGEX_ANY_YEAR = "[0-9]{4}";
private static String REGEX_ANY_DATE = "[0-9]{1,2}";
private String getFormat(String date) {
if (date.matches(REGEX_ANY_MONTH + " " + REGEX_ANY_DATE + "," + " " + REGEX_ANY_YEAR)) {
return "{MONTH} {DAY}, {YEAR}";
} else if (date.matches(REGEX_ANY_MONTH + " " + REGEX_ANY_YEAR)){
return "{MONTH} {YEAR}";
}
return null;
}
#Test
public void testGetFormatDateString() throws Exception{
String format = null;
String test = null;
test = "March 2012";
format = Whitebox.<String> invokeMethod(obj, "getFormat", test);
Assert.assertEquals("{MONTH} {YEAR}", format);
test = "March 10, 2012";
format = Whitebox.<String> invokeMethod(obj, "getFormat", test);
Assert.assertEquals("{MONTH} {DATE}, {YEAR}", format);
}
Both of the asserts are failing for me. What am I missing?
You need to wrap your piped list of month names in parentheses in order for it to match.
private static String REGEX_ANY_MONTH = "(January|Jan|February|Feb|March|Mar|April|Apr|May|June|Jun|"
+ "July|Jul|August|Aug|September|Sep|October|Oct|November|Nov|December|Dec)";
Otherwise the 'or' condition will be or-ing more than just the month.

Convert the string "8:00" into the minutes (integer value)

I'm reading the data from CSV file. One of the fields is the time in the format H:mm, i.e. "8:00". How to convert this string value into the minutes (integer value), i.e. 8:00 = 8*60 = 480 minutes?
String csvFilename = "test.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
String[] row = null;
csvReader.readNext(); // to skip the headers
int i = 0;
while((row = csvReader.readNext()) != null) {
int open = Integer.parseInt(row[0]);
}
csvReader.close();
You can use java.text.SimpleDateFormat to convert String to Date. And then java.util.Calendar to extract hours and minutes.
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date date = sdf.parse("8:00");
cal.setTime(date);
int mins = cal.get(Calendar.HOUR)*60 + cal.get(Calendar.MINUTE);
Try something like this
String str = "8:10";
int minutes=0;
String[] arr= str.split(":");
if(arr.length==2){
minutes=Integer.parseInt(arr[0])*60+Integer.parseInt(arr[1]);
}
System.out.println(minutes);
Write something like this to convert into int
public int convertToMin(String hrmin) {
String[] tokens = hrmin.split(":");
int minutes = 0;
for (int i = tokens.length; i > 0; i--) {
int value = Integer.parseInt(tokens[i - 1]);
if (i == 1) {
minutes += 60 * value;
}
else {
minutes += value;
}
}
return minutes;
}
Try this
String str = "8:20";
int ans = (Integer.parseInt(str.split(":")[0])* 60)+Integer.parseInt(str.split(":")[1]);
System.out.println("Answer = "+ans);

Categories

Resources