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);
}
}
Related
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 =
.
.
.
I am reading data from a txt file. I want to create new objects from every ten lines and "." indicates that the current object doesn't have any more data lines (I work with two types of object("Nemfuggetlen" and "fuggetlen"), "fuggetlen" has 9 and "Nemfuggetlen" has 7 lines, "." separates their data lines).
The problem is: when I read two "Nemfuggetlen" objects in a row, it works fine, but if I read "fuggetlen" after "Nemfuggetlen" it makes "-------" to the next object first data lines, when it shouldn't. For "Nemfuggetlen" object it should fill the last 3 lines of "adatok" string array with "-------" and step to the next object.
int sorokszama = 0;
input.mark(300);
while((s = input.readLine()) !=null){
sorokszama++;
System.out.println("Sorok szama : " + sorokszama);
input.reset();
for(int h = 0; h < sorokszama/10; h++){
for(int i = 0;(s = input.readLine()) !=null; i++) {
if(i < 10){
if(!(".".equals(s))) {
adatok[i] = s;
System.out.println(adatok[i]);
}
else {
adatok[i] = "-------";
System.out.println(adatok[i]);
break;
}
}
}
if("Ferfi".equals(adatok[2])){
nem = true;
}
else {
nem = false;
}
if("Van".equals(adatok[4])){
tamogato = true;
}
else{
tamogato = false;
}
if("-------".equals(adatok[7])){ //A kepviselo nem fuggetlen
k = new Nemfuggetlen(adatok[0], Integer.parseInt(adatok[1]), nem, adatok[4], new Kerulet (Integer.parseInt(adatok[5])), adatok[6]);
}
if("-------".equals(adatok[9])){ // A kepviselo fuggetlen
k = new Fuggetlen(adatok[0], Integer.parseInt(adatok[1]), nem, adatok[4], new Kerulet (Integer.parseInt(adatok[5])),tamogato, adatok[7], Integer.parseInt(adatok[8]));
}
kepviselok.add(k);
//System.out.println(kepviselok.get(0));
}
System.out.println("Kepviselok szama : " + sorokszama/10);
for(int i = 0; i < kepviselok.size(); i++) {
System.out.println((i+1) + ". tag : " + kepviselok.get(i));
}
input.close();
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.
Hi Guys I am writing a code that reads a text file in this format:
City |First Name| Second Name|Last Name|
The output I currently have is :
Column 1 is 17--------City
Column 2 is 10--------First Name
Column 3 is 12--------Second Name
Column 4 is 9---------Last Name
I need the Begin Position Also Of each Field in the Text File for example:
Column 1 is 17--------City : Position 1
Column 2 is 10--------First Name: Position 18
Column 3 is 12--------Second Name: Position 31
Column 4 is 9---------Last Name: Position 44
Here Is the Code I currently Have. Is there a way to achieve This?
package stanley.column.reader;
import java.io.*;
public class StanleyColumnReader {
public static void main(String[] args) throws IOException {
System.out.println("Developed By Stanley Mungai");
File f = new File("C:/File/");
if (!f.exists()) {
f.createNewFile();
} else {
f.delete();
}
String [] files = f.list();
for (int j = 0; j < files.length; j++){
FileInputStream fs = new FileInputStream("C:/File/" + files[j]);
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
String result = "_result";
BufferedWriter is = new BufferedWriter(new FileWriter("C:/File/" + files[j] + result + ".txt"));
for (int i = 0; i < 0; i++) {
br.readLine();
}
String line = br.readLine();
String[] split = line.split("|");
for (int i = 0; i < split.length; i++) {
int k = i + 1;
System.out.println("Calculating the size of field " + k );
is.write("Column " + k + " is " + split[i].length());
is.flush();
is.newLine();
}
}
System.out.println("Success");
System.out.println("Output Saved to C:/File");
}
}
You could do that with a bit more advanced regexp group matching and get the group start index. But might be overkill and too advanced considering the question.
But a quick simple way in your case that might work is to just use indexOf on the line.
That is change your output to include:
" Position "+(line.indexOf(split[i])+1)
As long as a last name, first name and city aren't repeated on the same line...
You hardly need to flush on each line by the way, I suggest to move it outside the loop.
The regexp solution:
//first declare the pattern once in the class
static final Pattern pattern = Pattern.compile("\\s*(.*?)\\s*\\|");
...
//instead of the split loop:
String line = "City |First Name| Second Name|Last Name| Foo |Bar |"; //br.readLine();
Matcher matcher = pattern.matcher(line);
int column = 1;
while (matcher.find(column == 1 ? 0 : matcher.end())) {
String match = matcher.group(1);
System.out.println("Column " + column + " is " + match.length() + "---" + match + ": Position " + (matcher.start() + 1));
column++;
}
Possibly, depending on the exact position you want, you might want to change (matcher.start()+1) to (matcher.start(1)+1)
IS this an assignment? Please tag it properly.
You haven't said whether the delimiters are "|" in the data too but seeing your code, I am assuming it is.
What I don't understand is how the position you mentioned for Column 3 is 31 and column 4 is 44? Column 3 should be 10+17+1 =28 and column 4 should be 10+17+12+1=40. If I am getting it wrong, you need to post your original data too.
String[] split = line.split("|");
int pos=1; //initial position
for (int i = 0; i < split.length; i++) {
System.out.println("Calculating the size of field " + (i+1));
is.write("Column " + (i+1) + " is " + pos+" : Position "+pos);
pos=pos+split[i].length+1; //starting position for next column data
is.flush();
is.newLine();
}
Or you could find position by using indexOf method : line.indexOf(split[i])+1
If I understand what you need. Maybe you can use the indexOf method. This brings you the first coincidence. After finding this, change the pipe for something different and call indexOf pipe in the next iteration again.
String line = br.readLine();
for (int i = 0; i < split.length; i++) {
System.out.println("Calculating the position " + line.indexOf("|") );
line[line.indexOf("|")] = ",";
}
This is what it does:
2,
4,
6,
8,
10
I would like for it to be horizontal:
2, 4, 6, 8, 10
try {
PrintWriter fout = new PrintWriter(new BufferedWriter(new FileWriter("numbers.dat")));
for(int i = start; i <= 100; i = i + 2) {
fout.println(i+",");
}
Another attempt
for(int i = start; i <= 100; i += 2)
System.out.print(i + (i > 98 ? "\n" : ", "));
In the write() method:
for(int i = start; i <= 100; i = i + 2) {
if (i > start) {
fout.print(",");
}
fout.println(i);
}
Then when you call output(), it will display as comma separated list. And for screen display
while((outputline = fin.readLine()) != null) {
System.out.print(outputline + " ");
}
System.out.println();
Alternatively, skip saving the comma in the file and displaying will be as follows
int count = 0;
while((outputline = fin.readLine()) != null) {
if (count > 0)
System.out.print(", ");
System.out.print(outputline);
count++;
}
System.out.println();
If you mean to do it on printing to your .dat file:
for(int i = start; i <= 100; i = i + 2) {
fout.print(i);
if(i < 100) {
fout.print(", ");
} else {
fout.println();
}
}
If it is when printing to the system output after reading your file, try this:
try {
BufferedReader fin = new BufferedReader(new FileReader("numbers.dat"));
String outputline = "";
StringBuilder result = new StringBuilder();
while((outputline = fin.readLine()) != null) {
result.append(outputline).append(", ");
}
int length = result.length();
result.delete(length - 2, length);
System.out.println(result);
fin.close();
}
This uses a StringBuilder to build up your result and then removes the last , when it is done.
Here is a very basic example of what you could do:
int max=11;
for(int i = 0; i < max; i += 2){
System.out.print(i);
if(i < max-2){
System.out.print(", ");
}
}
fout.println(i + ", ");
System.out.println(outputline + ", ");
This will give you commas after all the numbers but it looks like you don't need one after the final number.
You will have to remove the last comma either by using indexOf or checking for the last iteration of your loop.