So this code I'm trying to output to text file in a certain format so that when I load it it wont have any problems. I'm using String.format("%02d", 5) to output 05 instead of just 5. This works in console but when outputing to text file it seems to output as 5 not 05. Why is this happening?
PrintWriter output = new PrintWriter(scheduleFile);
for (int i = 0; i < getSchedule().length; i++) {
for (int j = 0; j < getSchedule()[i].length; j++) {
output.print(j + ":00-" + (j + 1) + ":00 =");
if (getSchedule()[i][j] != null) { // if not null
output.print(String.format("%02d", (j)) + ":00-" + String.format("%02d", (j+1)) + ":00 "); // print hours
}
output.println();
}
}
Text file looks like this:
0:00-1:00 =
1:00-2:00 =
2:00-3:00 =
3:00-4:00 =
4:00-5:00 =
5:00-6:00 =
6:00-7:00 =
7:00-8:00 =
8:00-9:00 =
9:00-10:00 =
.
.
.
should look like this:
00:00-01:00 =
01:00-02:00 =
02:00-03:00 =
03:00-04:00 =
04:00-05:00 =
05:00-06:00 =
06:00-07:00 =
07:00-08:00 =
08:00-09:00 =
09:00-10:00 =
.
.
.
Related
I am displaying output in jsp page using scriplets.
I am getting output from database as follows:
out.println(a) ; //prints output Jan-2019 Feb-2019 March-2019 April-2019
out.println(b) ; //prints output 100100200300
I am trying to print the output in jsp page using html css as follows:
Month Price
Jan-2019 100
Feb-2019 100
March-2019 200
April-2019 300
I searched a lot in google still didn't find any solution also tried with different regex code still its not resolved. Any help will be much appreciated.
Here is the code. It was intentionally made more "verbose" so as to facilitate more use of Regular Expressions with your data feed.
String a = "Jan-2019 Feb-2019 March-2019 April-2019";
String b = "100100200300";
Pattern P1 = Pattern.compile("(\\w{3,})-(\\d{4})");
Pattern P2 = Pattern.compile("[1-9]+0+");
Vector<Integer> years = new Vector<>();
Vector<String> months = new Vector<>();
Vector<Integer> prices = new Vector<>();
Matcher m = P1.matcher(a);
while (m.find())
{
months.add(m.group(1));
years.add(new Integer(m.group(2)));
}
m = P2.matcher(b);
while (m.find()) prices.add(new Integer(m.group()));
// Useful for debugging, to make sure these are "parallel arrays"
// Parallel Arrays are almost *always* useful when regular-expressions & parsing is "happening."
System.out.println( "years.size():\t" + years.size() + '\n' +
"months.size():\t" + months.size() + '\n' +
"prices.size():\t" + prices.size() + "\n\n" );
int len = years.size();
for (int i=0; i < len; i++)
System.out.println( months.elementAt(i) + " " +
years.elementAt(i) + ":\t" +
prices.elementAt(i) );
System.exit(0);
Here is the output:
years.size(): 4
months.size(): 4
prices.size(): 4
Jan 2019: 100
Feb 2019: 100
March 2019: 200
April 2019: 300
For splitting a do this:
String[] months = a.split(" ");
For splitting b do this:
ArrayList<String> prices = new ArrayList<String>();
boolean isZero = false;
String tmpPrice = "";
for (int i = 0; i < b.length(); i++) {
if (i + 1 >= b.length()) {
tmpPrice = tmpPrice + b.charAt(i);
prices.add(tmpPrice);
} else if (isZero && b.charAt(i) != '0') {
prices.add(tmpPrice);
tmpPrice = "" + b.charAt(i);
isZero = false;
} else if (b.charAt(i) == '0') {
isZero = true;
tmpPrice = tmpPrice + b.charAt(i);
} else if (b.charAt(i) != '0') {
isZero = false;
tmpPrice = tmpPrice + b.charAt(i);
}
}
I have a String = "abc model 123 abcd1862893007509396 abcd2862893007509404", if I provide space between abcd1 & number eg. abcd1 862893007509396 my code will work fine, but if there is no space like abcd1862893007509396, I will get java.lang.ArrayIndexOutOfBoundsException, please help ?:
PFB the code :
String text = "";
final String suppliedKeyword = "abc model 123 abcd1862893007509396 abcd2862893007509404";
String[] keywordarray = null;
String[] keywordarray2 = null;
String modelname = "";
String[] strIMEI = null;
if ( StringUtils.containsIgnoreCase( suppliedKeyword,"model")) {
keywordarray = suppliedKeyword.split("(?i)model");
if (StringUtils.containsIgnoreCase(keywordarray[1], "abcd")) {
keywordarray2 = keywordarray[1].split("(?i)abcd");
modelname = keywordarray2[0].trim();
if (keywordarray[1].trim().contains(" ")) {
strIMEI = keywordarray[1].split(" ");
for (int i = 0; i < strIMEI.length; i++) {
if (StringUtils.containsIgnoreCase(strIMEI[i],"abcd")) {
text = text + " " + strIMEI[i] + " "
+ strIMEI[i + 1];
System.out.println(text);
}
}
} else {
text = keywordarray2[1];
}
}
}
After looking at your code the only thing i can consider for cause of error is
if (StringUtils.containsIgnoreCase(strIMEI[i],"abcd")) {
text = text + " " + strIMEI[i] + " "
+ strIMEI[i + 1];
System.out.println(text);
}
You are trying to access strIMEI[i+1] which will throw an error if your last element in strIMEI contains "abcd".
I have a text editor where user can put text like this:
[[PAYMENTS_N]] You have to pay [[amount]]$ before [[date]].[[/PAYMENTS_N]]
[[PAYMENTS_Z]] You didn't pay [[debt]]$ on time: [[ddate]].[[/PAYMENTS_Z]]
And there are XML files that look like this:
<DATA_NZ><USER><ID>12345</ID><COMP_NZ><COMP>
<STATUS>Z</STATUS>
<AMOUNT_NZ>128.01</AMOUNT_NZ>
<DATE_NZ>28.05.2015</DATE_NZ>
<STATUS>N</STATUS>
<AMOUNT_NZ>12.32</AMOUNT_NZ>
<DATE_NZ>21.09.2015</DATE_NZ>
<STATUS>N</STATUS>
<AMOUNT_NZ>12.32</AMOUNT_NZ>
<DATE_NZ>20.10.2015</DATE_NZ>
</COMP></COMP_NZ></USER></DATA_NZ>
Now I want to change the text from editor into something like this:
Remember about your next payments:
You have to pay 12.32$ before 21.09.2015.
You have to pay 12.32$ before 20.10.2015.
You didn't pay 128.01$ on time: 28.05.2015.
And I have this code:
public void parseTags(String content) {
String nOpenTag, nCloseTag;
String zOpenTag, zCloseTag;
String dnTag, knTag, dzTag, kzTag;
nOpenTag = "[[PAYMENTS_N]]";
nCloseTag = "[[/PAYMENTS_N]]";
zOpenTag = "[[PAYMENTS_Z]]";
zCloseTag = "[[/PAYMENTS_Z]]";
dnTag = "[[amount]]";
knTag = "[[date]]";
dzTag = "[[debt]]";
kzTag = "[[ddate]]";
String textToExtract = "";
String textToExtract = "";
String textToReplace = "";
String parsedContent = content;//; = content;
if (content.contains(nOpenTag) || content.contains(zOpenTag)) {
for (int i = 0; i < getXMLContainer("SZUK_XM4.XML").getUsers().size(); i++) {
if (getXMLContainer("SZUK_XM4.XML").getUsers().get(i) != null) { //
contact = consentService.findByContactTypeAndIdNumber(ContactType.EMAIL, getXMLContainer("SZUK_XM4.XML").getUsers().get(i).getIdNumber());
payments = getXMLContainer("SZUK_XM4.XML").getUsers().get(i).getPaymentContainer().getPayments();
if (contact.size() > 0) {
StringBuilder strB = new StringBuilder();
StringBuilder strB2 = new StringBuilder();
String textToReplace;
for (int c = 0; c < contact.size(); c++) {
strB.setLength(0);
for (int p = 0; p < payments.size(); p++) {
if (payments.get(p).getStatus().contains("N")) {
textToExtract = content.substring(content.indexOf(nOpenTag) + nOpenTag.length(), content.indexOf(nCloseTag));
textToReplace = textToExtract.replace(dnTag, "Day " + payments.get(p).getPaymentDate());
textToReplace = textToReplace.replace(knTag, "Amount " + payments.get(p).getPaymentAmount());
strB.append(textToReplace);
parsedContent = content.replace(textToExtract, strB.toString());
}
if (payments.get(p).getStatus().contains("Z")) {
textToExtract = parsedContent.substring(parsedContent.indexOf(zOpenTag) + zOpenTag.length(), parsedContent.indexOf(zCloseTag));
textToReplace = textToExtract.replace(dzTag, "Day " + payments.get(p).getPaymentDate());
textToReplace = textToReplace.replace(kzTag, "Amount " + payments.get(p).getPaymentAmount());
strB2.append(textToReplace);
parsedContent = parsedContent.replace(textToExtract, strB2.toString());
}
}
mailService.sendTemplateMail(contact.get(c).getContact(), parsedContent);
}
}
}
}
}
}
This code is supposed to find in the database user with given ID from XML.
If user exists then it reads all the data between and replaces [[TAGS]] from the text editor. After everything's done, it should send an email with replaced text.
The problem is that the text it sends isn't correctly replaced. It gives
Remember about your next payments: You have to pay 12.32$ before
21.09.2015. You have to pay 12.32$ before 20.10.2015.
You didn't pay [[debt]]$ on time: [[ddate]].
See the difference in the last line?
I'm using JAXB to read XML, if it matters.
Hope you can help me! Thanks.
replace:
parsedContent = content.replace(textToExtract, strB.toString());
with:
parsedContent = parsedContent.replace(textToExtract, strB.toString());
I am trying to parse a pdf file with "iText". What I am trying to achieve is to parse all pages at once.
try {
PdfReader reader = new PdfReader("D:\\hl_sv\\L04MF.pdf");
int pages = reader.getNumberOfPages();
String content = "";
for (int i = 0; i <= pages; i++) {
System.out.println("============PAGE NUMBER " + i + "=============" );
content = content + " " + PdfTextExtractor.getTextFromPage(reader, i);
}
System.out.println(content);
}
I am getting this error:
Exception in thread "main" java.lang.NullPointerException
at com.itextpdf.text.pdf.parser.PdfReaderContentParser.processContent(PdfReaderContentParser.java:77)
at com.itextpdf.text.pdf.parser.PdfTextExtractor.getTextFromPage(PdfTextExtractor.java:74)
at com.itextpdf.text.pdf.parser.PdfTextExtractor.getTextFromPage(PdfTextExtractor.java:89)
at com.pdf.PDF.main(PDF.java:18)
Other problem I am facing is that the - hyphen is being parsed as ? question mark. How can I fix that?
I appreciate any help.
Edit
It works for me like this but I cant still solve the hyphen bug.
try {
PdfReader reader = new PdfReader("D:\\hl_sv\\L04MF.pdf");
int pages = reader.getNumberOfPages();
for(int i = 1; i<= pages; i++) {
System.out.println("============PAGE NUMBER " + i + "=============" );
String line = PdfTextExtractor.getTextFromPage(reader,i);
System.out.println(line);
}
}
public static String extractPdfText() throws IOException {
PdfReader pdfReader = new PdfReader("/path/to/file/myfile.pdf");
int pages = pdfReader.getNumberOfPages();
String pdfText = "";
for (int ctr = 1; ctr < pages + 1; ctr++) {
pdfText += PdfTextExtractor.getTextFromPage(pdfReader, ctr); // Page number cannot be 0 or will throw NPE
}
pdfReader.close();
return pdfText;
}
I've been trying to convert a PHP code to Java, but its not working as intended. I get an error in the loop with "String index out of range" after a few runs on char nextchar = inprogresskey.charAt(ranpos);
The PHP code is:
function munge($address)
{
$address = strtolower($address);
$coded = "";
$unmixedkey = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.#";
$inprogresskey = $unmixedkey;
$mixedkey="";
$unshuffled = strlen($unmixedkey);
for ($i = 0; $i <= strlen($unmixedkey); $i++)
{
$ranpos = rand(0,$unshuffled-1);
$nextchar = $inprogresskey{$ranpos};
$mixedkey .= $nextchar;
$before = substr($inprogresskey,0,$ranpos);
$after = substr($inprogresskey,$ranpos+1,$unshuffled-($ranpos+1));
$inprogresskey = $before.''.$after;
$unshuffled -= 1;
}
$cipher = $mixedkey;
$shift = strlen($address);
for ($j=0; $j<strlen($address); $j++)
{
if (strpos($cipher,$address{$j}) == -1 )
{
$chr = $address{$j};
$coded .= $address{$j};
}
else
{
$chr = (strpos($cipher,$address{$j}) + $shift) % strlen($cipher);
$coded .= $cipher{$chr};
}
}
$txt = "<script type=\"text/javascript\" language=\"javascript\">\n";
$txt .= "\ncoded = \"" . $coded . "\"\n" .
" key = \"".$cipher."\"\n".
" shift=coded.length\n".
" link=\"\"\n".
" for (i=0; i<coded.length; i++) {\n" .
" if (key.indexOf(coded.charAt(i))==-1) {\n" .
" ltr = coded.charAt(i)\n" .
" link += (ltr)\n" .
" }\n" .
" else { \n".
" ltr = (key.indexOf(coded.charAt(i))-
shift+key.length) % key.length\n".
" link += (key.charAt(ltr))\n".
" }\n".
" }\n".
"document.write(\"<a href='mailto:\"+link+\"'>\"+link+\"</a>\")\n" .
"\n".
"//-"."->\n" .
"<" . "/script><noscript>N/A" .
"<"."/noscript>";
return $txt;
}
And my Java code is:
private String encryptEmail(String email)
{
String address = email.toLowerCase();
String coded = "";
String unmixedkey = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.#";
String inprogresskey = unmixedkey;
String mixedkey = "";
int unshuffled = unmixedkey.length();
for (int i = 0; i <= unmixedkey.length(); i++) {
Random random = new Random();
int ranpos = random.nextInt(unshuffled - 1);
char nextchar = inprogresskey.charAt(ranpos);
mixedkey += nextchar;
String before = StringUtils.substring(inprogresskey, 0, ranpos);
String after = StringUtils.substring(inprogresskey, ranpos + 1, unshuffled - (ranpos + 1));
inprogresskey = before + "" + after;
unshuffled -= 1;
}
String cipher = mixedkey;
int shift = address.length();
for (int j = 0; j < address.length(); j++) {
int chr = -1;
if (StringUtils.indexOf(cipher, address.substring(j - 1, j)) == -1) {
coded += address.charAt(j);
} else {
chr = (cipher.charAt(j + shift)) % cipher.length();
coded += cipher.charAt(chr);
}
}
StringBuilder sb = new StringBuilder();
sb.append("<script type=\"text/javascript\">\n");
sb.append("var coded = \"" + coded + "\";\n");
sb.append("var key = \"" + cipher + "\";\n");
sb.append("var shift = coded.length;\n");
sb.append("var link = \"\";\n");
sb.append("for (i = 0; i < coded.length; i++) {\n");
sb.append(" if (key.indexOf(coded.charAt(i))==-1) {\n");
sb.append(" ltr = coded.charAt(i);\n");
sb.append(" link += (ltr);\n");
sb.append(" }\n");
sb.append(" else {\n");
sb.append(" ltr = (key.indexOf(coded.charAt(i))-shift+key.length) % key.length;\n");
sb.append(" link += (key.charAt(ltr));\n");
sb.append(" }");
sb.append("}");
sb.append("document.write(\"<a rel='nofollow' href='mailto:\" + link + \"'>\" + link + \"</a>\");\n");
sb.append("</script>");
return sb.toString();
}
Am I missing out on some functions (charAt, indexOf)?
Thanks
int ranpos = random.nextInt(unshuffled - 1);
atlast ranpos = 1
and you are doing nextInt(1 - 1)
char nextchar = inprogresskey.charAt(ranpos)
that's way above line gives you error
what you need to do is:
update your for loop for (int i = 0; i < unmixedkey.length(); i++)
and inside the loop add the below line of code
if(unshuffled==1)
{
ranpos = 1;
}
else {
ranpos = random.nextInt(unshuffled - 1);
}
The below is fully functional for loop code.
for (int i = 0; i < unmixedkey.length(); i++) {
Random random = new Random();
int ranpos=0;
if(unshuffled==1)
{
ranpos = 1;
}else{
ranpos = random.nextInt(unshuffled - 1);
}
char nextchar = inprogresskey.charAt(ranpos);
mixedkey += nextchar;
String before = StringUtils.substring(inprogresskey, 0, ranpos);
String after = StringUtils.substring(inprogresskey, ranpos + 1, unshuffled - (ranpos + 1));
inprogresskey = before + "" + after;
unshuffled -= 1;
}
I suspect that unshuffled is equal to 0 on the last time through the loop, and so charAt(-1) is failing.
You should take a look at Java IDEs like Eclipse and the debugger. Adding breakpoints will enable you to step through the code as it runs, and see the values of all variables, which would be the quickest way of solving this sort of issue in future.