How to access methods in java from other methods? - java

I'm very new to programming. However, I've written a method called "succ" that's adds 1 to a given parameter. It looks like this:
int succ(int x) {
return x += 1;
}
Now I'm supposed to write another method that adds 2 numbers using my first method. This is what my attempt looks like:
int add(int x, int y) {
for(int i = 0; i < y; i++) {
succ(x);
}
return x;
}
Unfortunately it doesn't seem to work; it always returns the initial x. For example: If I type add(8,5) it just returns 8. Can someone help me? What am I doing wrong?
Thanks in advance.

You're not doing anything with the returned value. If you want to assign it back to x, do that:
x = succ(x);
Edit: Or, perhaps you mean to add to x, since you're doing it in a loop? It's not entirely clear what this code is meant to do, and I suspect more applicable variable/method names would help. But if you want to keep adding the result, you'd just do this:
x += succ(x);
Additionally, you don't need to modify x in your succ function. Doing so in this manner may lead to unexpected behavior in the future in other examples. Keep the operations as simple as possible. Just return the calculated value:
return x + 1;

You are missing the return value of the succ method, replace the succ(x); with x = succ(x);
int add(int x, int y) {
for(int i = 0; i < y; i++) {
x = succ(x);
}
return x;
}

You keep overwriting the x value with the return value from the function. You need to add to it in each iteration, not overwrite it.

Related

Programming Assignments-Recursion

Still learning and I cant seem to wrap my head on what seemed like an easy task.
The computeMethods method's is where im totaly stumped, however the reverse method i just keep getting back the same integer without it being reversed.
/****************************
* For Method Computemethods1 i must compute series
* b(x)=1/3+2/5+3/7..... +x/2x+1
* For method ComputeMethod2
* 1/2+2/3+......... x/(x+1)
*******************************/
public static int computeMethod1(int x){
if (x==0)
return 0;
if (x==1)
return 1;
return computeMethod1(x-1/3/(x-1))+computeMethod1(x-2/3/(x-2));
}
public static int computeMethod2(int x){
if (x==0)
return 0;
return computeMethod2((x-1)/(x-1)+1)+computeMethod2((x-2)/(x-2)+1);
}
/********************
* For method reverseMethod i must reverse a user given int
**********************/
public static int reverseMethod(int x){
int reversedNum=0;
if (x!=0)
return x;
reversedNum=reversedNum *10 +x%10;
return reversedNum+reverseMethod(x/10);
}
/******************
* For method sumDigits i must use recursion
* to sum up each individual number within the int
********************/
public static long sumDigits(long n){
if( n==0)
return 0;
if (n==1)
return 1;
else
return n+sumDigits(n-1);
}
}
For reverse method, you are using: if (x!=0) return x;
May be you need to use: if (x==0) return x. So the logic is, if the given argument is 0, then return 0, else return reversed number.
P.S.: As somebody mentioned in comentaries, please take care of types, so for the division you are better using float or double, and take care of operations precedence for correct result, so (x+1)/2 will be different from x+1/2.
For each of your methods, follow through your code for small x.
For example, computeMethod1 should return:
1/3 for x == 1, whereas at the moment it simply returns 1 (Note, the return type will need to be something other than int.).
1/3 + 2/5 for x == 2.
1/3 + 2/5 + 3/7 for x == 3.
For each x, notice how we can use the previous result i.e. computeMethod1(x - 1).
When you come across code that doesn't seem to do what you expect, make your code simpler and simpler until you can narrow down where the problem is, then hopefully it will be obvious what the problem is, or online documentation can tell you.

Object Creation and putting them into a 2D array

i am having difficulty with 2D arrays and inserting objects that take 3 parameters (int x, int y, int cost)
This is the beginning of a search algorithm and admittedly im off to a very poor start. I will paste the code below. I am receiving a compiling error when i try to run this code and i'm very sure it is simple but i cannot resolve it.
The Map2 class i intend to use to implement the main bulk of the algorithms, such as sorting etc.
import java.util.Arrays;
public class Map2 {
public static void main (String args[]){
Points[][] grid = new Points[4][4];
for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid.length; j++){
grid[i][j] = new Points(i,j,1);
}
}
System.out.print(Arrays.deepToString(grid));
}
}
This class is my object, it contains the movement cost from moving from one position to the next (the next step obviously would be to determine neighbors) and yes, this is part of trying to create a working A star algorithm.
public class Points {
int x;
int y;
int movement_cost;
public Points(int iX, int iY, int cost){
x = iX;
y = iY;
movement_cost = cost;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public int getMovementCost(){
return movement_cost;
}
public void setX(int x){
this.x = x;
}
public void setY(int y){
this.y = y;
}
public void setMovementCost(int cost){
this.movement_cost = cost;
}
public String toString(){
return ""+getX()+ ""+getY()+""+getMovementCost();
}
}
This is the console read out after compiling (3 address spaces in memory)
run:[[001, 011, 021, 031], [101, 111, 121, 131],
[201, 211, 221, 231], [301, 311, 321, 331]]
BUILD SUCCESSFUL (total time: 2 seconds)
My hope here is simple, each object in the array will contain a reference of its coordinates in memory and contain a cost of movement, which would later be used to compare in order to determine the next best position (i will later implement things such as goal, start)
my question is: whats wrong with the code the way it is ?
I want to thank, in advance whomever responds as your responce will always be appreciated
CURRENT REVISION OF MY QUESTION V0.1:
Wow well thanks for the quick responces, i have learned something new today ^^ that Arrays.deepToString(grid)); is an amasing tool i was not aware of, however i am still receiving a runtime error . Thank you once again for your replies and once again for any further responces :). The code above has been revised as recommended, but the runtime error still exists
There are several things that are wrong with your code:
Your nested loops assume that the array is square (you iterate both dimensions to grid.length),
You print the entire array after initializing each row, and
You print the array incorrectly (Java array do not print their content when passed to System.out.println)
The first item is OK if your matrix is indeed always square. The second item is easy to fix by moving the output outside of the second nested loop.
The third item is the hardest. It would be a good exercise to write a static method that takes your 2D array, and prints it out element-by-element with two nested loops. You can also use System.out.println(Arrays.deepToString(grid)); if you would rather use a system function.

Removing a chromosome from a population?

I am trying to write a method to remove a chromosome from my population. The method I have written is below. I am getting an out of bounds error when I run the code. Population is constructed with an ArrayList. The getChromosomeFitness method returns an int value score. Can someone spot my error?
void removeWorst()
{
int worst = population.get(0).getChromosomeFitness();
int temp = 0;
for(int i = 1; i < population.size(); i++)
{
if (population.get(i).getChromosomeFitness() < population.get(worst).getChromosomeFitness())
{
worst = population.get(i).getChromosomeFitness();
temp = i;
}
}
Chromosome x = population.get(temp);
population.remove(x);
}
You should probably change
if (population.get(i).getChromosomeFitness() < population.get(worst).getChromosomeFitness())
to
if (population.get(i).getChromosomeFitness() < worst)
You don't assure that in this line population has an element with the index 0:
int worst= population.get(0).getChromosomeFitness();
Try to add this to your method:
void removeWorst() {
if (population.isEmpty()) {
return;
}
...
There are several potential problems in your code:
int worst= population.get(0).getChromosomeFitness();
you need to make sure that population.isEmpty() is false
population.get(worst).getChromosomeFitness()
same thing, you need to make sure that (worst >= 0 && worst < population.size()).
The issue seems that you are getting the actual fitness rather than the object itself. The issue is with this line: int worst= population.get(0).getChromosomeFitness();. This is returning an integer value which is not related to the List's dimensions, as you said, it is the fitness of the chromozome, which could be well over the size of the list.
This should solve the problem:
void removeWorst()
{
int temp=0;
for(int i=1; i <population.size();i++)
{
if (population.get(i).getChromosomeFitness() < population.get(temp).getChromosomeFitness())
{
temp=i;
}
}
Chromosome x= population.get(temp);
population.remove(x);
}
That being said, a probably neater way of doing this would be to use a custom comparator to sort the list and then simply remove the last element.
Make sure population has something in it before trying to remove something from it?

Accessing instance variables from objects in a list

I'm working on a self-assigned project over break, and am running into one major sticking point. This is a basic line-recognition program in Java.
I have a Points class which creates the Point from the ordered pairs & sends it to the Line class for slope & intercept calculation. The results are sent back to the Points class which deposits the results into the ArrayList linelist. There are three parts to each Line object: the slope & intercept integers and the Point from which they were calculated from.
From a loop, how can I access the slope & intercept variables from each object in the linelist for comparison? Since I don't want to compare the points, just the slope & intercept, the equals() method is not what I need.
It sounds like you want something like this:
class Point {
final int x;
final int y;
Point(int x, int y) { this.x = x; this.y = y; }
}
class Line {
final int slope;
final int intercept;
Line(Point p1, Point p2) {
this.slope = ...;
this.intercept = ...;
}
}
class Points {
public void doIt(ArrayList<Point> points) {
ArrayList<Line> lines = new ArrayList<Line>();
for (int i = 0; i < points.size(); i++) {
for (int j = i + 1; j < points.size(); j++) {
lines.add(new Line(points.get(i), points.get(j));
}
}
for (int i = 0; i < lines.size(); i++) {
for (int j = i + 1; j < lines.size(); j++) {
Line line1 = lines.get(i);
Line line2 = lines.get(j);
if (line1.slope == line2.slope && line1.intercept == line2.intercept) {
// blah blah blah
}
}
}
}
}
(For the peanut gallery, yes there is scope for micro-optimization. But no, it isn't worth the effort unless you've profiled the program and found there to be a real and significant bottleneck.)
[For a more elegant and scalable solution, override the equals(Object) (and hashcode()) methods on Line class and replace the lines list with a TreeSet. This will reduce O(N**2) comparisons to O(NlogN) comparisons. But that's overkill for a basic programming exercise.]
From a loop, how can I access the slope & intercept variables from each object in the linelist for comparison?
Just add another loop over the same list inside the loop and do the comparison in there.
You could have your Line object implement the Comparable interface. You could then put the comparison logic within the Line class in the compareTo method. The logic there will test whether the slope and the intercept match, and if so return 0. Other results could return 1 or -1 to enforce ordering, if you want.
Obviously, you don't need to implement this interface to effect your desired results. However, as this is homework, doing so will allow you to play around with some features of the JDK, like using sorted Lists, etc. With a sorted list, for example, you could obviate the need for a nested loop, as you would only need to compare the object in question against one you just removed from the Iterator in the previous iteration to see if you need to add it to an existing linelist or start a new one.

How to detect an infinite loop in a recursive call?

I have a function that is recursively calling itself, and i want to detect and terminate if goes into an infinite loop, i.e - getting called for the same problem again. What is the easiest way to do that?
EDIT: This is the function, and it will get called recursively with different values of x and y. i want to terminate if in a recursive call, the value of the pair (x,y) is repeated.
int fromPos(int [] arr, int x, int y)
One way is to pass a depth variable from one call to the next, incrementing it each time your function calls itself. Check that depth doesn't grow larger than some particular threshold. Example:
int fromPos(int [] arr, int x, int y)
{
return fromPos(arr, x, y, 0);
}
int fromPos(int [] arr, int x, int y, int depth)
{
assert(depth < 10000);
// Do stuff
if (condition)
return fromPos(arr, x+1, y+1, depth + 1);
else
return 0;
}
If the function is purely functional, i.e. it has no state or side effects, then you could keep a Set of the arguments (edit: seeing your edit, you would keep a Set of pairs of (x,y) ) that it has been called with, and every time just check if the current argument is in the set. That way, you can detect a cycle if you run into it pretty quickly. But if the argument space is big and it takes a long time to get to a repeat, you may run out of your memory before you detect a cycle. In general, of course, you can't do it because this is the halting problem.
You will need to find a work-around, because as you've asked it, there is no general solution. See the Halting problem for more info.
An easy way would be to implement one of the following:
Pass the previous value and the new value to the recursive call and make your first step a check to see if they're the same - this is possibly your recursive case.
Pass a variable to indicate the number of times the function has been called, and arbitrarily limit the number of times it can be called.
You can only detect the most trivial ones using program analysis. The best you can do is to add guards in your particular circumstance and pass a depth level context. It is nearly impossible to detect the general case and differentiate legitimate use of recursive algorithms.
You can either use overloading for a consistent signature (this is the better method), or you can use a static variable:
int someFunc(int foo)
{
static recursionDepth = 0;
recursionDepth++;
if (recursionDepth > 10000)
{
recurisonDepth = 0;
return -1;
}
if (foo < 1000)
someFunc(foo + 3);
recursionDepth = 0;
return foo;
}
John Kugelman's answer with overloading is better beacuse it's thread safe, while static variables are not.
Billy3
Looks like you might be working on a 2D array. If you've got an extra bit to spare in the values of the array, you can use it as a flag. Check it, and terminate the recursion if the flag has been set. Then set it before continuing on.
If you don't have a bit to spare in the values, you can always make it an array of objects instead.
If you want to keep your method signature, you could keep a couple of sets to record old values of x and y.
static Set<Integer> xs;
static Set<Integer> ys;//Initialize this!
static int n=0;//keeps the count function calls.
int fromPos(int [] arr, int x, int y){
int newX= getX(x);
int newY= getY(y);
n++;
if ((!xs.add(Integer.valueOf(newX)) && !ys.add(Integer.valueOf(newY))){
assert(n<threshold); //threshold defined elsewhere.
fromPos(arr,newx,newy);
}
}
IMHO Only loops can go into an infinite loop.
If your method has too many level of recursion the JVM will throw a StackOverflowError. You can trap this error with a try/catch block and do whatever you plan to do when this condition occurs.
A recursive function terminates in case a condition is fulfilled.
Examples:
The result of a function is 0 or is 1
The maximum number of calls is reached
The result is lower/greater than the input value
In your case the condition is ([x0,y0] == [xN,yN]) OR ([x1,y1] == [xN,yN]) OR ([xN-1,yN-1] == [xN,yN])
0, 1, ...N are the indexes of the pairs
Thus you need a container(vector, list, map) to store all previous pairs and compare them to the current pair.
First use mvn findbugs:gui to open a gui which point to the line where this error is present.
I also faced the same problem and I solved it by adding a boolean variable in the loop verification.
Code before ->
for (local = 0; local < heightOfDiv; local = local + 200) { // Line under Error
tileInfo = appender.append(tileInfo).append(local).toString();
while (true) {
try {
tileInfo = appender.append(tileInfo).append(getTheTextOfTheElement(getTheXpathOfTile(incr))).toString();
incr++;
} catch (Exception e) {
incr = 1;
tileInfo = appender.append(tileInfo).append("/n").toString();
}
}
To Solve this problem, I just added a boolean variable and set it to false in the catch block. Check it down
for (local = 0; local < heightOfDiv; local = local + 200) {
tileInfo = appender.append(tileInfo).append(local).toString();
boolean terminationStatus = true;
while (terminationStatus) {
try {
tileInfo = appender.append(tileInfo).append(getTheTextOfTheElement(getTheXpathOfTile(incr))).toString();
incr++;
} catch (Exception e) {
incr = 1;
tileInfo = appender.append(tileInfo).append("/n").toString();
terminationStatus = false;
}
}
This is how i Solved this problem.
Hope this will help. :)

Categories