Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 11-18-2010, 11:20 AM   PM User | #1
jstern
New to the CF scene

 
Join Date: Oct 2010
Posts: 7
Thanks: 4
Thanked 0 Times in 0 Posts
jstern is an unknown quantity at this point
Help with a Java problem

Here's the question in the book.

"Write a method integerPower(base, exponent) that returns the value of base ^ exponent.

For example integerPower( 3, 4 ) calculates 3^4 (or 3 * 3 * 3 * 3). Assume that exponent is a positive, nonzero integer and that base is an integer. Method integerPower should use a for or while statement to control the calculation. Do not use any math library methods. Incorporate this method into an application that reads integer values for base and exponent and performs the calculation with the integerPower method.

Here's what I have so far.

Code:
import java.util.Scanner;

public class Exponential{
	
		public static void main( String args[] ){
		int base, power;
		int counter;
		int cal;
		int xyp;
		
		Scanner googie = new Scanner(System.in);
		System.out.print("Enter base: ");
		base = googie.nextInt();
		
		System.out.print("Enter exponent: ");
		power = googie.nextInt();
		cal = base * base;
		counter = 1;
		while (counter < power){
		counter++;
		xyp = cal * power;
						
		}
	
		System.out.println(xyp);		
	}
}
At one point I got really angry, so frustrating, because I cannot figure out how to make the last part work. xyp needs to be initialize, and I'm so annoyed because I don't understand why it doesn't run the way it supposed to.

Last edited by jstern; 11-18-2010 at 11:49 AM..
jstern is offline   Reply With Quote
Old 11-19-2010, 05:53 AM   PM User | #2
pigpen
Regular Coder

 
Join Date: Dec 2007
Posts: 137
Thanks: 1
Thanked 21 Times in 21 Posts
pigpen is on a distinguished road
Try initializing your xyp integer.

Instead of
Code:
int xyp;
Initialize it with a value when you are declaring it.
Code:
int xyp = 0;
That should make your code work.

As far as the answer to the exercise question, I imagine you are still working that out. Is that from the Deitel Java book? It's a good book. The way I solved it was a bit differently, but there are multiple solutions to the problem.
pigpen is offline   Reply With Quote
Users who have thanked pigpen for this post:
jstern (11-22-2010)
Old 11-22-2010, 09:15 AM   PM User | #3
jstern
New to the CF scene

 
Join Date: Oct 2010
Posts: 7
Thanks: 4
Thanked 0 Times in 0 Posts
jstern is an unknown quantity at this point
Quote:
Originally Posted by pigpen View Post
Try initializing your xyp integer.

Instead of
Code:
int xyp;
Initialize it with a value when you are declaring it.
Code:
int xyp = 0;
That should make your code work.

As far as the answer to the exercise question, I imagine you are still working that out. Is that from the Deitel Java book? It's a good book. The way I solved it was a bit differently, but there are multiple solutions to the problem.
What frustrated me about this problem, being new to programming was not understanding why it has to be initialized in the first place. Why it couldn't just work the way I imagine it should work. Then again I'm new, so I'm sure there's an answer. At one point I got this concentrated anger for 5 seconds, and I imagine many people have burst a vein during such a state, so I'm glad I'm ok. Thanks for the help, but I realized that my calculation in the 1st program was wrong. I was sitting on the couch, grabbed a piece of paper, and figured it out pretty quickly. Things are much easier when you try to figure out the formula on a piece of paper, before hand, rather than trying to figure it out while writing the program. Oh, and the book is Deitel Java How To Program, 8th edition.

Here's the final code.

Code:
import java.util.Scanner;
public class Exponential {
	
	public static void main( String args[] ){
	int base, power;
	int counter;
	int hold;
	
	Scanner googie = new Scanner(System.in);
	System.out.print("Enter base: ");
	base = googie.nextInt();
	
	System.out.print("Enter exponent: ");
	power = googie.nextInt();
	hold = base;
	
	counter = 1;
	while (counter < power){
	counter++;
	base = base * hold;
	}

	System.out.println(base);		

	}
}

Last edited by jstern; 11-22-2010 at 09:22 AM..
jstern is offline   Reply With Quote
Old 11-22-2010, 09:50 PM   PM User | #4
pigpen
Regular Coder

 
Join Date: Dec 2007
Posts: 137
Thanks: 1
Thanked 21 Times in 21 Posts
pigpen is on a distinguished road
Nice job and thanks for following up on your thread and posting your solution. That should help others who may be reading this thread.

And yeah, as far as working out problems, I often break out a sheet of paper to do solve things. Also writing pseudo-code, not real code, to help formulate my logic, helps a lot, too.

One thing about your solution, I think you may want to put your code into a function, as the exercise wants you to be able to call your code via the "integerPower( 3, 4 )" method. Not a big deal, but if you aren't familiar with functions (or methods if they are in class), then it's a good idea to do so.

Like:

Code:
public static int integerPower(int base, int power)
 {

    int base, power;
    int counter;
    int hold;
    
    // rest of your code, and don't forget to "return" your int value
}
In regards to the int data type, in Java, int is a primitive data type. It is not an object, so therefore it can't be null. The same goes for char, short, long, and other primitive data types in Java. Some other languages, such as C# and Python, do treat int as objects so if you were programming in a different language, this is perhaps a source of frustration for beginners when switching to Java.

If you want to treat int as an object, then you have to use the Integer object in Java, which is totally fine. In general, int is faster than Integer, but if not doing a high amount of calculations, then the difference would be negligible, I would think.

Here's a guide on the difference between int and Integer.
http://mindprod.com/jgloss/intvsinteger.html

And more about primitive datatypes.
http://download.oracle.com/javase/tu...datatypes.html
http://java.sun.com/docs/books/jls/s...alues.doc.html
pigpen is offline   Reply With Quote
Old 11-28-2010, 09:40 AM   PM User | #5
jstern
New to the CF scene

 
Join Date: Oct 2010
Posts: 7
Thanks: 4
Thanked 0 Times in 0 Posts
jstern is an unknown quantity at this point
Quote:
Originally Posted by pigpen View Post
Nice job and thanks for following up on your thread and posting your solution. That should help others who may be reading this thread.

And yeah, as far as working out problems, I often break out a sheet of paper to do solve things. Also writing pseudo-code, not real code, to help formulate my logic, helps a lot, too.

One thing about your solution, I think you may want to put your code into a function, as the exercise wants you to be able to call your code via the "integerPower( 3, 4 )" method. Not a big deal, but if you aren't familiar with functions (or methods if they are in class), then it's a good idea to do so.

Like:

Code:
public static int integerPower(int base, int power)
 {

    int base, power;
    int counter;
    int hold;
    
    // rest of your code, and don't forget to "return" your int value
}
In regards to the int data type, in Java, int is a primitive data type. It is not an object, so therefore it can't be null. The same goes for char, short, long, and other primitive data types in Java. Some other languages, such as C# and Python, do treat int as objects so if you were programming in a different language, this is perhaps a source of frustration for beginners when switching to Java.

If you want to treat int as an object, then you have to use the Integer object in Java, which is totally fine. In general, int is faster than Integer, but if not doing a high amount of calculations, then the difference would be negligible, I would think.

Here's a guide on the difference between int and Integer.
http://mindprod.com/jgloss/intvsinteger.html

And more about primitive datatypes.
http://download.oracle.com/javase/tu...datatypes.html
http://java.sun.com/docs/books/jls/s...alues.doc.html
I already handed in, so hopefully it will come back ok. Funny, I read this a couple of days ago, and being new I was having a little bit of trouble following some of what you were talking about. Like the int, integer object, but after a few days of continuing to study, I understand it much better. Which makes me feel hopeful, since these things at the beginning feels so complicated, but I guess it sinks in eventually, so I would hope I would eventually become a sort of expert.

Ok, right now I was going to say that the only thing I'm having trouble following was what you meant bye "integerPower( 3, 4 )", but as I went back to copy and paste it, I now think I understand what you meant. Not completely, but I think I get where you're going. Actually I think I do now. I guess I mis read the problem. Thanks.
jstern is offline   Reply With Quote
Old 11-29-2010, 03:00 AM   PM User | #6
pigpen
Regular Coder

 
Join Date: Dec 2007
Posts: 137
Thanks: 1
Thanked 21 Times in 21 Posts
pigpen is on a distinguished road
I understand. Learning programming for the first time is overwhelming as you both have to learn the basics of programming, like creating variables, making loops, etc and at the same time learning the syntax, the words, of the language.

One of the earliest stumbling blocks is understanding how to make functions, but it's a fundamental concept in every programming language. Note in Java, functions are called "methods" (because they are part of classes, but don't worry about that for now).

Normally you can write something like this to add two numbers:

Code:
public class Main {


    public static void main(String[] args) {

        // add two numbers
        int n1 = 4;
        int n2 = 5;
        int result = n1 + n2;
        System.out.println(result); // displays "9"
    }
}
But what if you want to want to reuse that code? Like adding two different pairs of numbers. Easy. Put that code into a method.
Code:
    public static int addTwoNumbers(int n1, int n2) {
        int result = n1 + n2;
        return result;
    }
I've made a method, that takes two parameters, in this case, two integers, n1 and n2. It will take those two integers, add them and return the sum.

So now, if I want to use this method, I can do so easily and do it multiple times. In this example, from inside the Main method, I am calling addTwoNumbers method and displaying the results.

Code:
    public static void main(String[] args) {
       
        int myNumber = addTwoNumbers(3, 4);
        System.out.println(myNumber); // displays "7"

        int myNumber2 = addTwoNumbers(5, 1);
        System.out.println(myNumber2); // displays "6"

    }
Methods (aka "functions"), let you reuse code. Make your code more modular. And yes, main is a method, too, but don't worry about that for now. Just know that you can break up your code inside the main method, into separate discreet methods outside of the main method, like I did with the "addTwoNumbers()" method. It will make your code a lot easier to debug and to read. Later when you learning more about OOP, object-oriented programming, you'll learn more about methods and making classes (which we haven't talked about yet).

Here's the whole code for the example I gave above, if you simply wanted to copy and paste:

Code:
public class Main {

    public static void main(String[] args) {

        int myNumber = addTwoNumbers(3, 4);
        System.out.println(myNumber); // displays "7"

        int myNumber2 = addTwoNumbers(5, 1);
        System.out.println(myNumber2); // displays "6"
    }
    public static int addTwoNumbers(int n1, int n2) {
        int result = n1 + n2;
        return result;
    }
}
I hope that helps. Don't worry if it doesn't all gel yet. It'll take some time.
pigpen is offline   Reply With Quote
Old 03-21-2011, 03:54 PM   PM User | #7
digbysellers
New to the CF scene

 
Join Date: Mar 2011
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
digbysellers is an unknown quantity at this point
Hi, I was looking for a solution to the same problem, but without context to the book mentioned in this thread.

If I am not mistaken with this code (which is certainly a possiblity), a base to the power of zero returned the same as a base to the power of one.

I used an if-then-else statement to amend this:

Code:
import java.util.Scanner;

public class PowerDoWhile {
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		int base = 0;
		int power = 0;
		boolean flag = true;
		
		do {int hold = 0;
			int counter = 1;
			System.out.println("input your base: ");
			base = input.nextInt();
		
			System.out.println("input your power of: ");
			power = input.nextInt();
			hold = base;
			
			if(power>0){while(counter<power){counter++; base=base*hold;}
			}else{base=1;}
		
			System.out.println(base);
			
		} while (flag);
				
	}
}
digbysellers is offline   Reply With Quote
Old 04-02-2011, 09:59 PM   PM User | #8
mimis40
New Coder

 
Join Date: Mar 2011
Location: Utah
Posts: 30
Thanks: 0
Thanked 6 Times in 6 Posts
mimis40 is on a distinguished road
try:
Code:
double base = 0, power =0;
        base = in.nextDouble();
        power = in.nextDouble();
        double num = Math.pow(base, power);
        System.out.println(num);
mimis40 is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 03:54 PM.


Advertisement
Log in to turn off these ads.