ToString does not work - tostring

Why toString doesn´t work in my code? The output should be all elements that are in the idChild[].
Error:
child[Ljava.lang.String;#15db9742
public String[] onePointCrossover(int father, int mother) {
String linha1 = individualID.get(father);
idFather = linha1.split(" ");
String linha2 = individualDep.get(father);
depenFather= linha2.split(" ");
String linha3 = individualHour.get(father);
hourFather = linha3.split(" ");
String linhaA = individualID.get(mother);
idMother = linha1.split(" ");
String linhaB = individualDep.get(mother);
depenMother= linha2.split(" ");
String linhaC = individualHour.get(mother);
hourMother = linha3.split(" ");
String [] idChild = new String [idFather.length];
int crossPoint = (int) (Math.random()*idFather.length);
for(int i=0; i<idFather.length; i++)
{
if (i<crossPoint)
idChild[i] = idFather[i];
else
idChild [i] = idMother[i];
}
System.out.println("child" + idChild.toString());
return idChild;
}

If you want to loop through all childs in your array, then you need to loop through it, other wise you are attempting to read an array of objects as a string!
Try:
foreach (string s in idChild)
{
System.out.println(s);
}

This is the way toString() works (documentation here): the default implementation of the Object class (and of all arrays) shows the class name, the # symbol and the hexadecimal representation of the hash code of the object:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
The documentation says:
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object.
So it's really up to the programmer to choose what "textually represents" means.
If you want to print the String representation of all the items in an array you have to iterate over it.

Related

Java - For loop within ArrayList<String> method only returns one element

I am trying to use an ArrayList of string values from one table, modify the strings based on whether or not the string ends with ".tif" or ".tiff", then transfer the resulting strings to a new table. However, when I invoke this method, the new table only receives the first modified string. I'm not sure what is wrong with my logic, the first element of the original table would be checked to see if it satisfies a condition (either ending in ".tif" or ".tiff") then from there that string would be modified, added to the ArrayList fData, then iterate to the next table value. I don't understand why the method doesn't return more than one element contained within fData?
public ArrayList<String> getTableData() {
StringBuilder str = new StringBuilder();
String fString = null;
ArrayList<String> fData = new ArrayList<String>();
while(filePaths != null) {
int size = filePaths.size();
for (int i = 0; i <= size; i++) {
String pathName = filePaths.get(i);
if (pathName.endsWith(".tif")) {
int pathLength = pathName.length();
str = new StringBuilder(filePaths.get(i));
str.insert(pathLength - 4, "_Data");
fString = str.toString();
fData.add(fString);
tableModel2.addRow(new String[] { fString });
return fData;
}
else if (pathName.endsWith(".tiff")) {
int pathLength = pathName.length();
str = new StringBuilder(filePaths.get(i));
str.insert(pathLength - 5, "_Data");
fString = str.toString();
fData.add(fString);
tableModel2.addRow(new String[] { fString });
return fData;
}
}
tableModel2.fireTableDataChanged();
}
return null;
}
`
It appears that you are returning from getTableData() as soon as you do a single replacement. Instead, you should return only after having iterated over every file path.
Remove the return statements inside the loops and instead replace return null at the end with return fData.

Morse code conversion on how to return a method

Please pardon me for my weak porgramming ability. I'm trying to write a method converting english to morse code. As you can see, I use hashmap to store the equivalant and then convert it and stored the morse code into the variable 'result'. My concern is I can't return the variable 'result' outside of the loop. If i return 'dataInput', isn't it just returning the original input? How can I return the correct result?
public static String morseCode(String dataInput)
{
Map<String, String> morseCode = new HashMap<String, String>();
morseCode.put("a", ".-");
morseCode.put("b", "-...");
morseCode.put("c", "-.-.");
for (int i = 0; i<dataInput.length(); i++)
{
String result = (String)morseCode.get(dataInput.charAt(i)+"");
//convert input data into morse code
}
return dataInput;
}
Try like this:
import java.lang.StringBuffer; //at the top
Map morseCode = new HashMap();
morseCode.put("a", ".-");
morseCode.put("b", "-...");
morseCode.put("c", "-.-.");
StringBuffer buff = new StringBuffer();
for (int i = 0; i<dataInput.length(); i++)
{
String result = (String)morseCode.get(dataInput.charAt(i));
//convert input data into morse code
buff.append(result+" ");
}
return buff.toString();
}

Get string version of lambda expression property

Similar to question How can I get property name strings used in a Func of T.
Let's say I had a lambda expression
stored like this in a variable called "getter"
Expression<Func<Customer, string>> productNameSelector =
customer => customer.Product.Name;
how can I extract the string "Product.Name" from that?
I now fixed it somewhat haxy with
var expression = productNameSelector.ToString();
var token = expression.Substring(expression.IndexOf('.') + 1);
But i'd like to find a more solid way ;-)
The expression tree for your expression looks like this:
.
/ \
. Name
/ \
customer Product
As you can see, there is no node that would represent Product.Name. But you can use recursion and build the string yourself:
public static string GetPropertyPath(LambdaExpression expression)
{
return GetPropertyPathInternal(expression.Body);
}
private static string GetPropertyPathInternal(Expression expression)
{
// the node represents parameter of the expression; we're ignoring it
if (expression.NodeType == ExpressionType.Parameter)
return null;
// the node is a member access; use recursion to get the left part
// and then append the right part to it
if (expression.NodeType == ExpressionType.MemberAccess)
{
var memberExpression = (MemberExpression)expression;
string left = GetPropertyPathInternal(memberExpression.Expression);
string right = memberExpression.Member.Name;
if (left == null)
return right;
return string.Format("{0}.{1}", left, right);
}
throw new InvalidOperationException(
string.Format("Unknown expression type {0}.", expression.NodeType));
}
If you have an Expression you can use the ToString method to extract the string representation:
Expression<Func<Customer, string>> productNameSelector =
customer => customer.Product.Name;
var expression = productNameSelector.ToString();
var token = expression.Substring(expression.IndexOf('.') + 1);

How to search on multiple strings entered in single text box in mvc3

i have a single textbox named Keywords.
User can enter multiple strings for search.
How this is possible in mvc3?
I am using nhibernate as ORM.
Can i create criteria for this?
Edited Scenario
I have partial view to search job based on following values:
Keywords(multiple strings), Industry(cascading dropdown with functional area )//working well ,FunctionalArea//working well
Loaction(multiple locations), Experience//working well
In Controller i am retrieving these values from form collection.
What datatype should i use for keywords and location (string or string[] )?
public ActionResult SearchResult(FormCollection formCollection)
{
IList<Jobs> JobsSearchResultList = new List<Jobs>();
//string[] keywords = null;
string location = null;
int? industry = 0;
int? functionaArea = 0;
int? experience = 0;
string keywords = null;
if (formCollection["txtKeyword"] != "")
{
keywords = formCollection["txtKeyword"];
}
//if (formCollection["txtKeyword"] != "")
//{
// keywordAry = formCollection["txtKeyword"].Split(' ');
// foreach (string keyword in keywordAry)
// {
// string value = keyword;
// }
//}
......retrieving other values from formcollection
....
//Now passing these values to Service method where i have criteria for job search
JobsSearchResultList = oEasyJobsService.GetJobsOnSearchExists(keywords,industry,functionaArea,location,experience);
return View(JobsSearchResultList);
}
In Services i have done like:
public IList<EASYJobs> GetJobsOnSearchExists(string keywords, int? industryId, int? functionalAreaId, string location, int? experience)
{
IList<JobLocation> locationlist = new List<JobLocation>();
IList<Jobs> JobsList = null;
var disjunction = Expression.Disjunction();
ICriteria query = session.CreateCriteria(typeof(Jobs), "EJobs");
if (keywords != null)
{
foreach (string keyword in keywords)
{
string pattern = String.Format("%{0}%", keyword);
disjunction
.Add(Restrictions.InsensitiveLike("Jobs.keywords", pattern,MatchMode.Anywhere))
.Add(Restrictions.InsensitiveLike("YJobs.PostTitle",pattern,MatchMode.Anywhere));
}
query.Add(disjunction)
.Add(Expression.Eq("EASYJobs.Industry.IndustryId", industryId))
.Add(Expression.Eq("Jobs.FunctionalArea.FunctionalAreaId", functionalAreaId))
.Add(Expression.Eq("Jobs.RequiredExperience", experience)));
}
else
{..
}
JobsList = criteria.List<Jobs>();
}
Problems i am facing are:
In controller if i use string[],then Split(',') does not split the string with specified separator.It passes string as it is to Service.
2.In services i am trying to replace string with %{0}% ,strings with spaces are replaced/concat() here with given delimeter.
But the problem here is It always return the whole job list means not giving the required output.
Pleas help ...
As long as you have a delimiter you can break the input into pieces on you should be able to create an or expression with the parts. You can use a disjunction to combine an arbitrary number of criteria using OR's.
var criteria = session.CreateCriteria<TestObject>();
Junction disjunction = Restrictions.Disjunction();
var input = "key words";
foreach (var keyword in input.Split(" "))
{
ICriterion criterion = Restrictions.Eq("PropertyName", keyword);
disjunction.Add(criterion);
}
criteria.Add(disjunction);
Multiple keywords with special characters or extra spaces are replaced with single space with Regex expressions.
And then keywords are separated with Split("").
Its working as required....
if (!string.IsNullOrEmpty(keywords))
{
keywords = keywords.Trim();
keywords = System.Text.RegularExpressions.Regex.Replace(keywords, #"[^0-9a-zA-Z\._\s]", " ");
keywords = System.Text.RegularExpressions.Regex.Replace(keywords, #"[\s]+", " ");
if (keywords.IndexOf(" ") > 0)
{
string[] arr = keywords.Split(" ".ToCharArray());
for (int i = 0; i < arr.Length; i++)
{
if (!string.IsNullOrEmpty(arr[i]))
{
criteria.Add(Restrictions.Disjunction()
.Add(Expression.Like("EASYJobs.keywords", arr[i], MatchMode.Anywhere)));
}
}
}
else
{
criteria.Add(Restrictions.Disjunction()
.Add(Expression.Like("EASYJobs.keywords", keywords, MatchMode.Anywhere)));
}
}

How to get a substring in some length for special chars like Chinese

For example, I can get 80 chars with {description?substring(0, 80)} if description is in English, but for Chinese chars, I can get only about 10 chars, and there is a garbage char at the end always.
How can I get 80 chars for any language?
FreeMarker relies on String#substring to do the actual (UTF-16-chars-based?) substring calculation, which doesn't work well with Chinese characters. Instead one should uses Unicode code points. Based on this post and FreeMarker's own substring builtin I hacked together a FreeMarker TemplateMethodModelEx implementation which operates on code points:
public class CodePointSubstring implements TemplateMethodModelEx {
#Override
public Object exec(List args) throws TemplateModelException {
int argCount = args.size(), left = 0, right = 0;
String s = "";
if (argCount != 3) {
throw new TemplateModelException(
"Error: Expecting 1 string and 2 numerical arguments here");
}
try {
TemplateScalarModel tsm = (TemplateScalarModel) args.get(0);
s = tsm.getAsString();
} catch (ClassCastException cce) {
String mess = "Error: Expecting numerical argument here";
throw new TemplateModelException(mess);
}
try {
TemplateNumberModel tnm = (TemplateNumberModel) args.get(1);
left = tnm.getAsNumber().intValue();
tnm = (TemplateNumberModel) args.get(2);
right = tnm.getAsNumber().intValue();
} catch (ClassCastException cce) {
String mess = "Error: Expecting numerical argument here";
throw new TemplateModelException(mess);
}
return new SimpleScalar(getSubstring(s, left, right));
}
private String getSubstring(String s, int start, int end) {
int[] codePoints = new int[end - start];
int length = s.length();
int i = 0;
for (int offset = 0; offset < length && i < codePoints.length;) {
int codepoint = s.codePointAt(offset);
if (offset >= start) {
codePoints[i] = codepoint;
i++;
}
offset += Character.charCount(codepoint);
}
return new String(codePoints, 0, i);
}
}
You can put an instance of it into your data model root, e.g.
SimpleHash root = new SimpleHash();
root.put("substring", new CodePointSubstring());
template.process(root, ...);
and use the custom substring method in FTL:
${substring(description, 0, 80)}
I tested it with non-Chinese characters, which still worked, but so far I haven't tried it with Chinese characters. Maybe you want to give it a try.

Resources