Java get java.awt.Color from string - java

So I have a string that looks something like this:
text java.awt.Color[r=128,g=128,b=128]text 1234
How could I pop out the color and get the rgb values?

You can get the rgb values from that string with this:
String str = "text java.awt.Color[r=128,g=128,b=128]text 1234";
String[] temp = str.split("[,]?[r,g,b][=]|[]]");
String[] colorValues = new String[3];
int index = 0;
for (String string : temp) {
try {
Integer.parseInt(string);
colorValues[index] = string;
index++;
} catch (Exception e) {
}
}
System.out.println(Arrays.toString(colorValues)); //to verify the output
The above example extract the values in an array of Strings, if you want in an array of ints:
String str = "text java.awt.Color[r=128,g=128,b=128]text 1234";
String[] temp = str.split("[,]?[r,g,b][=]|[]]");
int[] colorValues = new int[3];
int index = 0;
for (String string : temp) {
try {
colorValues[index] = Integer.parseInt(string);
index++;
} catch (Exception e) {
}
}
System.out.println(Arrays.toString(colorValues)); //to verify the output

As said before, you will need to parse the text. This will allow you to return the RGB values from inside the string. I would try something like this.
private static int[] getColourVals(String s){
int[] vals = new int[3];
String[] annotatedVals = s.split("\\[|\\]")[1].split(","); // Split the string on either [ or ] and then split the middle element by ,
for(int i = 0; i < annotatedVals.length; i++){
vals[i] = Integer.parseInt(annotatedVals[i].split("=")[1]); // Split by the = and only get the value
}
return vals;
}

Related

How to divide a sentence to words and compare with another string?

I have saved the units in .txt file. These I am getting in an array list. Now I want to check if any of the units present in the string.
List contains :
"units", "kg", "kilogms", "kilo", "literes",
"Liter", "packets", "packet", "gms", "grams", "half kg"
Like, if I have a string - 1kg rice, I want to get numbers from this string and I want to divide this sentence to words and want to compare with each item from array list of units. If it is present I want to save it. So I want to store 1kg and rice separately. string may contain any spaces I want to trim all those spaces and check compare.
Getting text file in an array list.
public class ReadTextFiles {
public static List<String> readItemNamesFile(Context context) {
String sText = null;
List<String> stringList;
try{
InputStream is = context.getResources().openRawResource(R.raw.item_names);
//Use one of the above as per your file existing folder
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
sText = new String(buffer, "UTF-8");
String[] sTextArray = sText.replace("\"", "").split(",");
stringList = new ArrayList<String>(Arrays.asList(sTextArray));
System.out.print(stringList);
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return stringList;
}
}
public void getUnits()
{
List<String> units = new ArrayList<>();
units = ReadTextFiles.readUnitsFile(getActivity());
System.out.print(units.size());
}
Now I want to compare string suppose its "1 kg potato".Then should find potato from the array list. Also it should be case insensitive.
This is the full solution of your requirement as I understood:
String measuring = "\"units\", \"kg\", \"kilogms\", \"kilo\", \"literes\", \"Liter\", \"packets\", \"packet\", \"gms\", \"grams\", \"half kg\"";
String items = "\"Potato\", \"rice\", \"Eggs\", \"Maggi\", \"Dryfruits\", \"Maza\", \"cold drink\", \"sauce\", \"catchup\", \"coconut oil\"";
String matching = "Kg500 Potato";//"Potato 1 kg";
String item = "", measuringUnit = "", quantity = "";
private void findOut() {
String[] sMeasuringArray = measuring.replace("\"", "").split(", ");
ArrayList<String> measuringList = new ArrayList<String>(Arrays.asList(sMeasuringArray));
String[] sItemsArray = items.replace("\"", "").split(", ");
ArrayList<String> itemsList = new ArrayList<String>(Arrays.asList(sItemsArray));
String[] sMatchingArray = matching.split(" ");
matching = matching.toUpperCase();
for (int i = 0; i < measuringList.size(); i++) {
if (matching.contains(measuringList.get(i).toUpperCase())) {
measuringUnit = measuringList.get(i).trim();
break;
}
}
for (int i = 0; i < itemsList.size(); i++) {
if (matching.contains(itemsList.get(i).toUpperCase())) {
item = itemsList.get(i).trim();
break;
}
}
if (matching!= null) {
String[] part = matching.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
for (int k = 0; k < part.length; k++) {
try {
Integer.parseInt(part[k]);
quantity = part[k];
break;
} catch (Exception ex) {
continue;
}
}
}
/*if (sMatchingArray != null) {
if (sMatchingArray.length == 3) {
for (int j = 0; j < sMatchingArray.length; j++) {
if (measuringUnit.trim().equals(sMatchingArray[j].trim())) {
quantity = sMatchingArray[j - 1].trim();
break;
}
}
} else if (sMatchingArray.length == 2) {
String[] part = matching.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
for (int k = 0; k < part.length; k++) {
try {
Integer.parseInt(part[k]);
quantity = part[k];
break;
} catch (Exception ex) {
continue;
}
}
}
}*/
Log.e("Solution: ", "item = " + item + ", measuringUnit = " + measuringUnit + ", quantity = " + quantity);
}
I'm gonna be using algorithmic approach for the answer. So here it goes:
strItem = "1kg rice";
//Run a loop through the list of units and for each unit check this
if (strItem.contains(list.get(index)))
//Do the needful and break

How to add a String to another String array in android?

This my java code, here i have to add a string "RFID" in a String Array itemtypes and i have to stored it in an another string array item.But im getting an error.
String[] itemtype;
String[] item;
\...........
.........../
try {
response = (SoapPrimitive) envelope.getResponse();
Koradcnos = response.toString();
} catch (SoapFault e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
itemtypes = Koradcnos.split(";");
item=itemtypes+"RFID";//here im getting error
} catch (Exception er) {
//Helper.warning("Error", er.toString(),this);
}
imageId = new int[itemtypes.length];
for (int i = 0; i < itemtypes.length; i++)
if (itemtypes[i].equals("Yarn")) {
imageId[i] = R.drawable.yarnitem;
You need to work around for this :
Using with Arrays.copyOf
item = Arrays.copyOf(itemtypes , itemtypes.length + 1);
item[item.length - 1] = "RFID";
Or direct split from Koradcnos
item = (Koradcnos + ";RFID").split(";");
You cannot concatenate string with a list String.split() method returns a String array.
Instead of item=itemtypes+"RFID" iterate through the array as:
for (int i=0; i < itemtypes.length(); i++) {
item[i] = itemtypes[i] + "RFID";
}
Also I think the variable name will be itemtypes instead of itemtype
itemtypes is String array,it can't be modified,if you want to get a new array adding another element,you can use System.arrayCopy
System.arraycopy(Object src,
int srcPos,
Object dest,
int destPos,
int length)
Like this:
item = new String[itemtypes.length+1];
System.arraycopy(itemtypes,0,item,0,itemtypes.length);
item[itemtypes.length] = "RFID";

Java IndexOutOfBoundException

I'm trying to read from a text file, but I get this error I can't figure it out how to fix it .
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
and my code
try {
String scan;
FileReader file = new FileReader("C:\\Users\\W7\\workspace\\Lab 8\\students.txt");
BufferedReader br = new BufferedReader(file);
while((scan = br.readLine()) != null) {
String values = scan;
String[] val = values.split("\t");
String[] vals;
vals = val[0].split(":");
int size = val.length;
System.out.println(vals[1]);
switch (size) {
case 3 :
vals = val[0].split(":");
int id = Integer.parseInt(vals[1]);
vals = vals[1].split(":");
String name = val[1];
vals = val[2].split(":");
int grade = Integer.parseInt(vals[1]);
Student st = new Student(id, name, grade);
} catch (IOException e) {
System.out.println(e.getStackTrace());
}
My text file
ID:5 Name:john Grade:6
ID:6 Name:paul Grade:10
Length of vals is not known before accessing its first or second element:
String[] vals;
vals = val[0].split(":");
System.out.println(vals[1]);
Even before accessing the element at index 0, you need to make sure that vals is not an empty array by checking its length. This can happen, for example, when you encounter an empty line in the input which doesn't even have a tab.
The error is where you use vals[1] before checking the length of vals.
vals = val.contains(":") ? val[0].split(":") : null;
int size = (vals == null) ? 0 : vals.length; // which is the array I think you want
System.out.println(vals[1]);
switch (size) {
...
}
String values = scan;
String[] val = values.split("\t");
String[] vals;
vals = val[0].split(":");
int size = val.length;
System.out.println(vals[1]);
You sure the codes above can handle a blank line? You are assuming every single line has at least 1 ":"

Java StringTokenizer

I have the following input
(11,C) (5,) (7,AB)
I need to split them into 2 part for each coordinates.
So my intarray should have 11, 5, 7
and my letter array should have C,,AB
But when I try using stringtokenizer,
I only get my intarray should have 11, 5, 7
and my letter array should have C,AB
Is there any way I could get the empty part of (5,)?
Thank you.
Vector<String> points = new Vector<String> ();
String a = "(11,C) (5,) (7,AB)";
StringTokenizer st = new StringTokenizer(a, "(,)");
while(st.hasMoreTokens()) {
points.add(st.nextToken());
}
}
System.out.println(points);
List <Integer> digits = new ArrayList <Integer> ();
List <String> letters = new ArrayList <String> ();
Matcher m = Pattern.compile ("\\((\\d+),(\\w*)\\)").matcher (string);
while (m.find ())
{
digits.add (Integer.valueOf (m.group (1)));
letters.add (m.group (2));
}
Must be like this
String[] values = a.split("\\) \\(");
String[][] result = new String[values.length][2];
for (int i = 0; i < values.length; i++) {
values[i] = values[i].replaceAll("\\(|\\)", "") + " ";
result[i] = values[i].split("\\,");
System.out.println(result[i][0] + " * " + result[i][1]);
}
result will contain coordinate pairs.
public static void main(String[] args) {
String s = "(11,C), (5,) ,(7,AB)";
ArrayList<String> name = new ArrayList<String>();
ArrayList<Integer> number = new ArrayList<Integer>();
int intIndex = 0, stringIndex = 0;
String[] arr = s.split(",");
for (int i = 0; i < arr.length; i++) {
String ss = arr[i].replace("(", "");
ss = ss.replace(")", "");
boolean b = isNumeric(ss);
// System.out.println( Arrays.toString(arr));
if (b) {
int num = Integer.valueOf(ss.trim()).intValue();
number.add(num);
} else
name.add(ss);
}
System.out.println(name);
System.out.println(number);
}
public static boolean isNumeric(String str) {
try {
double d = Double.parseDouble(str);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
Try this: I have slightly changed the input from "(11,C) (5,) (7,AB)" to "(11,C), (5,) ,(7,AB)" .
Output:
[C, , AB]
[11, 5, 7]
Brutal coding, in raw level:
List<String> points = new ArrayList<String> ();
String source= "(11,C) (5,) (7,AB)";
StringTokenizer deleteLeft = new StringTokenizer(source, "(");
while(deleteLeft.hasMoreTokens()) {
StringTokenizer deleteRight = new StringTokenizer(deleteLeft.nextToken(), ")");
points.add(deleteRight.nextToken());
}
System.out.println(points);
}

multidimensional String[][] array java

I have an array that is from .split command and want to put it into an array called String[][] datatabvars, I do not know how to turn datatabvars into a two dimensional array and put the data into it.
public String[] getList() {
String file_name = "path";
String[] links = null;
String[][] datatabvars = null; // this var
int numberOfDatatabs = 0;
try {
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
int i;
for(i=0; i < aryLines.length; i++) { //aryLines.length
if (aryLines[i].substring(0, 7).equals("datatab")) {
aryLines[i] = aryLines[i].replace("datatab["+Integer.toString(numberOfDatatabs)+"] = new Array(", "");
aryLines[i] = aryLines[i].replace(");", "");
datatabvars = aryLines[i].split(","); // this split array
numberOfDatatabs++;
}
}
System.out.println(datatabvars[0]);
}catch (IOException e) {
System.out.println( e.getMessage() );
}
return links;
}
Update the two lines(I added comment) as below: (I am assuming that rest of your code is working)
String[][] datatabvars = null; // this var
int numberOfDatatabs = 0;
try {
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
datatabvars = new String[aryLines.length][]; // INITIALIZED
int i;
for(i=0; i < aryLines.length; i++) { //aryLines.length
if (aryLines[i].substring(0, 7).equals("datatab")) {
aryLines[i] = aryLines[i].
replace("datatab["+Integer.toString(numberOfDatatabs)+"] =
new Array(", "");
aryLines[i] = aryLines[i].replace(");", "");
datatabvars[i] = aryLines[i].split(","); // this split array: ASSIGNED
numberOfDatatabs++;
}
}
System.out.println(datatabvars[0]);
In general, arrays are to avoided like the plague - use collections if possible:. In this case, split() returns a String[], so use that, but use List<String[]> to store multiple String[]:
List<String[]> datatabvars = new ArrayList<String[]>();
...
String[] array = input.split(",");
datatabvars.add(array);
You find life is much easier using collections than arrays.

Categories

Resources