Converting int to toString() method - class

Hello I am new to coding and am working on designing my own class, which computes the average of 'n' numbers which will be provided in the driver program as an array. Currently I continue to get an error "incompatible types, cannot convert int to java.lang.String" in my toString method at the end and am not sure how to get solve it. any help is appreciated.
//this code computes the average
public int adverage(int...array)
{
int adverage = 0;
if (array.length > 0)
{
int sum = 0;
for(int num : array)
sum = sum + num; //add numbers in array
adverage = (int)sum / array.length; //divide numbers in array by the array lenth
}
return adverage;
}
//this code is the toString return method
public String toString()
{
return getMinimun() + getMaximun() + adverage();
}
It is merely a requirement of the problem I am working on the the final result be displayed at a string. Thankyou!

According to your function definition,
public String toString()
this function must return a String. However, in your implementation, you seem to be returning an int.
Wrapping your return value in String.valueOf should do the trick.
return String.valueOf(getMinimun() + getMaximun() + adverage());

It seems that in the toString() method you are returning integers instead of strings. I get the total of those integers if that's what you're trying to do as a number and then convert it into a string.
public String toString()
{
int total = getMaximun() + getMinimun() + adverage();
String done = Integer.toString(total);
return done;
}
If that makes sense.

Related

How to pass different data value to Alfresco activiti multi instance subprocess

I have created a multi instance subprocess and the number of subprocesses is created dynamically using Multi-Instance's loopCardinality element but my problem is that I am not able to pass different-different data value to each subprocess.
Image here:
This is my problem scenario as shown in the above image. I want to divide subprocess based on loopCardinality value like:
int getSubProcessDataValue(int fileCount,int loopCardinality){
if(fileCount < 1 && loopCardinality < 1)
return 0
int result=fileCount/loopCardinality;
return result;
}
Suppose fileCount=7 and loopCardinality=2 then the above function will return 3 for the first subprocess. It means I have to pass 3 file names to the first subprocess.
int getLastSubProcessDataValue(int fileCount,int loopCardinality){
if(fileCount < 1 && loopCardinality < 1)
return 0
int result=fileCount/loopCardinality;
int rem=fileCount%loopCardinality;
return result+rem;
}
Suppose fileCount=7 and loopCardinality=2 then the above function will return 4 for the last subprocess. It means I have to pass 4 file names to the last subprocess.
Anyone have an idea how to implement it? Please help me.
This is actually one of the coolest features of the Activiti engine in my opinion.
You do this by using the collection option rather than setting the cardinality.
The collection and elementValue options as shown below:
Here the number of instances will be determined by the size of the collection and the input variables "elementValue" will be the list element.
Using this approach you can pass different data into each instance of the multi instance loop.
Hope this helps,
Greg
I have done it using TaskListener as shown below code:
package com.knovel.workflow.scripts;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
public class FileSplittingTaskListener implements TaskListener{
private static final long serialVersionUID = 3972525330472103945L;
#Override
public void notify(DelegateTask task) {
System.out.println("#####FileSplittingTaskListener######");
task.setVariable("bpm_assignee", task.getVariable("bpm_assignee"));
task.setVariable("bpm_comment", task.getVariable("bpm_comment"));
task.setVariable("bpm_dueDate", task.getDueDate());
task.setVariable("bpm_priority", task.getPriority());
String strFileSplitter=(String)task.getVariable("wf_fileSplitter");
System.out.println("#############FileSplitter >>"+strFileSplitter);
Integer fileSplitter=Integer.parseInt(strFileSplitter);
System.out.println("#############FileSplitter >>"+fileSplitter);
//task.setVariable("wf_taskCounter", fileSplitter);
String workFlowFileName=(String)
task.getVariable("wf_workFlowFileName");
String[] files=workFlowFileName.split("-");
System.out.println("#######Files Length:"+files.length);
List<String[]> filesList = splitArray(files, fileSplitter);
List<String> fileList=new ArrayList<>();
for (String[] lists : filesList) {
String fileName="";
int srNo=0;
int count=1;
for (String string : lists) {
System.out.println("File>>"+string);
if(count == lists.length){
fileName=fileName+ ++srNo +"-"+string;
}else{
fileName=fileName+ ++srNo +"-"+string+",";
}
count++;
}
fileList.add(fileName);
srNo=0;
}
System.out.println("FileList>>"+fileList);
System.out.println("#############FileList >>"+fileList);
task.setVariable("filesList", fileList);
}
public static <T extends Object> List<T[]> splitArray(T[] array, int
max){
int x = array.length / max;
int r = (array.length % max); // remainder
int lower = 0;
int upper = 0;
List<T[]> list = new ArrayList<T[]>();
int i=0;
for(i=0; i<x; i++){
upper += max;
list.add(Arrays.copyOfRange(array, lower, upper));
lower = upper;
}
if(r > 0){
list.add(Arrays.copyOfRange(array, lower, (lower + r)));
}
return list;
}
}
And I have updated multiInstanceLoopCharacteristics element properties as shown below:
<multiInstanceLoopCharacteristics
isSequential="false"
activiti:collection="filesList"
activiti:elementVariable="wf_workFlowFileName">
</multiInstanceLoopCharacteristics>
Thank you so much for your valuable supports!!!

Calculator Functioning

I am trying to obtain calculator functioning of simple on button sum. In this one text field will display digits one after another seperated by + sign and one calculate button will display result. I am stuck in finding the sum in ans() function. Please help or suggest.
My Sum button calls function sumclicked and Equals button calls result
public void result(View v) { // This will only display the resut
TextView answer = (TextView)findViewById(R.id.output);
answer.setText(String.valueOf(ans()));
}
public int ans()
{ // This is just for calculating the sum value to display
int ans=0;
int num2=0;
int sum=sumclicked()+num2;
num2=sum=ans;
return ans;
}
public void sumclicked (View v)
{ // This is display of textfield. Eg 55 + 12 + 99
EditText value=(EditText)findViewById(R.id.input);
String ans=value.getText().toString();
String ans1= ans +"+";
TextView tempview = (TextView)findViewById(R.id.input);
tempview.setText(ans1);
}
public int sumclicked()
{ // This parses each string digit to int and returns it for getting the summation done.
EditText value=(EditText)findViewById(R.id.input);
String ans=value.getText().toString();
Integer ans1=Integer.parseInt(ans);
return ans1;
}

tostring method giving wrong output

Hi I'm writing a test program to reverse a string. When I convert the character array to a string using the toString() method, I get the wrong output. When I try to print the array manually using a for loop without converting it to a string the answer is correct. The code I've written is shown below:
import java.util.*;
public class stringManip {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "This is a string";
System.out.println("String=" +str);
//reverse(s);
char[] c = str.toCharArray();
int left = 0;
int right = str.length() - 1;
for (int i = 0; i < (str.length())/2; i++)
{
char temp = c[left];
c[left++] = c[right];
c[right--] = temp;
}
System.out.print("Reverse="+c.toString());
}
}
I should get the reverse of the string I entered, instead the output am getting is:
String=This is a string
Reverse=[C#45a1472d
Is there something am doing wrong when using the toString() method? Any help is appreciated. Thank you.
Arrays don't override the toString() method. What you're seeing is thus the output of the default Object.toString() implementation, which contains the type of the object ([C means array of chars) followed by its hashCode.
To construct a String from a char array, use
new String(c)

GWT, columnSortHandler.setComparator for all columns in a loop, make the sorting messed-up?

I've got this code:
ListHandler<List<String>> columnSortHandler = new ListHandler<List<String>>(list);
for (int k=0; k<10; k++){
IndexedColumn myColumn=new IndexedColumn(k+1);
table.addColumn(myColumn, "col "+k);
myColumn.setSortable(true);
columnSortHandler.setComparator(myColumn, new Comparator<List<String>>() {
public int compare(List<String> o1, List<String> o2) {
return o1.get(0).compareTo(o2.get(0));
}
});
}
When I do the sorting, the sorting action was invoked, the table did the sorting but the orders of values in that column are not correct. So I suspect it could be I put the columnSortHandler.setComparator inside a loop & that's causing the problem.
How do I fix it?
Your issue is that every time you compare you're comparing on the first String in the list. Assuming every object in the list represents the value of the column of that index then you should just change the index that your getting in the comparator.
Assuming what I said above is right then you might want to take a look at the answer I posted here.
In your case your comparator should be:
columnSortHandler.setComparator(myColumn, new Comparator<List<String>>(){
public int compare(List<String> o1, List<String> o2) {
if (o1 == o2) {
return 0;
}
// Compare the column.
if (o1 != null) {
return (o2 != null) ? o1.get(k).compareTo(o2.get(k)) : 1;
}
return -1;
}
});
Now I'm not sure if in the code above the k should be just k or k+1. Looking at the code you posted it isn't clear to me if your first column's value is at index 0 or 1.

How to get down to StringLiterals with Eclipse AST?

I need to create an Eclipse plugin that displays a tooltip when I hover the mouse over a String literal.
But only if that String literal is the first parameter of a special method.
Here is the Test.java file I use to test my plugin:
package test;
public class Test {
public static void main(String[] args) {
String hello = "Hello";
String world = Translator.get("Test.worldLabel");
System.out.println(hello + " " + world);
}
}
I created a class implementing IJavaEditorTextHover and I need to compile the currently edited Java file to compute if the cursor is hovering a String that needs to be translated or not.
Hovering "Hello" will do nothing.
Hovering "Test.worldLabel" will display my tooltip because that literal is included inside a Translator.get() method call.
At first I used this (170 is inside "Test.worldLabel"):
ITypeRoot typeRoot = (ITypeRoot)
JavaUI.getEditorInputJavaElement(editorPart.getEditorInput());
JavaElement foundElement = (JavaElement) typeRoot.getElementAt(170);
But the foundElement contains the whole main() method: it is not fine-grained enough.
Then, the correct way is, I think:
private static ASTNode parse(ICompilationUnit unit, int position) {
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(unit);
parser.setResolveBindings(true);
parser.setIgnoreMethodBodies(false);
// TODO Future optimisation: parser.setFocalPosition(position);
return parser.createAST((IProgressMonitor) null); // parse
}
And in my IJavaEditorTextHover.getHoverInfo(...) implementation:
ICompilationUnit compilationUnit = (ICompilationUnit)
JavaUI.getEditorInputJavaElement(editor.getEditorInput())
int position = 170/*hoverRegion.getOffset()*/;
ASTNode ast = parse(compilationUnit, position);
And now, here is my question:
How, from this ast node, do I get the ASTNode reprensenting the StringLiteral at position 170 in the source code (the "Test.worldLabel" String)?
Bonus question: did I choose the right solution? On a performance basis.
Edit:
Well, here is a solution I found:
private StringLiteral findStringLiteralAtPosition(final ASTNode parent, final int position) {
final List<StringLiteral> stringLiterals = new ArrayList<StringLiteral>();
parent.accept(new ASTVisitor() {
#Override
public boolean visit(StringLiteral stringLiteral) {
int start = stringLiteral.getStartPosition();
int end = start + stringLiteral.getLength();
if (start <= position && position <= end) {
stringLiterals.add(stringLiteral);
}
return super.visit(stringLiteral);
}
});
return (stringLiterals.size() > 0 ? stringLiterals.get(0) : null);
}
Does it seam OK?
Or is it an easier way or a more performant one?
One solution will be not using the offset logic at all.
You can generalise the solution by using a node parent check.
Here is a sample code:
public boolean visit(StringLiteral stringLiteral) {
// Check if parent is a method inovacation.
if (stringLiteral.getParent().getNodeType() == ASTNode.METHOD_INVOCATION) {
// get the parent method inovacation.
MethodInvocation miNode = (MethodInvocation) stringLiteral.getParent();
//To do: null and empty check on argument list.
// Check if is the special method and this is the 1st argument
if (miNode.getName().toString().equals("SpecialMethod")
&& miNode.arguments().get(0).toString().equals(stringLiteral.toString())) {
System.out.println("Found it : " + stringLiteral.toString());
}
}
return true;
}