Hi, I am taking a course that is Java based over the summer and the prerequisite class which I took a year ago was in c++ and has recently been switched over to java. So now the class expects me to have a good background in java but there is my problem. I took a java course in high school... which was about 3 years ago and I have forgotten the very basics of writing a simple program in java.

My assignment is very simple, I would be able to do it in 5 mins back when I was in high school but I am extremely rusty and do not have a textbook to refer to at the moment.

The assignment is to create a function that will take a real number such as 3.0 from the user,
then take an exponent such as 3,
then give an answer which would be 27.0 and would do the math recursively.

Honestly I do not remember how to program such a simple task and would appreciate any help greatly

Recommended Answers

All 9 Replies

I dont remember how to take user input(a double) and assign it to a variable.

Hi, I am taking a course that is Java based over the summer and the prerequisite class which I took a year ago was in c++ and has recently been switched over to java. So now the class expects me to have a good background in java but there is my problem. I took a java course in high school... which was about 3 years ago and I have forgotten the very basics of writing a simple program in java.

My assignment is very simple, I would be able to do it in 5 mins back when I was in high school but I am extremely rusty and do not have a textbook to refer to at the moment.

The assignment is to create a function that will take a real number such as 3.0 from the user,
then take an exponent such as 3,
then give an answer which would be 27.0 and would do the math recursively.

Honestly I do not remember how to program such a simple task and would appreciate any help greatly

Let's break down the problem into steps...

->Accept user input
->Perform the desired operation / use recursion
->Prove that the operation has been done (by a display)

... these steps are in no particular order. This will help you get an idea of what to look up.

I can give you a few hints.

"Accept user input" - try using the following syntax--

import java.util.Scanner; // import the Scanner class file above the class declaration/definition

public class <your class name> ...
// Creates a scanner that reads information from the standard input stream in class System
Scanner keyboard = new Scanner(System.in);

// Display statement - does nothing special but allow user/you to be aware of something
System.out.println("Enter a word");

String a = keyboard.nextLine();

System.out.println("You entered: " + a);

You need to create the function that performs the operation. Keep in mind that in order to power something you need to understand how power works.

3 to the power of 3 is pretty easy to evaluate in our heads. We typically think of the number in terms of previous experiences of getting the answer through the calculator or by seeing the answer done. Rarely do we look at the mechanics of how the powering is done.

If we were to break down 3 to the power of 3, we could say that 3 to the power of 3 is just 3 times itself 3 times. For example--

(Warning, the below is not expressed in binary manipulation but in terms of regular calculator-based equations!)

3 ^ 3 = 3 * 3 * 3

and likewise

2 ^ 3 = 2 * 2 * 2;

This is easily iterable--

public double power(double value, int exp){
     double result = 1;
     
     for(int i = 0; i < exp; i++){
         result = value * result;
     }
     return result;
}

The above works for integer exponent values 0 and greater. If you need to do values below zero you'll have to do some research.

Even with this much done, there's still two more steps. We have to use recursion to solve the above and also we still have to display the value to the user.

Recursion implies that the function will call itself and break up the task into smaller tasks each time it is called. For example...

public static void recursivePrint(int times, String word){
		  if(times < 0){
			  recursivePrint(-times, word);
			  return;
		  }
		  else if(times == 0)
			 return;

		  System.out.println(word + " value times is " + times);
		  recursivePrint(times - 1, word);
	}

Recursive print calls itself two additional times after the method is first invoked. This is because of the line-- recursivePrint(times - 1, word); --which is perfectly legal in java.

The question is "why do this? Why not use iteration?" The answer is that some things are easier to express using recursion instead of iteration. Also some patterns/equations or events are easier to express through recursion where you only really need to know how the process is broken down in comparison to how to do the process.

For example, if I were to write the Fibonacci sequence using iteration, I'd need to know what the starting point is before progressing to the finish point.

Fibonacci sequences are 0 at 0 and 1 at 1. At 2 the result is 1, at position 3 the result is 3, at pos 4 the result is 5... so on and so forth.

I'd then have to progress forward with the sequence by constantly evaluating the last two numbers, add them together then store the new number in some data type and do another comparison depending on what position the user wants to stop at in the Fib sequence.

In recursion you don't have to do that! You only need to know 2 things--

The pattern for the numbers and, the stopping case(s) [the sentinels].

Using iteration...

import java.util.Scanner;

public class Number_Manip{

	public static void main(String[] args){
		System.out.println(Number_Manip.fibonacci(3));
	}

	public static int fibonacci(int num){
		int first = 0, second = 1, result = 0; // rather annoying

		for(int i = 0; i < num + 1; i++){ // even more annoying
			result = first + second;
			second = first;
			first = result;
		}
		return result;
	}
}

And then using recursion--

import java.util.Scanner;

public class Number_Manip{

	public static void main(String[] args) throws Exception{
		System.out.println(Number_Manip.fibonacci(5));
	}

	public static int fibonacci(int num) throws Exception{
		if(num < 0)
			throw new Exception();
		if(num == 0)
			return 1;
		else if(num == 1)
			return 1;
		else return fibonacci(num - 2) + fibonacci(num - 1); // much cleaner
	}
}

The above example breaks down the process, but not that the functions have to keep calling themselves until a sentinel is met in which they can stop.

Also note that the initial call of the function must wait, that is it must evaluate the two functions at the last line of the method before it can return anything.

Actually, each function, since they're nearly the same as the initial-invoking function, must wait until the function they call has reached an evaluation.

The sentinels num == 0 and num == 1 force the method call of fibonacci(1) to return 1, and likewise fibonacci(0) also returns 1. This example is slightly different from the for loop example since the first starting numbers were 0 and 1 and now we use 1 and 1. Really it's a preference of what you want to be the "first number" in the sequence - count 0 or not.

You may not see much of a different, but consider this - if you needed two functions to cooperate with each other in terms of breaking down a process, how would you do it using pure iteration? The answer is that it would be incredibly difficult (but not impossible) with a lot of complexity to the code. Recursivity allows one to break down a process into smaller processes - basically you're delegating small jobs to each function call instead of trying to do everything in one step like you would using iteration.

Recursivity doesn't just apply to functions, but for now experiment with recursion to see if you can understand it. Remember that when the function calls itself and when the sentinel(s) is met are probably the two most important things to note when using recursion.

Also note that anything done recursively can be done using a loop. I'm pretty sure the reverse is true, so try making the far-above function of the for loop into a recursive method that returns the power of a number with a given exponent.

commented: Good post. +9
commented: Well written! +5

I don't get why it has to be done recursively. I am pretty sure just a normal, exponential way is much easy for exponents.

I don't get why it has to be done recursively. I am pretty sure just a normal, exponential way is much easy for exponents.

It's part of the requirements--

My assignment is very simple, I would be able to do it in 5 mins back when I was in high school but I am extremely rusty and do not have a textbook to refer to at the moment.

The assignment is to create a function that will take a real number such as 3.0 from the user,
then take an exponent such as 3,
then give an answer which would be 27.0 and would do the math recursively.

thinking about how i would do this recursively, a number to a power, is the same as the number times the number to the power-1, until the power is zero, if it is zero the exponentiation is always 1, no matter the number, granted this approach only does work if the power is an integer:

public static double myPow(double x, int y) throws IllegalArgumentException{
    if(y<0){
        throw new IllegalArgumentException();//i don't normally throw exceptions so i don't know if this is right
    }
    if(y==0){
         return 1;
    }
    return x * myPow(x,y-1);
}

thinking about how i would do this recursively, a number to a power, is the same as the number times the number to the power-1, until the power is zero, if it is zero the exponentiation is always 1, no matter the number, granted this approach only does work if the power is an integer:

public static double myPow(double x, int y) throws IllegalArgumentException{
    if(y<0){
        throw new IllegalArgumentException();//i don't normally throw exceptions so i don't know if this is right
    }
    if(y==0){
         return 1;
    }
    return x * myPow(x,y-1);
}

I would've posted the answer myself but I wanted to see if he could use the logic to get it on his own lol.

oh well =P

I dont remember how to take user input(a double) and assign it to a variable.

import java.util.Scanner;

public class Test_Class_9{
     public static void main(String[] args){
           System.out.println("Enter a double");
           Scanner kb = new Scanner(System.in);
           double myDouble = kb.nextDouble();
           System.out.println("You entered: " + myDouble);
     }
}

funny you should mention that i thought about posting the info without the code, but i figured it would end up in the thread anyway in one form or another sorry :(

can u run a simple Hello World output??

if not.. u didn't installed properly you JDK or Java Development Kit.. and you are not implement the Environment variable path..

otherwise what is your editor?

commented: Did you even read the original question? This is completely unrelated. -2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.