I would like to know if the following code should work:
if (M != 0){
Tools.Printer(stdnr);
}
Background Info:
I created a public class Tools with a few functions. One of the functions is the void Printer function. Is there a rule or something that if you want to use Tools.something you need to do assign the Tools.something to an integer / print it, etc. Or is Tools.Printer supposed to work on its own.
I ask this because I can't find anything wrong with my code. I would be glad if someone can help me right with the terms I used above - I suppose they are terribly wrong...
Thank a lot, Help would be greatly appreciated
If your method is a void type, it returns nothing, therefore you do not need to assign it to a variable (in fact, you'll get a compile time error if you do).
If it was instead a function, like it returned some value, for instance:
public String foo()
{
return "kdfldj";
}
You still don't necessary need to assign it to a variable. The returned value will just be discarded. For example, StringBuilder.append returns back the StringBuilder that you just appended to, but you can safely call it like this:
myStringBuilder.append("some text");
And ignore the return value.
However, if your Tools.Printer method is not a static method, you do need to create an instance of Tools, either assigned to a variable like this:
Tools tools = new Tools();
tools.Printer(stdnr);
or initialized without being placed in a variable:
new Tools().Printer(stdnr);
But if Printer is a static method, your code should be fine, since you are calling the method by the class it's contained in.
Related
I am looking to add a function to a program where I use static variables to create a list of all the times the driver has used the constructor, using names. What I need to know is this, is there a way, in java, to access what the reference variable is (as a string) to add it to the list?
Pseudocode:
public ClassName
String static list = "";
Public ClassName (parameters){
list += getReferenceVariable();
}
The getReferenceVariable is what I'm asking if anyone knows a way to do that
If I understand you correctly, you want to keep a list of all the times the constructor was called, and save the names of the currently-being-created variable? Because the "Reference variable" is none when you use the constructor, since you call the constructor with a new MyClass(), and not some obj.MyClass().
If, however, you simply want to know who called you (As a stack trace is), you can simply, as written in this thread (no pun intended), use
Thread.currentThread().getStackTrace(), and then choose the desired stack frame (Probably 2, since The first element (index 0) in the array is the java.lang.Thread.getStackTrace method, the second (index 1) is the constructor, and 2 is where the constructor was called from), where you can get (for example) the name of the source file that this stack trace corresponds to. Documentation of getFileName()
Since I haven't tried it on my end (not possible at the moment), I give you code to use with caution:
public class MyClass(){
MyClass(){
callerName = Thread.currentThread().getStackTrace()[2].getFileName();
... // anything here
}
}
I'm having issues with a concept from an assignment I'm working on
public class MyHugeInteger
{
MyIntList list = new MyIntList();
public int compareTo(MyHugeInteger hugeInt)
{
if (list.size() > this.list.size()) //this is where things don't work
return (-1);
if (list.size() < this.list.size())
return (1);
}
Basically, I need to be able to use the 'list' variable from the passed version of the object to be able to compare it to the list variable from the current object.
I had a similar problem to this before, and my professor responded with "objects of the same class can access each others' private data members. So you do have access to other.size from "this" and can check Set sizes for equality."
This is what I'm trying to use in the code given, but I found an example saying that this will call the field variable, the one already called by just saying 'list'
Am I missing something?
The comment was right, hugeInt.list.size() > this.list.size() instead of using 'this' for the passed object. One of those things that you miss when you're overthinking the problem
If you're trying to use the Java framework to sort things or use the compareTo method, as intended, you need to implements Comparable<MyHugeInteger> in your class.
public class MyHugeInteger implements Comparable<MyHugeInteger>
Then, to fix the error, you need to use the parameter object because this.list and the unqualified list are the exact same object.
Also consider what happens when sizes are equal.
Tip: don't need to rewrite the integer comparison logic yourself.
#Override
public int compareTo(MyHugeInteger hugeInt) {
return Integer.compare(this.list.size(), hugeInt.list.size());
}
Multiply by negative one or flip the parameters if you notice the ordering is wrong.
My assignment is to create a program that simulates a simple online shopping program.
we have to:
create a main menu with 3 options and then a submenu when selecting the 2nd option on the main menu.
I'm unsure how call a method from another class for example:
I have been given a method:
public void start() {
which is in the file "GroceryStore.java"
I am supposed to create a topMenu method which when the user inputs "1" calls to the method:
public void displayItems(){
^in file called "Stock.java"
which then prints out an array of items that online store has in stock. The array in the
Stock.java is
private SalesItem[] items;
Can anyone tell me how to do this? I have to do this for several things and I'm hoping I can apply the skeleton of this to the rest of the cases.
For now, I'm going to assume that Stock is an instance type(it sounds like an instance type), and It would make sense that your GroceryStore would have a reference to 1 or more Stock items.
Your Stocks will have to be instantiated with the new keyword. so
Stock myStock = new Stock(/*parameters for constructor*/);
after you do that, you can call the displayItems method of myStock like so
myStock.displayItems();
so start() is in the GroceryStore class.
So in a public static void main class you would go :
GroceryStore gs = new GroceryStore();
gs.start();
In your GroceryStore class you would have a new method which looks like (You may want to have the Stock stock = new Stock() line in the constructor of the GroceryStore object-- would make more sense:
Stock stock = new Stock();
public void topMenu(int parm){
if(parm==1)then{
stock.displayItems();
}
}
And then finally in the Stock class you have the displayItems method which may look like :
public void displayItems(){
for(int i=0;i<items.length;i++){
SalesItem temp = items[i];
System.out.prinlnt(temp.toString());//or this may be temp.getName() or whatever returns a string from this SalesItem object - I dont know what it looks like - you never said!
}
}
It is however essential you actually understand what is going on here not just copy paste and run?! This wont actually do anything anyway until you have a call to the topMenu method passing it 1, so you will need to workout how you are going to interact with your gs object whether its by keyboard input, mouse click on a gui or something else :)
To call a method outside the current instance you have multiple options:
make the method static (so that it won't be attached to any particular instance) and call it through MyClass.method(), this has sense if it is a stateless object, mostly an utility method
create a static instance variable that can be accessed (so method is not static but the specific object is), then call it through SomeClass.stock.method(), this has sense when you want a single object of a specific type throughout the program
create a normal instance variable inside the class from which you want to call the method (this has sense just if the object contained is used in a HAS-A relationship). Then you call it simply doing this.stock.method() (you can omit this)
You need to tell the compiler where to get the methods from if the method is not in the same class. The best way of doing this would be to create an object that refers to the class you're trying to reach (using the New Java keyword and the appropriate syntax, i.e. ClassName objectName = new ClassName() - you may want to include any parameters you may have).
Have a look at this other StackOverflow answer - the user had a question very similar to yours, so it may help.
Also, there is a pretty good tutorial on objects and classes on TutorialsPoint. I suggest you have a look at it and give it a go. Try understanding the concept behind what you're trying to achieve first - I can guarantee you it will help later on as this is a very fundamental concept in OO programming.
Suppose I want to test a method Foo.doSomething(String arg):String using EasyMock. I know that I can use EasyMock Capture in order to capture the value set inside of the parameter and then get it at a later time. When writing my test, my goal is to capture the value when I mock out Foo's method and then get the value of the capture outside of my mocked method. I am trying something like this:
Capture<String> stringCapture = new Capture<String>();
EasyMock.expect(foo.doSomething(EasyMock.capture(stringCapture)).andAnswer(new IAnswer<String> {
#Override
public String answer() throws Throwable {
...
});
String retrievedValue = stringCapture.getValue();
However, I get a runtime error when I try to use getValue():
java.lang.AssertionError: Nothing captured yet
at org.easymock.Capture.getValue(Capture.java:80)
at com.example.Test.myTest(...)
....
I wish I could have a String variable within my test method but outside of the IAsnwer closure and set that variable's value inside of my IAnswer.answer() method. The problem is that the String variable must be marked as final in order to be accessible to the closure, which makes it unmodifiable and hence useless. Also, I do not wish to use a global just to solve this.
The only workaround I've thought of it to use my own class that has a String field, declare it as a final variable outside of IAnswer, set the captured value during answer() and finally set this value into a field within my test method. Perhaps there's a better way to do this because using another class to extract a captured value, or even a global variable, seems ugly to me.
The getValue will only work after the actual (replayed) call to foo. Before that, nothing is capture.
To set a variable inside answer(), because of Java requesting variables used in an inner class to be final, I normally use an AtomicReference. It's a nice placeholder for such things. The AtomicReference is then final but its content isn't.
I do an import of the full package name / java file, and if I do a <classname>.<method>, SOMETIMES I can get it to access - other times I get a lot of can't use a static in a non static bunch of talk.
I'll admit I'm new to Java, so what do I need to do? Call a class instance first, then call my methods? I'm rather confused by this, as I want to put all of my 'functions' into a FunctionsList.java file, and all of my main Activity (UI) into a MyActivity.java file.
For example:
<MyActivity.java>
import com.example.FunctionsList;
private class MyActivity extends Activity {
FunctionsList.function();
}
9/10 times I get that static/non-static error.
If I put all of my functions into MyActivity.java, I have zero problems! Anyone help me on what I presume is a basic Java newbie issue?
Here's an example that will hopefully help you out a little.
public class MyFunctionClass {
public String myFunction() {
return "This is an instance function.";
}
public static String myStaticFunction() {
return "This is a static function.";
}
}
Then in your activity you have something like this.
public class MyActivity extends Activity {
#Override
public void onCreate() {
// If you want to call your static function, you do not
// require an instance of a MyFunctionClass object.
String myStaticString = MyFunctionClass.myStaticFunction();
// If you want to call your instance function, then you need
// to create a MyFunctionClass first.
MyFunctionClass variableName = new MyFunctionClass();
String myInstanceString = variableName.myFunction();
}
}
As Jon mentioned, you'll probably save yourself some frustration if you read up on object-oriented programming before diving in. There are some basic things that a new programmer will need to understand before diving in. Good luck!
If you want to use a non-static method, you have to have an instance of the class to call the method on. If you want to use a static method, you don't need an instance.
As an example, suppose you tried to call String.length() - what could that return? It's trying to find the length of something, but you haven't specified which string you're interested in. The same is true for other instance methods - the results will usually depend on which object you're calling them on, which is why they're instance methods to start with.
As an aside, I would strongly recommend you to learn the basics of Java first, before trying to use Android. That way when you get into genuinely tricky problems, you won't have to wonder whether it's part of Android or whether it's a simple Java error. See my answer on a related question for more advice about this.