Returning two values from a method - java

I am trying to implement a method that takes two boolean parameters, uses these inputs and outputs two results. I tried to create another class that holds the two results but I got confused in the way of returning the two results. This is my attempt so far:
public class Results
{
private boolean Sum;
private boolean Carry;
public Results (boolean Sum, boolean Carry)
{
this.Sum = Sum;
this.Carry = Carry;
}
public boolean getSum()
{
return Sum;
}
public void setSum(boolean sum)
{
this.Sum = sum;
}
public boolean getCarry()
{
return Carry;
}
public void setCarry(boolean carry)
{
this.Carry = carry;
}
}
This is my function:
public Results(boolean inp1, boolean inp2)
{
boolean sum = x1.OperatorGate(inp1, inp2);
boolean carry = a1.OperatorGate(inp1, inp2);
return new Results(sum, carry);
}
I know that there are a lot of examples on this site of how to achieve this, but every example I found, didn't use any parameters in the function.

You are on the right track. Creating a class to hold your set of two responses is correct.
Your function (method in java) is a bit off though. Try this:
public Results getResults(boolean inp1, boolean inp2)
{
boolean sum = x1.OperatorGate(inp1, inp2);
boolean carry = a1.OperatorGate(inp1, inp2);
return new Results(sum, carry);
}

You got a little confused between the purpose of a Constructor and the difference between a Constructor and a regular-old method that creates an instance of a class and returns it.
One key difference is that a constructor can only be specified inside the definition of its own class - you already did this, which is good.
Another key difference is that when you tried to declare a 'normal' method, you meant to say that the method should return an object of type Results, but instead you named the method Results. Only a constructor has a name identical to that of a class it is creating. So your 'return' statement does belong there, you just need to change the first line of your method declaration.

Related

Java method taking 0 arguments and returning a double using if else statements with strings

I am trying to write a method which does not take any arguments and then returns a double variable. It is a postcode identifier so when a cost code is entered certain post codes need to return a double.
In my example below i need post codes that start with either "GH6 TXX" or "NC4 LXX". (X stands for any random character or digit) to return 50.0.
If any other postcode is entered then return 100.0.
However i am not getting any results back and just finding errors. I'm sure i have gone massive wrong somewhere as im not great with If Else statements within methods. Any help or knowledge on this would be great!
public class multiPostcodeRange {
//Declaring Variables
String pcode;
public multiPostcodeRange()
{
pcode = "XXX XXX";
}
public void multiPostcodeRange()
{
if (pcode("GH6 TXX", "NC4 LXX")) {
return 100.0; }
else {
return 50.0;}
} }
public class MultiPostcodeRange {
private String pcode;
public MultiPostcodeRange() {
pcode = "XXX XXX";
}
public double multiPostcodeRange() {
if (pcode.equals("GH6 TXX") || pcode.equals("NC4 LXX")) {
return 100.0;
}
else {
return 50.0;
}
}
}
To return double from a function you need to define a return type for the function.
public double multiPostcodeRange
You created a class with his methods (which btw you shouldn't name as the class, but give them unique names).
Then you have to create a new instance object of that class and call the method on a main function.
For example, at the end of your code:
`public static void main(String args[]){
multiPostcodeRange Obj = new
multiPostcodeRange();
Obj.meth1();
Obj.meth2();}`
NB remember to give those methods unique names!
Also change 2nd method body and type as AndyMan's answer

Java code does not return anything even though it is supposed to

I'm just new to Java OOP, and I hardly understand about the class and stuff. I tried to write some code to understand but I didn't succeed. Here is my code, I expected it to return the number of eggs but I don't know why it returns nothing.
class EggCounter {
private int egg;
{
egg = 0;
}
public void eggAdd()
{
egg = egg + 1;
}
public void eggBreak()
{
egg = egg - 1;
}
public void eggAddDozen()
{
egg = egg + 12;
}
public int getEgg()
{
return egg;
}
}
public class EggTest
{
public static void main(String[]args)
{
EggCounter egg = new EggCounter();
egg.eggAdd();
egg.eggAddDozen();
egg.eggBreak();
egg.getEgg();
}
}
It does return 12. Replace the egg.getEgg(); line in your main method with System.out.println(egg.getEgg()); and you will notice it prints 12.
It is returning, it's just that you do nothing with the return value of getEgg. What you need to do is store it into the variable or do something with it. return <value> only returns the given value to the callee, you must store it to use it. Example:
int eggCount = egg.getEgg();
System.out.println(eggCount);
Here, the assignment of eggCount calls egg.getEgg(). The call resolves when the number of eggs is returned, which assigns the return value to eggCount. Finally, it will print out eggCount. If you need the result of egg.getEgg() later, you can simply just output the following:
System.out.println(egg.getEgg());
How this works is the method egg.getEgg() is called. The return value is then resolved, which is passed into the print statement. This gets rid of storing it into a variable you can use later.

Turning a for loop to recursive method for prime numbers

I need to convert the code below to a recursive method without using global variables and using only one parameter.I Searched the topics already there is no code with one parameter and doesnt use the global variables.
public boolean isPrime(int x){
for(int i=2;i<x;i++)
if(x%i==0) return false ;
return true;
}
Ok, as for your requirements:
Without using global variables.
Using only one parameter.
And, based on:
it come up in one of my university exams
There a couple of aspects to take into account:
If you pass an instance of a Class you are passing only one variable, and as Classes can have multiple variables inside...
They do not state if you can call multiple functions inside, so, again, this is a hint or clue, of what can you do. So, two solutions for you:
Solution 1 (Using Classes)
class RecursVar {
int x;
int i = 2;
RecursVar(int x) {
this.x = x;
}
}
public boolean isPrimeRecurs(int x){
return isPrime(new RecursVar(x));
}
boolean isPrime(RecursVar recursVar) {
if(recursVar.x % recursVar.i == 0)
return false;
if (++recursVar.i >= recursVar.x)
return true;
return isPrime(recursVar);
}
Solution 2 (Cleaner approach without using Classes but based in that the function that can have only one parameter is isPrime )
boolean isPrime(int x) {
return checkForPrime(x, 2);
}
boolean checkForPrime(int x, int i) {
if (i >= x) return true;
if (x % i == 0) return false;
return checkForPrime(x, ++i);
}
Again, this solutions are based on that many exams require a little creativity and maybe that was the aim of this case.
This cases should not be used in production, they are slow and
prune to make honor to this site (StackOverFlow) with a sweet
java.lang.StackOverflowError
It's an interesting problem.
If you can use java 8, you can solve the problem as followed (note that the case isPrime(2) needs to be checked with an additional if condition):
package test;
import java.util.function.Function;
public class Test {
public static void main(String[] args) {
System.out.println(isPrime(13));
}
private static Function<Integer, Boolean> fun;
public static boolean isPrime(int x) {
fun = i -> {
if (i > 2) return (x%i != 0) && fun.apply(i-1);
else return (x%i != 0);
};
return fun.apply(x-1);
}
}
One of my schoolmates' topic accually recieve a solution here it is if you interested its quite brilliant
https://stackoverflow.com/questions/35660562/finding-prime-numbers-recursively-with-using-only-one-parameter?noredirect=1#comment59001671_35660562

Reference a method within a method in java?

Ok, so I am going to see if this makes sense. In the second method below (int numAdd) I want to be used for the private method (int searchingNum). I don't really understand how private methods work, but whatever number the user enters for the (int numAdd) I want to be duplicated for the parameters in the first method. How is this possible?
//See if user input returns -1 to test whether or not number exists in the array
private int indexOf(int searchingNum)
{
}
//Add number in the array
public boolean addNumber(int numAdd)
{
if (list.contains(numAdd))
{
return false;
}
else
{
list.add(numAdd);
count++;
return true;
}
}
that's it? indexOf(numAdd);
public boolean addNumber(int numAdd)
{
// somewhere, in the middle of nowhere
indexOf(numAdd);
// more of code
}
You can call method of same class directly. No need to do anything. Like this :
public boolean addNumber(int numAdd)
{
int abc = indexOf(numAdd);
//Whatever you want to do...
}

How can I use the parent class to get a parameter from child class?

I have this child class AggressiveAlien and here is one method inside it
public boolean attack()
{
boolean attack;
if (currentLocation == this.AggresiveAlien.getCurrentLocation)
{
energyCanister = (int) ( (1/2) * alien2.energyCanister + energyCanister);
lifePoints = (int) (lifePoints - (1/2)*alien2.energyCanister);
attack = true;
}
return attack;
}
I would like the returned value to be used in the parent class Alien
public void gotAttacked()
{
if (AggresiveAlien.attack())
energyCanister = energyCanister/2;
}
But it seems to be giving errors on the AggresiveAlien.attack() part. Is there any way for me to use this returned value from AggresiveAlien to be used in Alien?
Help would be very much appreciated. Thanks!
Here is another part of the child class
public class AggressiveAlien extends Alien
{
public AggressiveAlien(XYCoordination currentLocation, int energyCanister)
{
super(currentLocation, energyCanister);
}
public int collectCanister(NormalPlanet canister)
{
super.collectCanister();
n=1;
}
I think you might be having two problems... First you need to cast the base type to the child type, such as
((AggressiveAlien)this).attack()
Also, 1/2 may actually be 0! 1 and 2 are interpreted as integers which means the value of any division is floored! so 1/2 = (int) 0.5 = 0
check your types! You better use 0.5 or use /2.0 to force the value to compute as a float or double (depending on the platform).
Hope this helped!
It looks as though you're trying to use AggresiveAlien statically. Instead you probably want to do:
if ((AggresiveAlien)this.attack()) energyCanister = energyCanister/2;
But I can't be sure given the limited amount of information.
you say, you have a parent and child class, which means you are using inheritance here. you can easily accomplish your task by using virtual function and then overriding in the child class.
in your Alien class create a function called attack() and override in the child class AggresiveAlien.
like following:
Alien class:
public boolean attack()
{
return false;
}
AggresiveAlien class:
public boolean attack()
{
return true;
}
and your gotAttacked function
public void gotAttacked()
{
if (this.attack())
energyCanister = energyCanister/2;
}

Categories

Resources