tostring method giving wrong output - eclipse

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)

Related

convert my user defined string into char array in java

I have string as below in java , when i am trying to convert getting error
HelloWorld.java:12: error: array required, but String found
c[i]=s[i];
^
1 error
public static void main(String []args){
String s="Abcde";
char c[];
System.out.print(s);
for(int i=0;i<s.length();i++)
{
//
c[i]=s[i];
}
}
}
I would suggest you to use inbuilt function instead of doing this. You can
find many methods available on internet and tutorials to convert your
string into char array in java. for example- Using **toCharArray()** Method.
`public static void main(String args[])
{
String str = "Abcde";
// Creating array and Storing the array
// returned by toCharArray()
char[] ch = str.toCharArray();
// Printing array
for (char c : ch) {
System.out.println(c);
}`

Converting int to toString() method

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.

BeamSql tramsformation issues

I have my below code in which I'm reading a csv file and defining its schema, after that I'm converting it into BeamRecords. and then applying BeamSql to implement PTransforms.
Code:
class Clo {
public String Outlet;
public String CatLib;
public String ProdKey;
public Date Week;
public String SalesComponent;
public String DuetoValue;
public String PrimaryCausalKey;
public Float CausalValue;
public Integer ModelIteration;
public Integer Published;
}
public static void main(String[] args) {
PipelineOptions options = PipelineOptionsFactory.create();
Pipeline p = Pipeline.create(options);
PCollection<java.lang.String> lines= p.apply(TextIO.read().from("gs://gcpbucket/input/WeeklyDueto.csv"));
PCollection<Clorox> pojos = lines.apply(ParDo.of(new ExtractObjectsFn()));
List<java.lang.String> fieldNames = Arrays.asList("Outlet", "CatLib", "ProdKey", "Week", "SalesComponent", "DuetoValue", "PrimaryCausalKey", "CausalValue", "ModelIteration", "Published");
List<java.lang.Integer> fieldTypes = Arrays.asList(Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.DATE, Types.VARCHAR,Types.VARCHAR,Types.VARCHAR, Types.FLOAT, Types.INTEGER, Types.INTEGER);
BeamRecordSqlType appType = BeamRecordSqlType.create(fieldNames, fieldTypes);
PCollection<BeamRecord> apps = pojos.apply(
ParDo.of(new DoFn<Clo, BeamRecord>() {
#ProcessElement
public void processElement(ProcessContext c) {
BeamRecord br = new BeamRecord(
appType,
c.element().Outlet,
c.element().CatLib,
c.element().ProdKey,
c.element().Week,
c.element().SalesComponent,
c.element().DuetoValue,
c.element().PrimaryCausalKey,
c.element().CausalValue,
c.element().ModelIteration,
c.element().Published
);
c.output(br);
}
})).setCoder(appType, getRecordCoder());
PCollection<BeamRecord> out = apps.apply(BeamSql.query("select Outlet from PCOLLECTION"));
out.apply("WriteMyFile", TextIO.write().to("gs://gcpbucket/output/sbc.txt"));
}
My questions are:
what shall I implement in ExtractObjectsFn() so that the records gets converted into BeamRecords ?
How to write the final output to a csv file ?
I have implemented ExtractObjectsFn() as :
public void processElement(ProcessContext c) {
ArrayList<Clo> clx = new ArrayList<Clo>();
java.lang.String[] strArr = c.element().split("\n");
for(int i = 0; i < strArr.length; i++) {
Clo clo = new Clo();
java.lang.String[] temp = strArr[i].split(",");
clo.setCatLib(temp[1]);
clo.setCausalValue(temp[7]);
clo.setDuetoValue(temp[5]);
clo.setModelIteration(temp[8]);
clo.setOutlet(temp[0]);
clo.setPrimaryCausalKey(temp[6]);
clo.setProdKey(temp[2]);
clo.setPublished(temp[9]);
clo.setSalesComponent(temp[4]);
clo.setWeek(temp[3]);
c.output(clo);
clx.add(clo);
}
}
Let me know if its done correctly because while executing the code and getting error as No Coder has been manually specified; you may do so using .setCoder().
1> what shall I implement in ExtractObjectsFn() so that the records gets converted into BeamRecords ?
In the processElement() method of ExtractObjectsFn, you simply need to convert a CSV line from the input (String) to a Clorox type. Split the string by the comma delimiter (,), which returns an array. Iterate over the array to retrieve the CSV values and construct the Clorox object.
2> How to write the final output to a csv file ?
Similar process as above. You simply need to apply a new transform that will convert a BeamRecord to a CSV line (String). Members of the BeamRecord can be concatenated into a string (CSV line). After this transform is applied, the TextIO.Write transform can be applied to write the CSV line to file.

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;
}

Non-static methods used in a static context error

I keep getting two errors for this bit of code about non-static methods used in a static context. This code uses an ArrayList of different objects of birds, cats, and dogs and puts them in the ArrayList called petList using an interface called Pet.
I get the same errors on the 4th and 6th line.
public static void Feed(ArrayList petList){
Scanner input = new Scanner(System.in);
String petName = input.next();
contains(petName, petList);
if(ifThere == true){
String feed = Pet.feed();
System.out.println(petName + feed);
}
else{
System.out.println("Unknown pet");
}
}
public boolean contains (String petName, ArrayList petList){
boolean ifThere = false;
int sizeList = petList.size() -1;
for(int i=0; sizeList > i; i++){
Pet booleanPet = petList.get(i);
String booleanName = booleanPet.getName();
if (booleanName.equals(petName)){
ifThere = true;
}
}
return ifThere;
}
In short : You can not call non static method from static method.
Solution : 1) Make your "contains" method as Static and it will solve the problem.
OR
2) (Assume the name of the class is Pet then create an instance of Pet class and call contains method :
your line 4 can be replaced by below code(C# style code) :
Pet somePet = new Pet ();
somePet.contains(petName, petList);
-- Extra Details:
Static method is a method which is never specific to any object. e.g. Addtion of 2 number. You
dont need to instantiate any class to call Math.Add() method because Add is static method.
You can also say that Static is a method which is not a virtual meaning you definitely know
which method is being called.