I have a string = "1.515 53.11 612.1 95.1 ; 0 0 0 0"
I'm tring to parse it via this code:
public class SendThread implements Runnable {
public void run()
{
socket = null;
BufferedReader in;
while (true)
{
// Loop until connected to server
while (socket == null){
try{
socket = new Socket ("192.168.137.1", 808);
}
catch (Exception e) {
socket = null;
//Log.d("Connection:", "Trying to connect...");
}
try {
Thread.sleep(30);
} catch (Exception e) {}
}
// Get from the server
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.d("Connection: ", "connected");
String line = null;
while ((line = in.readLine()) != null) {
Log.d("Socket:", line);
NumberFormat nf = new DecimalFormat ("990,0");
String[] tokens = null;
String[] tempData = null;
String[] windData = null;
try {
tokens = line.split(";");
tempData = tokens[0].trim().split(" ");
windData = tokens[1].trim().split(" ");
} catch (Exception error)
{
Log.d("Parsing error:", error+"");
}
for (int i = 0; i < currentTemp.length; i++)
currentTemp[i] = (Double) nf.parse(tempData[i]);
for (int i = 0; i < currentWind.length; i++)
currentWind[i] = (Double) nf.parse(windData[i]);
//Toast.makeText(getApplicationContext(), "Received data:", duration)
for (int i = 0; i < currentTemp.length; i++){
Log.d("Converted data: currentTemp["+i+"] = ", currentTemp[i]+"");
}
for (int i = 0; i < currentWind.length; i++){
Log.d("Converted data: currentWind["+i+"] = ", currentWind[i]+"");
}
}
socket = null;
Log.d("Connection: ", "lost.");
}
catch (Exception e) {
socket = null;
Log.d("Connection: ", "lost.");
Log.d("Connection:", e+"");
}
}
}
}
Bad code :( But I don't know better way to hold the socket connection :)
I always get "java.text.ParseException: Unparseable number". How to fix it?
tokens, tempData, windData are String[]
Apart from what others said, I bet when you do
windData = tokens[1].split(" ");
you get
windDate = {"","0","0","0","0"}
and try to parse the first element as Number.
Try to do :
try {
tokens = line.split(";");
tempData = tokens[0].trim().split(" ");
windData = tokens[1].trim().split(" ");
} catch (Exception error)
{
Log.d("Parsing error:", error+"");
}
You don't need to escape the semicolon. Try just doing:
try {
tokens = line.split(";");
tempData = tokens[0].split(" ");
windData = tokens[1].split(" ");
} catch (Exception error)
{
Log.d("Parsing error:", error+"");
}
I suspect your parse error is because of the trailing space after the 95.1 in your input string. As it is, your tempData array will have 5 values, the last being ''. Trying to parse that as a number will give you that exception.
Hmm, your code (as posted) does not generate this exception. Secondly, "\\;" is redundant, you can write ";"
You could use, string tokenizer for that.
String s = "1.515 53.11 612.1 95.1 ; 0 0 0 0";
StringTokenizer tokenizer = new StringTokenizer(s,";");
while(tokenizer.hasMoreElements()){
StringTokenizer numberTokenize = new StringTokenizer(tokenizer.nextToken());
while(numberTokenize.hasMoreElements()) {
System.out.println(numberTokenize.nextElement());
}
}
Try using the \s in your split for whitespace; e.g. tempData = tokens[0].split("\s"); ... it represents a whitespace character.
Related
EDIT: editted for clarity as to what I'm having trouble with. I'm not getting the right responses as its counting dupes. I HAVE to use RegEx, can use tokenizer however but I did not.
What I am trying to do here is, there is 5 input files. I need to calculate how many "USER DEFINED VARIABLES" there are. Please ignore the messy code, I'm just learning Java.
I replaced: everything within ( and ), all non-word characters, any statements such as int, main etc, any digit with a space infront of it, and any blank space with a new line then trim it.
This leaves me with a list that has a variety of strings which I will match with my RegEx. However, at this point, how make my count only include unique identifiers?
EXAMPLE:
For example, in the input file I have attached beneath the code, I am receiving
"distinct/unique identifiers: 10" in my output file, when it should be "distinct/unique identifiers: 3"
And for example, in the 5th input file I have attached, I should have "distinct/unique identifiers: 3" instead I currently have "distinct/unique identifiers: 6"
I cannot use Set, Map etc.
Any help is great! Thanks.
import java.util.*
import java.util.regex.*;
import java.io.*;
public class A1_123456789 {
public static void main(String[] args) throws IOException {
if (args.length < 1) {
System.out.println("Wrong number of arguments");
System.exit(1);
}
for (int i = 0; i < args.length; i++) {
FileReader jk = new FileReader(args[i]);
BufferedReader ij = new BufferedReader(jk);
FileWriter fw = null;
BufferedWriter bw = null;
String regex = "\\b(\\w+)(\\s+\\1\\b)+";
Pattern p = Pattern.compile("[_a-zA-Z][_a-zA-Z0-9]{0,30}");
String line;
int count = 0;
while ((line = ij.readLine()) != null) {
line = line.replaceAll("\\(([^\\)]+)\\)", " " );
line = line.replaceAll("[^\\w]", " ");
line = line.replaceAll("\\bint\\b|\\breturn\\b|\\bmain\\b|\\bprintf\\b|\\bif\\b|\\belse\\b|\\bwhile\\b", " ");
line = line.replaceAll(" \\d", "");
line = line.replaceAll(" ", "\n");
line = line.trim();
Matcher m = p.matcher(line);
while (m.find()) {
count++;
}
}
try {
String s1 = args[i];
String s2 = s1.replaceAll("input","output");
fw = new FileWriter(s2);
bw = new BufferedWriter(fw);
bw.write("distinct/unique identifiers: " + count);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();
}
if (fw != null) {
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
//This is the 3rd input file below.
int celTofah(int cel)
{
int fah;
fah = 1.8*cel+32;
return fah;
}
int main()
{
int cel, fah;
cel = 25;
fah = celTofah(cel);
printf("Fah: %d", fah);
return 0;
}
//This is the 5th input file below.
int func2(int i)
{
while(i<10)
{
printf("%d\t%d\n", i, i*i);
i++;
}
}
int func1()
{
int i = 0;
func2(i);
}
int main()
{
func1();
return 0;
}
Try this
LinkedList dtaa = new LinkedList();
String[] parts =line.split(" ");
for(int ii =0;ii<parts.length;ii++){
if(ii == 0)
dtaa.add(parts[ii]);
else{
if(dtaa.contains(parts[ii]))
continue;
else
dtaa.add(parts[ii]);
}
}
count = dtaa.size();
instead of
Matcher m = p.matcher(line);
while (m.find()) {
count++;
}
Amal Dev has suggested a correct implementation, but given the OP wants to keep Matcher, we have:
// Previous code to here
// Linked list of unique entries
LinkedList uniqueMatches = new LinkedList();
// Existing code
while ((line = ij.readLine()) != null) {
line = line.replaceAll("\\(([^\\)]+)\\)", " " );
line = line.replaceAll("[^\\w]", " ");
line = line.replaceAll("\\bint\\b|\\breturn\\b|\\bmain\\b|\\bprintf\\b|\\bif\\b|\\belse\\b|\\bwhile\\b", " ");
line = line.replaceAll(" \\d", "");
line = line.replaceAll(" ", "\n");
line = line.trim();
Matcher m = p.matcher(line);
while (m.find()) {
// New code - get this match
String thisMatch = m.group();
// If we haven't seen this string before, add it to the list
if(!uniqueMatches.contains(thisMatch))
uniqueMatches.add(thisMatch);
}
}
// Now see how many unique strings we have collected
count = uniqueMatches.size();
Note I haven't compiled this, but hopefully it works as is...
I have a text file which has text as follows:
emVersion = "1.32.4.0";
ecdbVersion = "1.8.9.6";
ReleaseVersion = "2.3.2.0";
I want to update the version number by taking the input from a user if user enter the new value for emVersion as 1.32.5.0 then
emVersion in text file will be updated as emVersion = "1.32.5.0";
All this I have to do using java code. What I have done till now is reading text file line by line then in that searching the word emVersion if found the broken line into words and then replace the token 1.32.4.0 but it is not working because spaces are unequal in the file.
Code what i have written is :
public class UpdateVariable {
public static void main(String s[]){
String replace = "1.5.6";
String UIreplace = "\""+replace+"\"";
File file =new File("C:\\Users\\310256803\\Downloads\\setup.rul");
Scanner in = null;
try {
in = new Scanner(file);
while(in.hasNext())
{
String line=in.nextLine();
if(line.contains("svEPDBVersion"))
{
String [] tokens = line.split("\\s+");
String var_1 = tokens[0];
String var_2 = tokens[1];
String var_3 = tokens[2];
String var_4 = tokens[3];
String OldVersion = var_3;
String NewVersion = UIreplace;
try{
String content = IOUtils.toString(new FileInputStream(file), StandardCharsets.UTF_8);
content = content.replaceAll(OldVersion, NewVersion);
IOUtils.write(content, new FileOutputStream(file), StandardCharsets.UTF_8);
} catch (IOException e) {
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//---this code changes each version's values but the is a option to keep the old value.
Scanner in = new Scanner(System.in);
File file = new File("versions.txt");
ArrayList<String> data = new ArrayList<>();
String[] arr =
{
"emVersion", "ecdbVersion", "releaseVersion"
};
String line = "";
String userInput = "";
try (BufferedReader br = new BufferedReader(new FileReader(file));)
{
while ((line = br.readLine()) != null)
{
data.add(line);
}
for (int i = 0; i < arr.length; i++)
{
System.out.println("Please enter new " + arr[i] + " number or (s) to keep the old value.");
userInput = in.nextLine();
line = data.get(i);
String version = line.substring(0, line.indexOf(" "));
if (arr[i].equalsIgnoreCase(version))
{
arr[i] = line.replace(line.subSequence(line.indexOf("= "), line.indexOf(";")), "= \"" + userInput + "\"");
}
if (userInput.equalsIgnoreCase("s"))
{
arr[i] = line;
}
}
PrintWriter printWriter = new PrintWriter(new FileWriter(file, false));
printWriter.println(arr[0]);
printWriter.println(arr[1]);
printWriter.println(arr[2]);
printWriter.close();
}
catch (Exception e)
{
System.out.println("Exception: " + e.getMessage());
}
Use regular expression eg:- line.trim().split("\s*=\s*"); . If it does not work please let me know , i will provide you complete solution.
Hello all I am trying to scan the bottom 6 lines of a text file and display them in a JOptionPane.showMessageDialog currently it is being displayed as [line7, line6, line5, line4, line3, line2] I would prefer it to be displayed as a vertical list instead of the comma seperator.
ArrayList<String> bandWidth = new ArrayList<String>();
FileInputStream in = null;
try {
in = new FileInputStream("src/list.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String tmp;
try {
while ((tmp = br.readLine()) != null)
{
bandWidth.add(tmp);
if (bandWidth.size() == 7)
bandWidth.remove(0);
}
} catch (IOException e) {
e.printStackTrace();
}
ArrayList<String> reversedSix = new ArrayList<String>();
for (int i = bandWidth.size() - 1; i >= 0; i--)
reversedSix.add(bandWidth.get(i));
JOptionPane.showMessageDialog(null,bandWidth,null,JOptionPane.INFORMATION_MESSAGE);
Try looping the ArrayList and produce a String with new line characters:
String result = "";
for (int i = 0; i < bandWidth.size(); i++)
{
result += bandWidth.get(i) + "\n";
}
JOptionPane.showMessageDialog(null,result ,null,JOptionPane.INFORMATION_MESSAGE);
Note: if this is outputting HTML, then use <br \> instead of \n.
I have socket application that i use for communication with a device.
When i open socket i can read status outputs from the machine.
Machine sends some data which is separated by comma ',' and i need to parse only numbers.
The problem is when i parse the data i recieve numbers but i also recieve "empty" strings.
Here is my code:
void startListenForTCP(String ipaddress) {
Thread TCPListenerThread;
TCPListenerThread = new Thread(new Runnable() {
#Override
public void run() {
Boolean run = true;
String serverMessage = null;
InetAddress serverAddr = null;
BufferedWriter out = null;
int redni = 0;
try {
Socket clientSocket = new Socket(ipaddress, 7420);
try {
mc.pushNumbers("Connection initiated... waiting for outputs!"
+ "\n");
char[] buffer = new char[2];
int charsRead = 0;
out =
new BufferedWriter(new OutputStreamWriter(
clientSocket.getOutputStream()));
BufferedReader in =
new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
while ((charsRead = in.read(buffer)) != -1) {
String message = new String(buffer).substring(0, charsRead);
if (message.equals("I,")) {
mc.pushNumbers("\n");
} else {
String m = message;
m = m.replaceAll("[^\\d.]", "");
String stabilo = m;
int length = stabilo.length();
String result = "";
for (int i = 0; i < length; i++) {
Character character = stabilo.charAt(i);
if (Character.isDigit(character)) {
result += character;
}
}
System.out.println("Result:" + m);
}
}
} catch (UnknownHostException e) {
mc.pushNumbers("Unknown host..." + "\n");
} catch (IOException e) {
mc.pushNumbers("IO Error..." + "\n");
} finally {
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
mc.pushNumbers("Connection refused by machine..." + "\n");
}
}
});
TCPListenerThread.start();
}
And the System.out.println(); returns this:
Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:26Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:13
Result:Result:Result:Result:Result:Result:Result:Result:Result:
I just don't know why I can't parse only numbers, there is probably something that machine sends and it isn't parsed by m = m.replaceAll("[^\\d.]", "");
You're building your String incorrectly. It should be:
String message = new String(buffer, 0, bytesRead);
where 'bytesRead' is the count returned by the read() method. It's a byte count, not a char count.
The code is suppose to read information from a file, create a object using that information, and then adding it to an ArrayList called servers.
try {
BufferedReader br = new BufferedReader(new InputStreamReader(openFileInput(MainActivity.FILE_SERVERS)));
String line = "";
while ((line = br.readLine()) != null) {
String name = "";
String ip = "";
String port = "";
String checkFrequency = "";
int counter = 1;
boolean alert = true;
for (String value : line.split(",")){
if (counter == 1){
name = value;
}else if (counter == 2){
ip = value;
}else if (counter == 3){
port = value;
}else if (counter == 4){
checkFrequency = value;
}else if (counter == 5){
alert = Boolean.parseBoolean(value);
}
counter++;
}
MCServer server = new MCServer(name, ip, port, checkFrequency, alert);
servers.add(server);
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Example line of what is stored in file:
Name,199.99.99.99,80,60,true
Would there be a better way to retrieve that information to be able to store it in the correct variable without using a loop with a counter the way shown above?
What about:
try (BufferedReader br = new BufferedReader(
new InputStreamReader(openFileInput(MainActivity.FILE_SERVERS)))) {
String line = null; // start with null in case there is no line
while ((line = br.readLine()) != null) {
String[] tokens = line.split(",");
MCServer server =
new MCServer(tokens[0], tokens[1], tokens[2], tokens[3],
Boolean.parseBoolean(tokens[4]));
servers.add(server);
}
}
You can just ignore the counter and use directly the tokens, but you should at least be sure there are enough tokens:
try
{
BufferedReader br = new BufferedReader(new InputStreamReader());
String line = null;
String[] tokens;
while ((line = br.readLine()) != null) {
tokens = line.split(",");
MCServer test = new MCServer(tokens[0],tokens[1],tokens[2],tokens[3],Boolean.valueOf(tokens[4]));
}
}
catch (IndexOutOfBoundsException e) { // <- be sure to catch this
// not enough elements in array
}
In addition you are passing strings as IP addresses and port, they are string but they should be checked against being convertible, so you could have Integer.valueOf(tokens[2]) for example just to raise a NumberFormatException in case.
Try this
try {
BufferedReader br = new BufferedReader(new InputStreamReader(openFileInput(MainActivity.FILE_SERVERS)));
String line = "";
while ((line = br.readLine()) != null) {
String name = "";
String ip = "";
String port = "";
String checkFrequency = "";
int counter = 1;
boolean alert = true;
String s[] = line.split(",");
name = s[0];
ip = s[1];
port = s[2];
checkFrequency= s[3];
alert = s[4];
MCServer server = new MCServer(name, ip, port, checkFrequency, alert);
servers.add(server);
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I've revised your code a bit:
try {
BufferedReader br = new BufferedReader(new InputStreamReader(openFileInput(MainActivity.FILE_SERVERS)));
String line;
while ((line = br.readLine()) != null) {
String[] lineSplitted = line.split(",");
String name = lineSplitted[0];
String ip = lineSplitted[1];
String port = lineSplitted[2];
String checkFrequency = lineSplitted[3];
boolean alert = Boolean.parseBoolean(lineSplitted[4]);
MCServer server = new MCServer(name, ip, port, checkFrequency, alert);
servers.add(server);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
Changes:
initialising the variables and then setting them is redundant, you never access them without setting them beforehand, so if you have your line splitted in the the first place you can initialise them with the values right away
for cycle is unnecessary if you're working with a single array each time, just access the correct elements of the array
catch blocks can be collapsed; IOException covers FileNotFoundException