Java: Store specific part of string to an array - java

I'm using inputstreamer to retrieve the output of a shell command running continuously providing an output.
I've managed to isolate a part of the shell output by printing it here: System.out.println(inputStr.substring(inputStr.lastIndexOf(" ")+1));
However, I'd like to store the output in either of two arrrays, depending on the expression of the shell output.
Say we have two shell outpust that follows this syntax: IP 192.168.0.12.4588 > 212.98.120.24.443 psx 4488 as the first one, and the opposite: IP 212.98.120.24.443 > 192.168.0.12.4588 psx 12
From the above print, I can isolate and print both 4488 as well as 12. But if 192.168.0.x.x is the first IP, the value 4448 to be stored in a specific array. Likewise, if > 192.168.0.x.x is on the other side, I want to store the value 12 in a different array.
How would I go about that?

You could do something like this:
public static void main(String[] args)
{
String temp = "IP 212.98.120.24.443 > 192.168.0.12.4588 psx 12";
if(temp.matches(".*192\\.168\\.0\\..*>.*"))
{
System.out.println("1st");
//your code here
}
else if(temp.matches(".*>.*192\\.168\\.0\\..*"))
{
System.out.println("2nd");
//your code here
}
}

Related

Pattern.quote not working for \037 character when it is passed to a spark program via oozie

I am passing ASCII character \037 (to be used as a field delimiter) to a spark program via oozie. In my oozie property file i have given the value like,
delimiterArg=\\\037
In my spark program, I am trying to split the line as below
public static void main(String[] args) {
String column1 = line.split(Pattern.quote(args[0]));
}
But it is not working. But if I use without Pattern.quote, it is working,
public static void main(String[] args) {
String column1 = line.split(args[0]));
}
I would like to use Pattern.quote() as it will handle special characters like Pipe (|). Any suggestions?
EDIT:
Here is my complete scenario
I need to pass the delimiter \037 to spark program which is triggered via oozie job.I will use this as a field delimiter for processing data.
In order to pass \037 to spark program I have to give \\037 in my job.properties file.
Now that i have received this value in my spark program and trying to split the input string. Issue is that
String column1 = line.split(Pattern.quote(args[0])); // Not Working
String column1 = line.split(args[0])); // Working
I suspect that the String you are passing to Pattern.quote() is not the string you intended.
Here is a test program:
public class MVCE
{
public static void main(String[] argv)
{
final String line = "ab\037cd\037ef";
final String[] columns = line.split( Pattern.quote("\037") );
System.out.println(Arrays.toString(columns));
}
}
The output from this program is:
[ab, cd, ef]
I would debug your situation by adding a print statement to the beginning of your main() method so that you can see exactly what string is passed as args[0]. I know nothing of oozie, but I do notice you show \\037 as the value in its file. Perhaps you have multiple levels of programs interpreting the bytes in various ways such that the five bytes (if it is ASCII or UTF-8) in your configuration file does not result in the intended/expected four Unicode characters in args[0].

How to split a "\n" in java when read the data from mysql?

In my Java code I define a string String strExample='abc\ndef'. Now I want to split it. So I try to get the length of the string.
int strArrlength=strExample.split("\n").length
The result is 2.
But when I try to write the strExample in to mysql table, and then read it from the table, in the same code I get the length is 1.
My development environment is Windows 8.1, and the database is installed in CentOS 6.5.
What's wrong? I've tried to change the code like:
strExample.split("\\n"),split("\r\n"),split("\n+"),split("\\r?\\n")
but all of them return 1;
Here is my test,but still not work.
private final static String mHexStr1="5468697320697320612074657374EFBC815C6E204F6E6C792061207465737421";
public static void main(String[] args) {
String testStr=hexStr2Str(mHexStr1);
System.out.print(testStr+";"+testStr.split("\\n").length);//return 1
String abc="This is a test!\n Only a test!";
System.out.println(abc+";"+abc.split("\n").length);//return 2
}
You don't need to select HEX content.Just replace the data \\n with \n which is read from mysql.

Reading values from user in C#

This code works fine, if the user enters the numbers in separate lines
i.e.
10
12
Result is : 22
However, when I try to input this there is an error.
10 12
Now, I know console.readline() reads the entire line, and obviously the space isn't an int and so I get the error. However, when I used to code in C, there was scanf function, which by simply specifying the datatype to expect from user, could run for both the cases. Also, I think JAVA's scanner.nextInt() would have not allowed such troubles. Is there any simple way to ask c# to read data separated by spaces, or lines in the same manner? This is the only reason why I never used c# in coding competitions. I simply don't understand how to solve this problem.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test
{
class Program
{
static void Main(string[] args)
{
int result=0,a, b;
a = int.Parse(Console.ReadLine());
b = int.Parse(Console.ReadLine());
result = a + b;
Console.WriteLine("The result is {0}", result);
Console.ReadKey();
}
}
}
Here an example where extract the number(s) from the string with Regex
string input = "There are 4 numbers in this string: 40, 30, and 10.";
// Split on one or more non-digit characters.
string[] numbers = Regex.Split(input, #"\D+");
foreach (string value in numbers)
{
if (!string.IsNullOrEmpty(value))
{
int i = int.Parse(value);
Console.WriteLine("Number: {0}", i);
}
}
Console.ReadKey();

two dimensional array in java - difficulties

I'm used to python and django but I've recently started learning java. Since I don't have much time because of work I missed a lot of classes and I'm a bit confused now that I have to do a work.
EDIT
The program is suppose to attribute points according to the time each athlete made in bike and race. I have 4 extra tables for male and female with points and times.
I have to compare then and find the corresponding points for each time (linear interpolation).
So this was my idea to read the file, and use an arrayList
One of the things I'm having difficulties is creating a two dimensional array.
I have a file similar to this one:
12 M 23:56 62:50
36 F 59:30 20:60
Where the first number is an athlete, the second the gender and next time of different races (which needs to be converted into seconds).
Since I can't make an array mixed (int and char), I have to convert the gender to 0 and 1.
so where is what I've done so far:
public static void main(String[] args) throws FileNotFoundException {
Scanner fileTime = new Scanner (new FileReader ("time.txt"));
while (fileTime.hasNext()) {
String value = fileTime.next();
// Modify gender by o and 1, this way I'm able to convert string into integer
if (value.equals("F"))
value = "0";
else if (value.equals("M"))
value = "1";
// Verify which values has :
int index = valor.indexOf(":");
if (index != -1) {
String [] temp = value.split(":");
for (int i=0; i<temp.length; i++) {
// convert string to int
int num = Integer.parseInt(temp[i]);
// I wanted to multiply the first number by 60 to convert into seconds and add the second number to the first
num * 60; // but this way I multiplying everything
}
}
}
I'm aware that there's probably easier ways to do this but honestly I'm a bit confused, any lights are welcome.
Just because an array works well to store the data in one language does not mean it is the best way to store the data in another language.
Instead of trying to make a two dimensional array, you can make a single array (or collection) of a custom class.
public class Athlete {
private int _id;
private boolean _isMale;
private int[] _times;
//...
}
How you intend to use the data may change the way you structure the class. But this is a simple direct representation of the data line you described.
Python is a dynamically-typed language, which means you can think of each row as a tuple, or even as a list/array if you like. The Java idiom is to be stricter in typing. So, rather than having a list of list of elements, your Java program should define a class that represents a the information in each line, and then instantiate and populate objects of that class. In other words, if you want to program in idiomatic Java, this is not a two-dimensional array problem; it's a List<MyClass> problem.
Try reading the file line by line:
while (fileTime.hasNext())
Instead of hasNext use hasNextLine.
Read the next line instead of next token:
String value = fileTime.next();
// can be
String line = fileTime.nextLine();
Split the line into four parts with something as follows:
String[] parts = line.split("\\s+");
Access the parts using parts[0], parts[1], parts[2] and parts[3]. And you already know what's in what. Easily process them.

Write to same location in a console window with java

I would like to write a character to the same location in a console window.
The characters I would like to write are / - \ _. This will get me a little spinner I can display to show progress or loading.
How can you write the chars to the same location though? Otherwise, you will wind up with something like this /-\_/-\_/-\
With Java 6 you can use the Console to do something like this:
class Main {
public static void main(String[] args) throws InterruptedException {
String[] spinner = new String[] {"\u0008/", "\u0008-", "\u0008\\", "\u0008|" };
Console console = System.console();
console.printf("|");
for (int i = 0; i < 1000; i++) {
Thread.sleep(150);
console.printf("%s", spinner[i % spinner.length]);
}
}
}
\u0008 is the special backspace character. Printing that erases the last character on the line. By starting to print a | and then prepending the \u0008 before all other characters you get the spinner behavior.
Note that this might not be 100% compatible with all consoles (and that System.console() can return null).
Also note that you don't necessarily have to use the console class, as printing this sequence to standard output commonly works just as well.
I don't think Java natively allows for that. You need to use some external library - maybe JCurses can help you.

Categories