Reference a method within a method in java? - 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...
}

Related

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.

How to use boolean statements and return

I am trying to create a piece of code which will;
return true if given an int n, which is with in 10 of 100 or 200.
import java.util.Scanner;
class nearHundred{
public boolean nearHundred(int n){
Scanner input = new Scanner(System.in);
n = input.nextInt();
if(10>=Math.abs(100-n) || 10>=Math.abs(200-n)){
return true;
}
return false;
}
}
Where have I gone wrong?
From comments it looks like your main method is misplaced, wherever it is I hope it exists only once in a project. Call your class from that main() method, for example -
new nearHundred().nearHundred(100); // a call from main method
Now coming to your code there are several things to correct here. Your method should not take care about Scanner, its job is to take input and check for the logic.
For example;
public class Utils {
public static boolean isNearToHundered(int num) {
return Math.abs(num-100)<=10 || Math.abs(num-200)<=10;
}
}
Give the responsibility to main method for parsing the input, this is how it should work.
Now since I made method static, you can call like
Utils.isNearToHundred(105); // TRUE
Here is how the method should look:
public void mainMethod() {
Scanner input=new Scanner(System.in);
int val=input.nextInt();
boolean nearHundredBoolean=nearHundred(val);
//do something with nearHundredBoolean....
//Same logic, but passes the input to the method nearHundred
public boolean nearHundred(int n) {
if(Math.abs(100-n)<=10 || Math.abs(200-n)<=10)
return true;
else return false;
}
You should pass the value of the scanner input into this method's parameter requirement, instead of not using the parameter n in your current method. If there is a problem, it may be due to the 'input.nextInt()' method that overwrites the value of the parameter n.

Can I use value of a local variable defined in a method, in other method in Java?

The method is not returning the value of the local variable.
Can I use the value of local variable index from the following method
public boolean contains(Object input) {
int index = 0;
while(myAsetIterator.hasNext()) {
index++;
if(input.equals(myAsetIterator.next())) {
return true;
}
}
return false;
}
in this method as the index of the array of the object that I want to remove.
public boolean remove(Object o) {
int count = 0;
if(o == null) {
return false;
}
if(contains(o)) {
genArray[index] == null;
}
if (count > 0) {
System.out.println(count+" same elements were present in Aset. "
+ "Removed all those "+count+" elements from Aset.");
return true;
}
return false;
}
I know the scope of a local variable is limited to the method it's declared in. But there might be a way that I might not now yet to make this happen without using a field/instance variable.
No. The whole point of it being local to a method is that it only exists within that method. The options are:
Use an instance field, i.e. make it part of the state of the object. That's unlikely to be appropriate.
Use a static field, i.e. make it part of the static of the type. That's almost certainly inappropriate.
Change the existing method to return the information you want.
Create a new method to return the information you want.
Duplicate the existing code within remove so that you can get the index. That would be sad :(
As an example of the last two, you could write:
public int indexOf(Object input) {
int index = 0;
while(myAsetIterator.hasNext()) {
index++;
if (input.equals(myAsetIterator.next())) {
return index;
}
}
return -1;
}
public boolean contains(Object input) {
return indexOf(input) == -1;
}
... then in your remove method, you'd use indexOf instead of contains.

Returning two values from a method

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.

How to return a specific element of an array?

I want to return odd numbers of an array yet Eclipse doesn't seem to accept my return array[i]; code. I think it requires returning a whole array since I set an array as a parameter to my method.
As I said before, I need to pass an array and get a specific element of that array in return. Even if I make that array static, how do I return a single element?
Edit : Alright then, here it is:
public class newClass{
public static void main(String[] args)
{
int [] newArray= new int [4];
int [] array = {4,5,6,7};
newArray[0] = array[0]+array[1]+array[2]+array[3];
newArray[1] = array[0]*array[1]*array[2]*array[3];
newArray[2] = findOut(array);
}
public static int findOut (int [] array3)
{
int e1=0;
int e2=0;
for (int i=0; i<array3.length; i++)
{
if (array3[i]%2==0)
{
e1+=array3[i];
array3[i]=e1
return array3[i];
}
else
{
e2+=array3[i];
array3[i]=e2;
return array3[i];
}
}
}
}
I know there are probably more than a few mistakes here but I'm working on it and I'm not only returning odd numbers, I also add them together.
You code should look like this:
public int getElement(int[] arrayOfInts, int index) {
return arrayOfInts[index];
}
Main points here are method return type, it should match with array elements type and if you are working from main() - this method must be static also.
I want to return odd numbers of an array
If i read that correctly, you want something like this?
List<Integer> getOddNumbers(int[] integers) {
List<Integer> oddNumbers = new ArrayList<Integer>();
for (int i : integers)
if (i % 2 != 0)
oddNumbers.add(i);
return oddNumbers;
}
Make sure return type of you method is same what you want to return.
Eg:
`
public int get(int[] r)
{
return r[0];
}
`
Note : return type is int, not int[], so it is able to return int.
In general, prototype can be
public Type get(Type[] array, int index)
{
return array[index];
}
(Edited.) There are two reasons why it doesn't compile: You're missing a semi-colon at the end of this statement:
array3[i]=e1
Also the findOut method doesn't return any value if the array length is 0. Adding a return 0; at the end of the method will make it compile. I've no idea if that will make it do what you want though, as I've no idea what you want it to do.

Categories

Resources