FAQ Database Discussion Community


Java call a method before constructor

java,methods,constructor,call
I have the class Map with a method setMapName which choose from an Enum mapName to set it, inside the constructor there is a rule to name a cell from the array sector either Alien or Human according to the mapName value, i want to test if the name of...

jQuery's .get() stole my elements. Ok, but why?

jquery,dom,methods
So I have been brushing up on my jQuery and have been playing with the .get() method. I understand that you can use it to put DOM elements into an array like $('p').get(); and then access their properties for example console.log($('p').get(0).innerText);. But I also noticed that when I tried to...

Palindrome Check in Java using two Methods will not compile [closed]

java,methods,compilation,palindrome
I was working on this for a class assignment, and I cannot for the life of me get it to compile. I keep getting this error: CPT236PalindromeCheckMethod.java:52: error: reached end of file while parsing } ^ 1 error I have tried adding, removing, and checking all of my braces, but...

Having issues with methods

java,oop,methods,constructor
Alright, I have a class assignment to create 3 predetermined methods for a rock, paper, scissors program written by the teacher. However, when I run the program it running the methods multiple times in a row. I've looked through the code several times and can't figure out the problem. Below...

Go array for method

pointers,methods,go
Can I use array and its pointer for Go methods? I have the following code: var array = [3]string{"A", "B", "C"} type arrayTypePt *[3]string func (m *arrayTypePt) change() { m[1] = "W" } func main() { (arrayTypePt(&array)).changeArray4() } But this code: http://play.golang.org/p/mXDEhmA9wk give me an error of: invalid receiver type...

Beginner Programming in Java - using an integer in a Dialog (JOptionPane) box from another method

java,swing,methods,joptionpane
I have just started using Java and I am trying to write some code which will take some Inputs using Dialogue boxes and then transform/manipulate those Inputs further I can get the desired answer if I only use one method but I am trying to use multiple methods. I believe...

How many parameter in this printf() function? [duplicate]

c,methods,arguments,printf
This question already has an answer here: How does printf handle its arguments? 5 answers I am very new to programming. Now I am learning C. Please look at this following code snippet - printf("StudentId: %d CGPA: %f", id, cgpa); printf("Name: %s StudentId: %d CGPA: %f", name, id, cgpa);...

Meteor template helper not returning value

javascript,templates,methods,meteor
I wrote a method to return a value onto the client: Template.Cart.helpers({ cartPrice: function(result) { Meteor.call('returnCartPrice', function(error, result) { if(error) { alert(error.reason); } else { alert('result is ' + result); //this alerts return result; } alert('result is ' + result); //this does NOT alert return result; }); } }); cart.html:...

Calling User Defined Function In User Defined Class

php,function,class,methods
I am trying to create a custom class that will handle mailing for me. Here is my class (mailerclass.php) : class Mailer { // Private fields private $to; private $subject; private $message; // Constructor function function __construct($to, $subject, $message) { $to = $to; $subject = $subject; $message = $message; }...

Passing a class instance as a parameter to one of its own functions

objective-c,function,class,methods,properties
When a class of properties (let's call it class_X) is being instantiated from another class, all of class_X's methods and functions are also included in every instance. Q1: Wouldn't that add substantial overheads, especially if there are multiple instances of that class? The class instance (class_X) could then be passed...

How can I write this private method for being unique to the ticket number, and set that ticket number constructor?

methods,constructor,private
ParkingTicket Here are the relevant attributes: ticket number of type String the name of the police officer who issued the ticket the police officer's badge number the car's license number the car's make the car's model amount of the fine Note that the ticket number must be unique, created by...

Assigning a variable from another class

ios,objective-c,methods,protocols
I have a UIView with a UIButton created in 1 class: "viewClass". In my mainVC class, I called viewClas and I needed to call a method in mainVc when the button is selected, so I created a protocol. (I hope that was clear.) Here's how I set up the protocol...

Downcasting doesn't work and functions called from object own class instead of where the function is (Java)

java,class,oop,methods,casting
i have this classes hierarchy: public class Musician { private String name; public String instrument; public Musician(String name, String instrument) { this.name = name; this.instrument = instrument; } public String getName() { return name; } public String getInstrument() { return instrument; } private String getClassName() { return "Musician"; } public...

Simplify code with sending Methods as Variable

c#,variables,methods
I want to load XML into my program. most parts of code have same body with a little difference. this part is used in many methods.but with a bit differences. while (reader.Read()) { if (StateElement(State.Enter, "EnterElement", reader))// "EnterElement" is Variable { LoadElement(reader, type);// Method LoadElement and type are variables }...

Finding numbers within a certain range in an arraylist

java,netbeans,methods,arraylist,range
I have an Integer array list that collects numbers that the user inputs. I have to display numbers within the array that <= 50, using a method. How can I do this? public static double levelR(List<Integer> marks){ for (int i= marks.get(0); i<= 50; i++){ System.println(marks.get(i)); } This is all I...

error about returning a string from a String method

java,string,methods
Why am I getting an error in both of these methods that say 'this method must return type string...when I am returning type string. I am trying to do the stupid ninety-nine bottles of beer on the wall question that I'm sure everyone had learning java. But in my book...

Python: new class, inheriting and overriding

python,class,if-statement,methods
I am trying to create a new class in Python, MyClass, with UserList as its base class, but I wish to override the __add__, append, and extend functions to avoid repetition, so that if items already appear in a list, they will not be added to it. I start by...

Java Generic Interface vs Generic Methods, and when to use one

java,generics,methods,interface,parameterized
I was wondering, aside from syntactic difference, when would one use a generic interface over a method that accepts a generic parameter? public interface Flight<T>{ void fly(T obj); } over public interface Flight{ void <T> fly(T obj); } ...

Python 3.x error with methods asking for input error is TypeError: __init__() takes 0 positional arguments but 1 was given

python,oop,python-3.x,methods,user-input
I'm attempting utilizing TeamTreehouse learning subscription & this Starting Out With Programming Logic And Design (3rd Ed) book to attempt learning programming & Python. Please don't shoot to kill me I'm learning. Goal: I'm attempting to set a Pet class with 3 fields/attributes/properties. The class will have 2 methods, set...

Apply method to array through for loop

arrays,loops,for-loop,methods
I am trying to apply a method to an array of arrays through a for loop. Unfortunately where I have inserted my array of arrays inside the checkGuess method, I am getting the error 'Local variable x defined in an enclosing scope must be final or effectively final'. I'm a...

Can't understand this Javascript function (function overloading)

javascript,function,methods,overloading
I'm reading Secrets of Javascript Ninja and came across an example that I cannot fully understand. This same example was cited by some other user here before, but their doubts are different than mine. Here is the example: function addMethod(object, name, fn) { var old = object[name]; object[name] = function(){...

Method nonvisibility of same instanceof but differing class

java,class,methods,visibility
I have something like the below: Item var; Depending on user input, it will be initialized as a different class: if (/*user input*/ == 1) { var = new Item(); } else { var = new Truck(); } The classes are defined as: public class Truck extends Item { public...

Java Failure on JUnit Case Calling a Method from a Subclass

java,methods,junit,subclass
I have the constructor Alieni from the subclass Alieni of the class Settore that sets the name ALIENI from the enum Nome to a certain Settore (composed by the integers coordinataX and coordinataY). The test I'm trying to make is to verify that after running the method Alieni to a...

How Can I Override Library Methods in Java?

java,android,methods,override
I'm working on a large Android project which is using Gson. The method fromJson() is called dozens of times in many files. I need to provide some special-case tests every time this method is called. Rather than going through and repeating the tests for each and every time this method...

JS: Is it possible “something(arg)” and “something.my_method(arg)” at same time

javascript,function,oop,methods
I know how create just a function something(arg) something = function(arg) { console.log('Function result', arg); } I know how create an object with function something.my_method(arg) something = { my_method: function(arg) { console.log('Method result', arg); } } Is it possible to write code, wher both something(arg) and something.my_method(arg) are exists? Like...

Replace method that adds an incrementing number to a repeated string

javascript,node.js,methods,replace
I have a document with a bunch of <a id="r"></a> tags, and want to add an incrementing number to each, so, <a id="r1"></a>... <a id="r2"></a>, etc. The loop that I currently have, doesn't seem to work. function(doc) { for (var i = 1; i <= doc.length; i++) { var number...

Javascript Calling a nested function from within itself

javascript,function,methods,nested,closures
If I run the following... function outer(){ function inner(){ } inner(); } inner will run the first time as expected. If I then try to run the following... function outer(){ function inner(){ inner(); } inner(); } inner will again run the first time as expected, but then fails at any...

Abstract class and methods, Why?

java,class,methods,override,abstract
Hope anyone can help, i am learning Java and as comparable to anyone else in this forum i guess i am a newbie to programming as well. I have come across a chapter on abstract class and methods but don't really fully understand what they are used for and why,...

Using same AlertDialog box multiple times with one variable change

android,function,methods,android-alertdialog
In my application i want to use a AlertDialog boxes in several places. I can to this by using the code everywhere i want the AlertDialog box. But it seems like a waste because it's the same code with only one change. How can i use the same code for...

How do I invoke a main() method of one class in another class?

java,class,object,methods,main
How do I invoke a main() method of one class in another class? I have two classes SaveData and DynamicTest. Both of the classes contain a main() method. I would like to want to run my main in DynamicTest class. How do I properly call SaveData? public class SaveData {...

if condition for multiple methods in a class

python,class,methods
I'm writing in python to get a better feel for good practices when using classes. I've written a few methods for a couple classes; dog and person. I have introduced a new method for dog called die, defined below: def die(self): if self.owner: self.owner.pets.discard(self) self.owner = None self.dead = True...

Basic CakePHP: Edit Post Method become Add Post Method

cakephp,methods,sql-update,edit
Currently following the blog tutorial however my database and their variable are different. I was looking through the "Edit Post" method and follow the step they given however they turn into "Add Post" method. What is the reason that cause it ? (I have set the hidden field at view...

Bounding type parameters of generic methods with interfaces?

java,generics,methods,interface,generic-method
So I have 2 versions of the same method. Version 1: public static <T> int countGreaterThan(T[] anArray, T elem) { int count = 0; for (T e : anArray) { if (e > elem) count++; } return count; } Version 2: public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T...

Schedule to run a method at periodic time in java

java,methods,timer,scheduler,runnable
I have to schedule a method to be executed when starting and periodically thereafter at intervals of 1 minute. For that I have done this: public void init(){ loadConfig(); //method which needs to be executed periodically Timer scheduler = new Timer(); scheduler.scheduleAtFixedRate(loadConfig(),60000,60000); } This is giving an error and it...

Get warning when convert double to NSDecimalNumber

ios,objective-c,methods,double,nsdecimalnumber
I'm trying to convert a double to an NSDeciamlNumber. Here is my code: - (NSDecimalNumber *)myMethod { double amount = 42; ... return [NSDecimalNumber numberWithDouble:amount]; // Get warning here } But I get the following warning: Incompatible pointer types returning 'NSNumber *' from a function with result type 'NSDecimalNumber *'...

Reference method from different class as curried function

swift,methods,currying
There are two merge methods in RACSignal: - (RACSignal *)merge:(RACSignal *)signal; + (RACSignal *)merge:(id<NSFastEnumeration>)signals; When I write RACSignal.merge it references static method: class func merge(signals: NSFastEnumeration!) -> RACSignal! How to reference object method? I can't write self.merge, because it is in wrapper class and self is not RACSignal....

Why does this code in java print a reference instead the result of invoking the method?

java,arrays,methods,reference,boolean
I am supposed to write a method that accepts 3 2-D arrays of This method should determine whether one of the matrices is the result of matrix addition of the other two. public class Matrix { public static void main(String[]args){ int [][] a = {{5,2,3},{4,1,6},{0,7,2}}; int [][] b = {{1,2,3},{4,5,6},{0,1,2}};...

PHPunit call magic methods

methods,mocking,phpunit,magic-methods
I have magic method getData. Is it possible to call following inside unit test: $this->attributeMock ->method('getData') ->with('additional_data') ->willReturn('some value'); $this->attributeMock ->method('getData') ->with('is_default') ->willReturn('something'); When I do this, I got: Failed asserting that two strings are equal. --- Expected +++ Actual @@ @@ -'is_default' +'additional_data' Is there some another way?...

What is the best way to decorate methods of a Python class?

python,methods,decorator
I am following below conventions to decorate certain methods in a Python class. I am wondering if there are some better ways to do the same. My approach certainly doesn't look good; the call to original member function doesn't look intuitive at all. from threading import Lock def decobj(fun): def...

Function does not return any value if called in a class

python,function,class,methods
I am trying to make my version of Zork & Adventures from the tutorial I found here This tutorial uses an Engine class that from a Map class select what scene must come next and so on. To select the next scene, the Engine takes the return value of a...

ios xmpp call another viewcontroller from oneview controller through appdelegate

ios,methods,xmpp
I am working on XMPP project. i have created connection and able to login successfully.but i have setup methods and all in appdelegate [connect] method. so when i am login in app successfully but when i have to fetch friend list then i have to again call appdelegate [connect] method...

Is it more efficient to have a print statement in a method besides main or does it matter?

java,performance,methods,main
This might be a dumb question but I'm teaching myself from a book and I noticed that a lot of examples have the print statement inside a method other than main. I was wondering if it makes a difference where you put it so I pasted the program I was...

Needing a private and public method for the same recursive function

c++,recursion,methods,private,public
We have recently been working on implementing recursive methods for several classes (trees, heaps, queues, linked lists, etc) in C++ for my computer science class. I have not been having any trouble writing the implementations for the methods, but something my professor mentioned briefly in passing confused me and she...

Issue with calling a method and updating graphics

java,methods
I have a KeyListener that works, but when I try to call a method such as getdx(), I'm not seeing any change. goal is to make a map move with arrows. I've searched google and stackoverflow in various places, chopped my code all up and it's now pretty messy. what...

Automatically Generate Google Mock Methods?

c++,methods,googletest,googlemock
I'm fairly new to C++ and Unit testing and I'm learning to use Google Mock and Google Test right now to test some code that I'm working with. Instead of writing all of the Google Mock methods manually, is there a way to point Google Mock to your class and...

Instance method returns correct array from one view controller but null from others

objective-c,xcode,methods,null,instance
This is my first post so apologies for any errors I make, but this has been frustrating me for hours now and I cannot find a solution. I have an app that uses a UITabBarViewController that has 3 tabs: FirstViewController, SecondViewController and ThirdViewController. I have an NSObject class (Manager) where...

Initialize Arraylist in method [duplicate]

java,methods,arraylist,initialization
This question already has an answer here: Is Java “pass-by-reference” or “pass-by-value”? 54 answers Following Question. I have a big amount of ArrayList attributes (basically the same as Kreuzlagerort20kg etc). Instead of initializing them all in the constructor (the part commented out) i'd love to initialize them inside the...

Java: Shuffle a Deck of 32 cards?

java,methods,shuffle
I've wrote this method on my own I want to know if there is a better way to do it? public Card[] Shuffle(){ for(int i = 0; i < Deck.length; i++){ int x = i + (int) (Math.random() * (32 - i)); Card temp = Deck[i]; Deck[i] = Deck[x]; Deck[x]...

how to post parameter like {“register_id”:“3”} in AFNetwroking

post,methods,parameter-passing,afnetworking,raw-data
i Tried it but didn't work in AFNetworking only showing parameters error but i used postman to check and when i send data via key and value it showing error but from raw data i send {"register_id":"3"} then it will show me data so how to post parameter like this...

What Is The Difference Between Passing Parameters By Output And By Reference In C#

c#,methods,parameters,parameter-passing,pass-by-reference
I have been making an effort on C# methods. There are three ways that parameters can be passed to a C# methods. Value parameters : This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside...

Passing “this” as a Method Argument - Clarification

java,swing,methods,this,actionlistener
I am currently working on Java Swing lessons after finishing my first set of lessons in Java. In this lesson, we are working on communication between different components (buttons,toolbars,etc.) that we have been studying. The problem is, "this" is being passed as a method argument for the addActionListener() method. This...

Practical Reasons to use C# “named arguments”

c#,methods,parameters,arguments,optional-parameters
I find this feature "named arguments" from C# to be really weird because I see two flaws from it. The book says "named arguments give you the "ability to pass arguments in any order". Two flaws I think is a problem for this C# feature: It violates "information hiding" in...

Why don't I get any output?

c++,class,methods,output
I am trying to write my first OOP code in C++, but for some reason I am not getting any output. I am trying to create a class that contain a method getSquare() that accept an int n and returns the number squared. Can anyone tell me where I am...

How to restrict parameter types in generic methods

c#,generics,methods
Say I have 3 classes: A,B and C. Each of these class have a GetValue() method, which returns an int. I want to create this method: int GetTotalValue<T,R>(T c1, R c2) { return c1.GetValue() + c2.GetValue() } Obviously, this won't work. As not all parameter types have a GetValue() method....

What is the error in each Java Statement?

java,class,object,methods
//a. Rectangle r = Rectangle(5, 10, 15, 20); //b. Rectangle r; r.setSize(50, 100); //c. Rectangle r = null Is that right that "new" operation is missing in a? e.g. Rectangle r = new Rectangle(5, 10, 15, 20); ...

Why can't I call a method I define in a field? [duplicate]

java,oop,methods
This question already has an answer here: Calling newly defined method from anonymous class 5 answers Consider the following code. B.java public class B { void foo() { System.out.println("foo"); } } A.java public class A { B b = new B() { void lorem() { System.out.println("Lorem"); } }; void...

How to link code for button function to checkboxlist in C#?

c#,button,methods,checkboxlist,asp.net-4.5
I would like to link the function of my Chart Output Button to the items in my check box list such that when an item in the check box is selected or deselected, the page is reloaded again and my chart is refreshed. My codes to refresh the chart have...

How to pass args when calling one method from another

java,android,methods,parameters
I have written the following code to create a key pair, store the private key locally, and then read the private key from that file. When I try to call the methods savePrivateKey(); and retrievePrivateKey(); from testData(View view) I get an error that says (String[]) cannot be applied to ()....

Removing items from an array

java,arrays,methods
Just started taking Java 2, and it has been over 6-7 months since I've taken Java 1 and done much programming at all, so please be kind if I did something dumb The majority of the three classes below are for a previous assignment where you took a listing from...

method overriding Vs class variable overriding in java

java,methods,member,overriding
I was just trying some sample code for checking class variable overriding behavior in Java. Below is the code: class A{ int i=0; void sayHi(){ System.out.println("Hi From A"); } } class B extends A{ int i=2; void sayHi(){ System.out.println("Hi From B"); } } public class HelloWorld { public static void...

Updated Method signature is not working in wcf RESTful services

wcf,rest,methods,overloading,fiddler
I have a method like this [WebInvoke(UriTemplate = "StrDetails", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] public List<StrSearchDetails> StrDetails(string str1) { List<StrSearchDetails> details = new List<StrSearchDetails> (); return details; } I am able to hit this method from Fiddler I have updated and replaced like this [WebInvoke(UriTemplate = "StrDetails", ResponseFormat =...

Calling “Form” class method from “A” class without adding a reference to the “Form” class

c#,winforms,methods,class-library
I have two Projects one is a Winform application another is a Class library. I have added a reference to the class Library in Winform and called a method of the class library. Now I want to call a different method in winform application from class library but I can't...

Variables are leaking from my methods in C#

c#,methods
I have currently have a block of code that is repeated throughout my program inside Button Clicks with the exception of a few variables. The issue is that when I go from clicking one button to another button, plHTML starts leaking text from the previous button. This did not happen...

How to .count instances of current_level 6?

ruby-on-rails,ruby,methods
I'm trying to .count on current_level when it's specifically at 6. How should I write the method in habit.rb? def current_level return 0 unless date_started def committed_wdays committed.map do |day| Date::ABBR_DAYNAMES.index(day.titleize) end end def n_days ((date_started.to_date)..Date.today).count do |date| committed_wdays.include? date.wday end - self.real_missed_days end case n_days when 0..9 1 when...

Object Oriented Python - rectangle using classes and functions

python,function,class,oop,methods
I am creating a program in Python that will utilize object oriented programming to print the properties of a given rectangle. The project has these given constraints: The purpose of this lab is to give you practice creating your own object. You will be given a main function that expects...

Run class methods in different threads

java,multithreading,object,methods
Let's suppose I have this class: public class Myclass { method1(); method2(); method3(); } I want to know if there's a way to run all 3 methods in different threads simultaneously. Is there a way to create a class MyThread : public class MyThread{ //implementation } in way that it...

Method error using jquery

jquery,methods,meteor
I keep getting that message in my console when calling my method: Exception while invoking method 'displayAndAddPost' ReferenceError: $ is not defined However everything works fine so I am not sure how to properly use Jquery and stop that error message. Here is the invoked method: Meteor.methods({ displayAndAddPost: function(word, counter)...

wrapMethod Meteor methods

javascript,methods,meteor
I was looking into this presentaton, builindg large meteor applications, and i like the idea of the wrapMethod(), but it seems like i cant use it like on the example. Here is my code. Meteor.methods({ 'EX.Accounts.Methods.updateProfileData' : function(userId, firstName, secondName) { check([firstName, secondName], [String]); Meteor.users.update(userId, { $set: { 'profile.firstName': firstName,...

JFrame not including certain variables

java,swing,methods,jframe
I am new to using JFrame. I have a JFrame class that is separate from the main class. I have been having trouble getting it to work, like separating it from the main class. I have an issue though where a constructor in my JFrame class is not used, and...

Discover all PSmethods of an object

powershell,methods
When I run this command: $psise.CurrentPowerShellTab.AddOnsMenu.SubMenus | GM The result does not show me the methods Remove & Removeat which I know do exist. So how do we discover all the methods available to an object? I have run GM -force but still don't see the Remove methods. Are these...

java object oriented programming [closed]

java,arrays,methods
first off im new here. and i dont know if some peoples will be able to help me but i hope somebody can help me. the thing is we will have an java exam about object oriented programming , methods and classes and i wasnt there when we had that...

Execute a method from a class in mainActivity (Android)

java,android,methods,call
I m trying to execute a method from a class called QrScann in the MainActivity class when the user click on a button but everytime the app crash as soon as I click the button and it gives me this log crash output 06-02 17:00:24.890 7067-7084/t.n.app W/EGL_emulation﹕ eglSurfaceAttrib not implemented...

Why can I call all these methods that aren't explicitly defined in a class?

python,oop,methods,vk
So I am working with an API wrapper in python for vk, Europe's Facebook equivalent. The documentation on the vk site has all the API calls that can be used, and the wrapper is able to call them correctly. For example, to get a user's information, you would call api.users.get(id)...

How to handle empty parameters in a main method java call

java,methods,jar,call,main
I would like to have a dynamic way of passing in parameters to a java main method call which is done via the Command Line(cmd) to a Runnable JAR file. At the moment my main() method takes 6 parameters and sets each one to a variable before calling another method...

How to properly call handler method in C#?

c#,methods,parameters,handler
I am having issues with the following method below -GetTransactionsCompletedEventHandler. I am attempting to pass the necessary arguments to it, but it is also asking for more parameters in a format I am unfamiliar with. It is asking for GetTransactionsCompletedEventHandler(object[] results(object, GetTransactionsCompletedEventArgs)target) Can anyone point me in the right direction...

Angularjs .factory method return

angularjs,methods,return,factory
I have been able to get this .factory to work by adding a "return" in front of both the Restangular.all statement and the response. My question is why is it needed there? Why can't I just return the response? app.controller('MainController', ['GetIndexesFromES', '$scope', function(GetIndexesFromES, $scope) { $scope.indices = GetIndexesFromES.getUniqueIndexIDs(); console.log($scope.indices); }]);...

C# Recursion Error - Extension Methods

c#,loops,methods,infinite
I get an error here saying that the program could not exit the infinite loop. public static class Program { public static void Main(string[] args) { Object obj = new Object(); Console.WriteLine(obj.GetClassName()); } public static string GetClassName(this object value) { return value.GetClassName(); } } ...

java - How to retrieve anything inside method

java,methods,constructor,local-variables,bcel
From what i know, java cannot retrieve anything inside method. so i using option -g or -g:vars in javac. for e.g : class Test { int a=0; void method(boolean boo){ String b; try { new Thread().sleep(1000); } catch(InterruptedException e){} JOptionPane.showMessageDialog(null,"test"); BufferedImage image=ImageIO.read(new File("C:\\file.png")); } } So, i use BCEL to...

Using NON static class Methods Without reference

java,object,methods,reference,static
I'm new to Java. I know the concept of static and non static method. I'm wondering if it's possible to use non static methods of a class without having to create a reference to it. Like for example, for my program I'm working with Date objects, and I need to...

When to use $this->$property

php,class,oop,methods
I am having trouble understanding when and why you need to use $this->$property. So adding the $ to both the the this keyword and the property. I have only seen this used within the magic methods __get() and __set(). Can anybody elaborate?

Call model method from different view

ruby-on-rails,ruby,methods,model
I have a model method def full_name_find(user_id) user = User.find(user_id) "#{user.first_name} #{user.last_name}" end that is in the User model. I would like to call it from another view (tickets#show) and I can't seem to get it to work. I tried: <%= User.full_name_find(comment.user_id) %> where comment has a user_id. I get...

Method works if called from one Class but not from another

java,methods,reference
I am new to Java. I am working on a GUI for Serial Communication between a PC and a Microcontroller. I am using the RXTX Library and it works. As i want to be able to modify the GUI from another Classes, i built the Programm as follows: 1: Main...

Invoke a custom method on a DOM element

javascript,jquery,dom,methods,invoke
I want to invoke a custom method on a DOM element like this : <div id="MyObject"> <!-- some elements --> </div> <script> function doSomething() { // do something with input DOM element } $("MyObject").doSomething(); </script> How can I develop this problem? Is it necessary to use jQuery or not?...

Quadrature sensor sinus signal to distance value

c,algorithm,math,methods,sensor
From a sensor I have 4 signals in quadrature. Two signals are analog and two are digital. The signals represent the position of a pickup sensor, se figure. The signals are: A-Analog B-Analog A-Digital B-Digital The analog signals are phase shifted by 90 degrees. The digital signal is produced by...

What is the correct way to use System.exit() method in java and call a method after? [closed]

java,methods,main,exit
How do I create an option in my program where the user can exit the program? For some reason, it won't let me exit it using System.exit(). I've debugged and found that the only problems with the program are with these lines: else if (input==6){ System.exit(); } else{ main(); }...

Calling an object and its method from another object class method

javascript,class,oop,object,methods
I have created some classes/objects for some animations. I created a class called Navigation(), and another class called Stars(). Each of the classes have their own methods and objects associated with them. I have created a method within the Navigation() class that attempts to run a method and the object...

JUnit to test for StringBuffers

java,methods,junit,stringbuffer
Assignment: Write a JUnit test assuming you have two StringBuffer references named sbOne and sbTwo and you only want it to pass if the two references point to the same StringBuffer object. I want to make sure this actually a good way to approach this assignment. I wrote the assumed...

'.class' expected when trying to pass a double Array in Java

java,arrays,class,methods
I'm a newbie of Java, and while studying it I found out an exercise who killed my brain for almost 7 hours. I tried everything I knew, I read the chapter of the book once again, I've googled for an answer for hours, and even used the Search button here,...

PDO class use chain method

php,class,oop,methods,pdo
This is my "wrapper" class, over PDO (it is larger, this is the important part right now) class DB { protected $pdo; protected $dsn; protected $username; protected $password; protected $driverOptions; protected $query; public function __construct($dsn, $username = '', $password = '', array $driverOptions = []) { $this->dsn = $dsn; $this->username...

Shoppe gem each method on product categories

ruby-on-rails,ruby-on-rails-4,methods,gem
Just wondering if anyone with any experience with Shoppe know how to call an each method on product categories? I'm trying to do something like this : <% Shoppe::ProductCategory.each do |prod| %> <li><%= prod.name %></li> <% end %> but I'm getting an undefined method error. Is there some special method...

Can inherited method access subclass fields in Java

java,inheritance,methods
I'm having trouble understanding inheritance. In the code below, why doesn't the inherited method access the field in the subclass? Is there any way to access the subclass field without overriding the inherited method? class Fish { private String fishType = "Fish"; public String getFishType() { return fishType; } }...

Resharper intellisense : how to show method return type

methods,resharper,intellisense
I've formatted my pc, and now i can't seem to find the option to show the method return type in the intellisense... Using VS 2015 RC with Resharper 9.1.1 Thanks, screenshot below. ...

Why should we use a List of a particular type in Java

java,methods,arraylist,static,format
I am currently going through a lesson in Java, and this lesson covers passing an ArrayList object through a static method. In the first static method, you see that ArrayList only had to be declared as ArrayList, and a name for it. The first static method displays all of the...

Add hash argument or string argument in a method to a hash (Ruby)

ruby,methods,hash,arguments
If the argument "entry" to the method add is a hash I need to add it to the :entries hash. If "entry" is a string "entry" needs to be set as a key in the hash and its value to nil. I have a solution below but is there a...

handle different instance variables in method

java,methods,instance-variables
So if I have a method where a variable can be an instance of a bunch of different classes where only some of them have a specific instance variable, how do I use this instance variable in the method without getting the cannot be resolved or is not a field...

What does the `.select` method do in Ruby? [closed]

ruby,methods
I don't know what it does. It's there in many programs. I've never really used it. Could someone clarify, with examples, please? arr = [15, 20, 132, 144, 100, 101, 34] s = Proc.new { |x| x<100 } new = arr.select(&s) ^ The specific snippet I was talking about....

setting objects equal to eachother (java)

java,methods,compiler-errors,equals
So I have a class called Person which looks like this public class Person { private String personName; public String toString(){ return personName; } public Person(String personName){ this.personName = personName; } } and another class in which I am creating the object(s) person public class IdanJavaTask { public static void...

Return out of method instead of returning anything or null [on hold]

c#,methods
public static string DecryptString(string EncryptedString) { try { ....... .... } catch { return something else if decryption fails instead of null or empty string; } } I am trying to return error if the decryption fails not the string....

Why “if” is not doing anything in this boolean method?

java,methods,boolean
import java.util.Scanner;//import Scanner public class review{ //name of the program public static void main(String[]args){ // main statement Scanner i=new Scanner(System.in); System.out.println("Enter a string"); String b=i.nextLine(); System.out.println("Enter a letter"); char c=i.next().charAt(0); System.out.println("Answer is "+test1(b,c)); } public static boolean test1(String a, char b){ boolean result= true; for(int i=0;i<a.length();i++) if(a.charAt(i)==b) result =true; else...

form post method not working

php,html,post,methods
<html> <head> <title>Register</title> <head> <body> <h3>Register Page</h3> <a href="index.php">Click here to go back</a></br> <form action="register.php" method="post"> Enter Username: <input type="text" name="username" required="required"/></br> Enter Password: <input type="password" name="password" required="required"/></br> <input type="submit" value="Register"/> </form> </body> </html> <?php if...