Java split not working consistently - java
I have the following code below the output.
My issue is that the split function is not working correctly/consistently.
I want to split on each "$".
Reason being is that I want to parse the GGA and RMC data.
Before anyone spends to much time, is this the right way to do this?
My steps:
Read GPS data
Store sentence type (GGA, RMC) in variables that only store the most recent data
Parse those variables and pass to program and then database?
[
$GPGSV,,,,,,,,,*43
$GPRMC,055106.000,A,,N,,W,0.00,61.40,,,,A*4D]
[
$GPVTG,,,,,,T,,M,,,,K,A*3E
$GPGGA,055107.000,,N,,W,,,,M,-33.3,M,,0000*6T
$GPGLL,,N,,W,055107.000,A,A*44]
[
$GPRMC,055107.000,A,,N,,W,0.00,,,,,A*4F
$GPVTG,,,,,,T,,M,0.00,,0.0,,A*3E]
[
$GPGGA,055108.000,3,N,,W,1,09,0.9,,,M,,0000*62]
import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener; import jssc.SerialPortException;
import java.util.Arrays;
//import java.awt.List;
//import java.util.Base64;
//import java.io.BufferedReader;
//import java.io.ByteArrayInputStream;
//import java.io.InputStream;
//import java.io.InputStreamReader;
//import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.io.IOException;
import java.lang.*;
//import static java.util.Arrays.asList;
//import java.util.List;
//import java.util.stream.Collectors;
//import org.apache.commons.lang3.StringUtils;
public class test {
static List<String> datat = new ArrayList<String>();
static SerialPort serialPort;
public static void main(String[] args) {
serialPort = new SerialPort("COM1");
try {
serialPort.openPort();//Open ports
serialPort.setParams(4800, 8, 1, 0);//Set params
int mask = SerialPort.MASK_RXCHAR + SerialPort.MASK_CTS + SerialPort.MASK_DSR;//Prepare mask
serialPort.setEventsMask(mask);//Set mask
serialPort.addEventListener(new SerialPortReader());//Add SerialPortEventListener
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}
/*
* In this class must implement the method serialEvent, through it we learn about
* events that happened to our port. But we will not report on all events but only
* those that we put in the mask. In this case the arrival of the data and change the
* status lines CTS and DSR
*/
static class SerialPortReader implements SerialPortEventListener {
public void serialEvent(SerialPortEvent event) {
// if(event.isRXCHAR()){//If data is available
// if(event.getEventValue() < 577){//Check bytes count in the input buffer
//Read data, if 10 bytes available
try {
String getdata = serialPort.readString(event.getEventValue()+1);
String[] parts= getdata.split("$");
if(!datat.isEmpty()){
datat.set(datat.size() - 1, datat.get(datat.size() - 1) + parts[0]);
}
//data.set(data.size() - 1, data.get(data.size() - 1) + parts[0]);
for (int i=1; i<parts.length; i++) {
datat.add(parts[i]);
// System.out.println(Arrays.toString(parts));
}
String[] data2 = datat.toArray(new String[0]);
for(String s : data2)
{
data2 = s.split("$");
List<String> data3 = Arrays.asList(data2);
// int testing = data3.size();
System.out.println(data3);
}
}
catch (SerialPortException ex) {
}
}
}
}
The split function takes a regular expression, not a string, You are using a special character in a regular expresion ($) then you need to scape that character
String s= "$........$...$....";
String[] data2= s.split("\\$");
Related
Parse .prn file to html
I am trying to convert a .prn file to html. But due to file format, I am not able to parse in a way I want. I tried many approaches. some of are: package main; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class PrnToHtml { public static void main(String[] args) { try (BufferedReader reader = new BufferedReader(new FileReader(".\\Workbook2.prn")); FileWriter writer = new FileWriter("output_prn.html")) { writer.write("<html><body><h3>PRN to HTML</h3><table border>\n"); String currentLine; while ((currentLine = reader.readLine()) != null) { writer.write("<tr>"); for(String field: currentLine.split("\\s{2,}")) // "\\s{2,}" writer.write("<td>" + field + "</td>"); writer.write("</tr>\n"); } writer.write("</table></body></html>\n"); } catch (IOException e) { e.printStackTrace(); } } } Output of this will be html page looks like this: prn file\data looks like this: Other this I tried to read this is: package main; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; public class PRNToHtml { private static final String DILIM_PRN = " "; private static final Pattern PRN_SPLITTER = Pattern.compile(DILIM_PRN); public static void main(String[] args) throws URISyntaxException, IOException { try (#SuppressWarnings("resource") Stream<String> lines = new BufferedReader(new FileReader(".\\Workbook2.prn")).lines()) { List<String[]> inputValuesInLines = lines.map(l -> PRN_SPLITTER.split(l)).collect(Collectors.toList()); for (String[] strings : inputValuesInLines) { for (String s : strings) { System.out.print(s.replaceAll("\\s+", "") + " "); } System.out.println(); } } } } output of this is the exactly same looking in prn data file. But when I am trying to embed in html, it is looking weird like this: Help will be appreciated. Thank you :)
Counting instances of letter sequences
The purpose of this code is to count the instances of letters that occur in sequence, using HashMaps, and Streams. I've run into the problem of my System.out.print(results) is printing [is=3, imple=2, it=1] to the console, but my junit is saying "expected <[is=3 imple =2 it=1]> but was <[]>. The code prints out [is=3, imple=2, it=1] but it doesn't seem to actually be updating this out into memory. Any tips or advice on what I should do? Thank you so much! import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.List; import java.util.ArrayList; import java.util.Collections; public class WordCount { protected Map<String, Integer> counts; static Scanner in= new Scanner(System.in); public WordCount(){ counts = new HashMap<String,Integer>(); } public Map getCounts(){ return counts; } public int parse(Scanner in, Pattern pattern){ int counter=0; while (in.hasNext()) { // get the next token String token = in.next(); // match the pattern within the token Matcher matcher = pattern.matcher(token); // process each match found in token (could be more than one) while (matcher.find()) { // get the String that matched the pattern String s = matcher.group().trim(); // now do something with s counter=counts.containsKey(s) ? counts.get(s):0; counts.put(s,counter+1); } } return counter; } public void report(PrintStream printstream){ List<Map.Entry<String, Integer>> results = new ArrayList<Map.Entry<String, Integer>>(); for(Map.Entry<String, Integer> entry: counts.entrySet()){ results.add(entry); Collections.sort(results,Collections.reverseOrder(Map.Entry.comparingByValue())); results.toString(); } System.out.println(results); // The main problem is this outputs [is=3, imple=2, it=1] but the junit doesn't pass. } } //Test Cases import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.Scanner; import java.util.regex.Pattern; import junit.framework.TestCase; public class TestWordCount extends TestCase { public void test_WordCount_parse() { WordCount wc = new WordCount(); Scanner in = new Scanner("this is a simple test, but it is not simple to pass"); Pattern pattern = Pattern.compile("[i][a-z]+"); wc.parse(in, pattern); assertEquals((Integer)3, wc.getCounts().get("is")); assertEquals((Integer)2, wc.getCounts().get("imple")); assertEquals((Integer)1, wc.getCounts().get("it")); } public void test_WordCount_report() { WordCount wc = new WordCount(); Scanner in = new Scanner("this is a simple test, but it is not simple to pass"); Pattern pattern = Pattern.compile("[i][a-z]+"); wc.parse(in, pattern); ByteArrayOutputStream output = new ByteArrayOutputStream(); wc.report(new PrintStream(output)); String out = output.toString(); String ls = System.lineSeparator(); assertEquals("is=3_imple=2_it=1_".replace("_", ls), out); }
`public void report(PrintStream printstream)` In this method you do not print anything to printstream. Try adding printstream.print(results); to this method. Note that, although System.out is a PrintStream itself, it's a different stream that is bound to the console.
How to get values from grid using regex in java
I'm working on resume parser and i can get some of data i.e company details from text but not getting if it is kept in a grid or table import java.io.FileNotFoundException; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JOptionPane; import org.apache.poi.xwpf.extractor.XWPFWordExtractor; import org.apache.poi.xwpf.usermodel.XWPFDocument; public class CmpnyNameex { public static void main(String[] args)throws IOException { String text=""; String name=""; XWPFDocument msDocx = new XWPFDocument(new FileInputStream("A:\\Resumes\\Anwesh.docx")); XWPFWordExtractor extractor = new XWPFWordExtractor(msDocx); text = extractor.getText(); } catch(FileNotFoundException ex){ex.printStackTrace(); JOptionPane.showMessageDialog(null,"The system cannot find the file specified file it may be because of old file format","Error",JOptionPane.ERROR_MESSAGE); } String rx13="(?<=Have been associated with).*.(.*Ltd?)"; Pattern p1 = Pattern.compile(rx13); Matcher found1 = p1.matcher(text); while(found1.find()) { name= found1.group(0); } } }
Java NumberFormatException Error
Hey guys this is a code where I am trying to make java read a text file.I have some float values I want the program to read but it is throwing a Number Format Exception.The text file "h.txt" is a notepad file that is encoded in ANSI. package javaapplication1; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.text.NumberFormat; import java.util.Locale; import java.lang.*; public class JavaApplication1 { int[][] adj=new int[50][50]; String line; public JavaApplication1(int[][] adj) { // TODO Auto-generated constructor stub this.adj=adj; } public void fileinput2() { try { BufferedReader file=new BufferedReader(new FileReader("h.txt")); try { while((line=file.readLine())!=null){ String[] s=line.split("\t+") for(int i=0;i<s.length;i++) { float x=Float.valueOf(s[i].trim()); System.out.print(x+" "); } System.out.println(); } } catch (NumberFormatException | IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { { int[][] adj=new int[50][50]; JavaApplication1 m=new JavaApplication1(adj); m.fileinput2(); } } } } The h.txt is a text file whose first line is 0 0.25 3 Java is giving me a NumberFormatException:- java.lang.NumberFormatException: For input string: "0.25" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at javaapplication1.JavaApplication1.fileinput2(JavaApplication1.java:35) at javaapplication1.JavaApplication1.main(JavaApplication1.java:70) Kindly help me out.Thanks :)
0.25 is not valid Integer value hence its failing to parse value use appropiate datatype like. double or float for your requirement. i.e. Float.parseFloat(variable)
Change your split line to: String[] s = line.split(" "); And change your for loop to: for (String string : s) { if (!string.isEmpty()) { float x = Float.parseFloat(string); System.out.print(x + " "); } }
Java outputs garbage?
import java.io.BufferedReader; import java.io.CharArrayReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; public class Main { /** * #param args * #throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); PrintWriter output = new PrintWriter(System.out); String st=""; String st1; String st2; while((st1 = input.readLine()) != null) { char[] x1 = st1.toCharArray(); st2 = input.readLine(); char[] x2 = st2.toCharArray(); Arrays.sort(x1); Arrays.sort(x2); st1 = x1.toString(); st2 = x2.toString(); output.print(st1.charAt(0)); output.flush(); } } } input can be any two strings. the problem is that this code outputs garbage value, so, what is the wrong with this ? NOTE: this is a partial code debugging, the rest of the code is not attached.
x1.toString() calls the toString() method on the x1 array. Which returns something like [C#33909752. Which is the value returned by the Object.toString() method. [ - it's an array C - of type `char` 33909752 - on memory address `33909752` If you want to build a String based on the characters in array x1 you must use new String(x1).