Use the Object that is calling the method - java

Apologies for the terribly worded question, but I'm a bit new to Java and still a bit unsure how to word my problems/ not really sure if it's possible to do what I want to.
I have a class called ClassA which has a trivial method returnInt that looks something like this:
public class ClassA {
private int numberino;
public ClassA(Int int) {
this.numberino = int;
public boolean isPositive(){
if (this.numberino > 0){
return true;
return false;
public int returnInt() {
final int addVal = 2;
int sum = 1
sum = addVal*numberino + sum;
return sum;
}
Now when I call this method in another main loop, like:
ClassA temp = new ClassA(7);
temp.returnInt();
My question is, is there anyway I can pass the object temp into the returnInt() method, so I could perhaps use the isPositive(int) method on it without changing the structure (by passing in an argument) of the returnInt() method?
Something like this is how I would imagine it being (but I know it's wrong);
public int returnInt() {
final int addVal = 2;
int sum = 1
if (temp.isPositive()){
sum = addVal*numberino + sum;
}
return sum;
Where that temp is Object being created and the method returnInt() is the method being used from it.
I hope that makes sense.
Thanks!

returnInt is an instance method of ClassA, so it can call any method of ClassA. There's no need to pass anything.
public int returnInt() {
final int addVal = 2;
int sum = 1
if (isPositive()) { // or this.isPositive() if you want to be explicit
sum = addVal*numberino + sum;
}
return sum;
}

Related

Alternative to pointers in Java

#include<stdio.h>
void decrease(int *i);
int main(){
int i = 10;
decrease(&i);
printf("%d",i);
}
void decrease(int *i){
*i = *i - 1;
}
What would be the Java program for the same?
As you pointed out (no pun intended), Java does not support pointers. So, there is no way to directly manipulate the value of a primitive passed to a method, because only a copy of the primitive would be used in the method. One way to get around this would be to just return the updated value, and then overwrite the integer in the calling scope:
public static int decrease(int i) {
return i - 1;
}
public static void main(String[] args) {
int i = 10;
i = decrease(i);
System.out.println(i); // prints 9
}
You have two options, either (return) the value, and modify it in the main class, or pass an Object, not a primitive.
An object with your values:
public class Holder {
public int x;
}
And a method to modify it
public void modify(Holder h){
h.x = 2;
}
Called like:
Holder h = new Holder();
h.x = 1;
modify(h);
System.out.println(h.x);
Results in:
2

Passing two variables to one method to get two results

I am trying to pass two variables along to a method and have the method give me back two independent results.
int numX = 5;
int numY = 3;
System.out.println(displayTwiceTheNumber(numX, numY));
}
public static int displayTwiceTheNumber(int numX, int numY) {
int numW, numZ;
numW, numZ = 2 * (numX, numY);
return numW numZ;
}
Java takes it that at numW, numZ = 2 * (numX, numY); that I am trying to redefine numX and numY. How do I phrase the last block to take two variables and give two results?
A single int function can only return 1 int at a time.
If you want to return 2 values, consider calling the function twice or creating a custom object to be used.
You need to change the return type of the function. Currently, the return type is int, so you have to return one integer.
To return two integer, you should consider returning an array or a list or something similar.
public static int[] displayTwiceTheNumber(int numX, int numY){
//your code that do something
int[] ret = {numW, numZ};
return ret;
}
Or knowing that this function would change the value of numW and numZ, you could declare those as global variable. Now, when you call this function, those variable will be changed. Then, you can use numW and numZ subsequently.
public int numW;
public int numZ;
public static void displayTwiceTheNumber(int numX, int numY){
//your code that do something and modifies numW and numZ
}
public static void anotherfunction(){
//after calling displayTwiceTheNumber, numW and numZ would have the appropriate value
//you can now just use numW and numZ directly
}
Overview: Use a tuple. In this example I use an tuple to return more than one result. Tuple means to return more than one result type. In this example I return a tuple of two integer types. My class TupleCustom contains one method function1 which receives two parameters of type integer: x and y. I create a tuple of type integer and return the tuple as a variable. Internally, the precomiler converts the tuple json than back to a tuple with variable Item1, Item2...ItemN in the unit test method.
public class TupleCustom
{
public async Task<Tuple<int, int>> Function1(int x, int y)
{
Tuple<int, int> retTuple = new Tuple<int, int>(x, y);
await Task.Yield();
return retTuple;
}
}
public class TestSuite
{
private readonly ITestOutputHelper output;
public TestSuite(ITestOutputHelper output)
{
this.output = output;
}
[Fact]
public async Task TestTuple()
{
TupleCustom custom = new TupleCustom();
Tuple<int, int> mytuple = await custom.Function1(1,2);
output.WriteLine($" Item1={mytuple.Item1} Item2={mytuple.Item2} ");
}
When I have this problem I create a private utility class for handling the return values. By doing it this way, you can pass various types in the argument list. Aspects of the class can be tailored to your requirements.
public static void main(String [] args) {
int numX = 5;
double numY = 3.0;
Nums n = displayTwiceTheNumber(numX, numY);
System.out.println(n.numX);
System.out.println(n.numY);
}
public static Nums displayTwiceTheNumber(int numX, double numY) {
int numW;
double numZ;
// do something with arguments.
// in this case just double them and return.
return new Nums(2*numX, 2*numY);
}
private static class Nums {
int numX;
double numY;
public Nums(int nx, double ny) {
this.numX = nx;
this.numY = ny;
}
public String toString() {
return "(" + numX + ", " + numY +")";
}
}
Prints
10
6.0

Setting variable values to be based on other variables

Say we have variables int a = 0; and int c;.
Is it possible to make it so that c is always equal to something like a + 1 without having to redundantly retype c = a + 1 over and over again
Thanks!
No, it is not possible to make one variable track another variable. Usually, this is not desirable either: when a value of one variable is tied to the value of another variable, you should store only one of them, and make the other one a computed property:
int getC() { return a+1; }
A less abstract example is a connected pair of age and date of birth. Rather than storing both of them, one should store date of birth alone, and make a getter method for computing the current age dynamically.
Since you have 2 variables tied in a specific way, consider using custom object to wrap a and c values. Then you can control the object state inside the class logic. You can do something like this:
public class ValuePair {
private final int a;
private final int c;
public ValuePair(int a) {
this.a = a;
this.c = a + 1;
}
public int getA() {
return a;
}
public int getC() {
return c;
}
}
Firstly, The answer is no, you can't do it directly in Java, but you can redesign your int class, There is an example:
public class Test {
public static void main(String[] args) throws IOException {
MyInt myInt1 = new MyInt(1);
KeepIncrementOneInt myInt2 = new KeepIncrementOneInt(myInt1);
System.out.println(myInt2.getI());
myInt1.setI(2);
System.out.println(myInt1.getI());
System.out.println(myInt2.getI());
}
}
class MyInt { //your own int class for keep track of the newest value
private int i = 0;
MyInt(int i) {
this.i = i;
}
public int getI() {
return this.i;
}
public void setI(int i) {
this.i = i;
}
}
class KeepIncrementOneInt { //with MyInt Class to get the newest value
private final MyInt myInt;
KeepIncrementOneInt(MyInt myInt) {
this.myInt = myInt;
}
public int getI() {
return this.myInt.getI() + 1; //get the newest value and increment one.
}
}
Create your own Int class, because we need a reference type to keep track of the newest the value a. like the MutableInt in apache commons.
Create a always increment 1 class with your own Int class as a member.
In getI method, it's always from the reference Int class get the newest value a.

How would I utilize a value returned from a method and implement it the main method in java?

Can I pass the return value from a method into the main method then utilize that value in another method? That sounds confusing but let me try to explain it better with some code...
public static void main(String[] args){
ArrayList<GeometricObject> geoList = new ArrayList<GeometricObject>();
findPositionLargestObject(geoList);
System.out.println("BIGGEST OBJECT AT "+ maxIndex +" AREA =
"+geoList.get(maxIndex).getArea());
showObjects(geoList.get(maxIndex));
}
//METHOD RETRIEVING INT OF ARRAYLIST
private static int findPositionLargestObject(
ArrayList<GeometricObject> geoList) {
int maxIndex = 0;
for (int i = 1; i < geoList.size(); i++) {
// AREA OF I COMPARES MAX INDEX
if (geoList.get(i).getArea() > geoList.get(maxIndex).getArea()) {
maxIndex = i;
}
}
return maxIndex;
}
// METHOD FOR PRINTING SINGLE OBJECT OF ARRAYLIST
private static void showObjects(GeometricObject geometricObject) {
System.out.println(geometricObject.toString());
}
Lets say I even instantiate the index in the main method such as
int maxIndex = 0;
I want the first method called to return the value, assign that value to the variable maxIndex then utilize that value for the showObjects method. Thanks for any insight that can be given to a coding novice like myself. Is instantiating the variable in the main method no good? What is the logic behind the JAVAC execution here?? The curriculum covered in my course feels like this is an enormous hole that needs to be filled. Basically, How do I utilize a value returned from a method then implement into another method?
Variables are only containers for a value bound to its type. If a method is returning a type, you can place it's return value in a variable located in another block of code. To provide a very basic example for an easier understanding of how this can work:
private String getString(int number) {
if (number == 2) {
return "Not One";
}
return "One";
}
private void printValue(String number) {
if (number.equals("One")) {
System.out.println("i is 1");
} else {
System.out.println("i is not one");
}
}
public static void main(String[] args) {
int i = 1;
String testNum = getString(i);//returns "One"
printValue(testNum);//output: i is 1
}
With this example in mind,
int maxIndex = findPositionLargestObject(geoList);
showObjects(geoList.get(maxIndex));
is valid.
Unless I'm missing something, assign the result of your function call. I suggest you program to the List interface. Also, if using Java 7+ you could use the diamond operator <> like
List<GeometricObject> geoList = new ArrayList<>(); // <-- diamond operator
// ... populate your List.
int maxIndex = findPositionLargestObject(geoList);
and then yes you can use the variable maxIndex
you can obtain the return value in main method like this,
int maxIndex=findPositionLargestObject(geoList);
Code:
public static void main(String[] args){
ArrayList<GeometricObject> geoList = new ArrayList<GeometricObject>();
int maxIndex=findPositionLargestObject(geoList);
System.out.println("BIGGEST OBJECT AT "+ maxIndex +" AREA =
"+geoList.get(maxIndex).getArea());
showObjects(geoList.get(maxIndex));
}
//METHOD RETRIEVING INT OF ARRAYLIST
private static int findPositionLargestObject(
ArrayList<GeometricObject> geoList) {
int maxIndex = 0;
for (int i = 1; i < geoList.size(); i++) {
// AREA OF I COMPARES MAX INDEX
if (geoList.get(i).getArea() > geoList.get(maxIndex).getArea()) {
maxIndex = i;
}
}
return maxIndex;
}
// METHOD FOR PRINTING SINGLE OBJECT OF ARRAYLIST
private static void showObjects(GeometricObject geometricObject) {
System.out.println(geometricObject.toString());
}

Understanding Java methods

So, I'm very new to Java, I have a summer college course and we're on functions or methods and I'm having a bit of trouble understanding them.
There is a question on a lab I'm having a little trouble with:
"Write a method called MaxOfThree that accepts three integer
parameters and returns the largest of the three."
This is what I have so far but I'm not sure whats wrong. I added the print statement at the end because I wasn't getting a return value when I ran it but now I'm getting errors and it's not compiling. If you could help me understand methods a bit more I'd greatly appreciate it. For instance how the parameters work and calling it and if what's included in the function call is correct and how that works. I just get so confused when I read through the material and was hoping for an explanation in more layman's terms. Thanks for any help, here is what I have so far.
public class Test {
public static void main(String[] args) {
int a = 2, b = 3, c = 4;
int maxValue = max3(a, b, c);
}
public static int max3(int a, int b, int c) {
int max = a;
if (b > max) max = b;
if (c > max) max = c;
return max;
System.out.println(max);
}
}
Here are the errors I'm receiving just in case...
Test.java:16: error: unreachable statement
System.out.println(max);
^
Test.java:17: error: missing return statement
}
^
2 errors
You can't have a statement after the return statement, or to be more exact - a statement imediatelly after a return statement (such as your println) can never be executed, and is therefore an error.
The println should be before the return statement.
public static int max3(int a, int b, int c) {
int max = a;
if (b > max) max = b;
if (c > max) max = c;
System.out.println(max);
return max;
}
I suggest You to change those if statements into one simple for loop with simple int[] vector. This solution is much more elegant and flexible. Additionally, You initialized and not used anywhere int maxValue = max3(a, b, c); in Your code.
public class Demo {
public static void main(String args[]) {
int[] numbers = new int[] {2, 3, 4};
System.out.println(maxValue(numbers));
}
public static int maxValue(int[] n) {
int max = n[0];
for (int i = 1; i < n.length; i++) {
if (n[i] > max) {
max = n[i];
}
}
return max;
}
}
But let's bow for a moment on the problem of methods implementation in Java.
At the begining of Your journey through the vastness of the Java realm You should get familiar with two types of methods: 1) void methods, and 2) return methods. The first ones are responsible for doing something without returning any value. We can for example use them for setting values of the fields of our application, initializing GUI, or other operations. The use of the void method can look like this:
/* method declaration */
void setValue(int value) {
someField = value;
}
/* method invocation */
setValue(5);
After invocation of setValue(5) the value of the someField object will be 5. However, you have to remember about type compatibility, so in this case someField can not be e.g of String type.
Second method type mentioned above, i.e return method is very useful, when you expect the method to give You an output, e.g in result of some operations conducted on the data You've given to Your method. But of course it's not necessary, to provide for the return method an input. Anyway, the use of return method can look like this:
/* method returns text You've given to it */
String getText(String text) {
return text;
}
/* method returns result of addition of three given int's */
int calculate(int a, int b, int c) {
return a + b + c;
}
/* method return a random number */
int createRandomNumber() {
Random random = new Random();
return random.nextInt();
}
You can easily see, that there is plenty of space for improvisation. Basicaly and in summary, void methods can work with given objects, for example can set values and conduct other operations, but thay don't return any STRAIGHT results You can work with. Return methods, from the other hand, provide You physical results, which You can use in further operations, or even in other methods, for example:
import java.util.Random;
public class Demo {
private static int someValue;
public static void main(String args[]) {
setValue(calculate(
createRandomNumber(),
createRandomNumber(),
createRandomNumber()));
System.out.println(someValue);
}
public static void setValue(int value) {
someValue = value;
}
public static int calculate(int a, int b, int c) {
return a + b + c;
}
public static int createRandomNumber() {
Random random = new Random();
return random.nextInt();
}
}
The problem is that the compiler detects that execution will never reach the System.out.println line, so it refuses to compile. The line return max; effectively ends the method, so nothing more will run after that.
You should move return max; to below the System.out.println line.
Swap your last 2 lines (return and System).
It should be like this, return max statement should be the last line in your method if you want to print something, because return statement goes back or invoke the line that called him,so your print statement is not reach.
public static int max3(int a, int b, int c) {
int max = a;
if (b > max) max = b;
if (c > max) max = c;
System.out.println(max);
return max;
}
You need to put
System.out.println(max);
before:
return max;
the reason is your return unconditionally ends the function and therefore the compiler won't reach the println causing a compile error.
You have a System.out.println() statement after the return. return ends the method and so the System.out.println() will never happen because the method will have ended. That's why you are getting errors. Put the System.out.println() before the return:
public static int max3(int a, int b, int c) {
int max = a;
if (b > max) max = b;
if (c > max) max = c;
System.out.println(max);
return max;
}
As already been said, after you return something, the method will end. So your output in the last line of the method will not be executed, so remove it.
You can print the returned value of the method when you write the following outside of the method:
System.out.println("highest value:" + max3(a,b,c));
So now, the 3 values are given to the method which can do something with them now. After it did the calculations, the method returns a value, which can now be printed to the console for example.
The issue with the code you provided is that you're trying to print to the console, after you use your return statement. This causes your program to never reach that line: System.out.println(max);

Categories