displaying list of powers program - java

I really need help with creating a program that displays a list of powers
here is the input and the output:
Input to the application is to include numbers to represent the following:
base
exponent (between 1 and 10)
Output is to list the number that you entered as a base and find the powers for that base from 1 up to the ending exponent number that is input.
I'm almost done the program, but the problem is that the program only calculate the base to the power without listing a list of powers.
I know i'm missing something in my loop
here is my code
double baseIn, exponentIn;
baseIn = Integer.parseInt(txtBase.getText());
exponentIn = Integer.parseInt(txtExponent.getText());
// power = (int) Math.pow(baseIn, exponentIn);
for (int i = 1; i <= exponentIn; i++) {
txtArea.setText(Integer.toString((int) baseIn)+ "to the power of " + i + "=" + Math.pow(baseIn, i) );
}

The following is a recursive solution. Explained in steps. Assuming you want 2^4
1) we call power(2,4)
2) power(2,4) calls power(2,3)
3) power(2,3) calls power(2,2)
4) power(2,2) calls power(2,1)
5) power(2,1) calls power(2,0)
6) power(2,0) returns 1
7) power(2,1) returns (2 * 1) or 2
8) power(2,2) returns (2 * 2) or 4
9) power(2,3) returns (2 * 4) or 8
10) power(2,4) returns (2 * 8) or 16
public static int power(int base, int power){
if (power == 0)
return 1;
else
return base * power(base, power-1);
}

One problem could be that you overwrite the test string of the output text area in each iteration of the loop, so that at the end -- probably without seeing anything else, because your code happens so fast that no repaint occured -- you, only see the last output.
Use a stringbuilder, append the string of each iteration, and only display the combined result after the loop.
Or use the already existing functionality
textArea.append(text + newline);
see for instance Java Swing: Approach for dynamically appending text in text area, have scrollbar update

Related

Printing random even value between two values using inheritance

I am trying to print a list of random even numbers (5 times) using a bounds. Example being from 0 to 30 (including both those numbers). This is what I have so far (this is in its own class):
public int nextEven(int h){
int n = rand.nextEven(h) % 2;
return n;
}
This is where it would print from my main method:
System.out.println("Random Even:");
for (int i = 0; i < 5; i++){
System.out.println(rand.nextEven(30));
}
When I run the program it gives me an error and I am not quite sure how to solve this. This is an example of the desired output of even numbers from 0 to 30:
4
26
12
10
20
It isn't clear why taking the remainder of 2 would yield an even number. Instead, generate a number in the range 0 to h / 2 and then multiply the result of that by 2. Like,
public int nextEven(int h){
int n = ThreadLocalRandom.current().nextInt(1 + (h / 2)); // 0 to (h / 2) inclusive
return n * 2; // n * 2 is even (or zero).
}
What exactly is rand? Is it the Random class or an instance of your own class?
Since you want to do something with inheritance I guess you want to overwrite a method, but if rand is an instance of the java Random class this won't work.
The error probably comes from recursively calling nextEven method forever.
If you could clarify what exactly you want to do?
I see at least two solutions.
The first one supposes that random + 1 = random. I mean, that if you add or subtract a random number you still get a valid random number. That's why you can use Random class to generate a value in the desired period and then add or subtract one it the number is odd.
The second approach is just to generate an array of even values for the desired period. Then take a random value from this array.
The mod operator % will give you the remainder of the first value divided by the second.
value % 2
... will return 0 if value is even, or 1 if value is odd.
Since rand is a reference to an instance of the class containing your code, you have an infinite recursion. What you really need is something like:
public int nextEven(int h){
int evenRandomValue;
do {
evenRandomValue = (int)(Math.random() * (h + 1));
} while(evenRandomValue % 2 == 1);
return evenRandomValue;
}
Here is a quite explicit way to achieve this using streams:
List<Integer> myRandomInts = Random.ints(lower, upper + 1)
.filter(i -> i % 2 == 0)
.limit(5).boxed()
.collect(Collectors.toList());
This can be read as 'generate an infinite stream of random numbers between given bounds, filter out odds, take the first 5, turn into Integer objects and then collect into a list.

Textfield JavaFX with dynamic mask for monetary values

I'm trying to create a textfield Java FX for a financial application. I would like this texfield to follow the same pattern as the numerical fields found in ATMs. For example: in ATM the initial value in the value field is "0.00". When the user types the value he wants to extract, for example, typing starts from right to left, replacing the leading zeros ... For example, I want to withdraw $ 99.90 (user type the 9 key three times and the 0 key once) and it happens that :
0.09 -> 0.99 -> 9.99 -> 99.90
Anyone have an idea how to create this mask?
I've seen several answers on similar topics but I could not adapt any of them to my project (maybe because I'm a beginner in Java and I'm still learning about the String class, textfield methods, etc.)
Thank you in advance for your attention.
P.S .: I am not yet fluent in English, so if there is any grammatical error in this message, it was because of the Google Translator I used to write
The basic algorithm is the following (pseudo code):
float value = 0; // The initial value is 0
// On Input
void input( int digit ){ // This is invoked when the user presses a digit on the keyboard
// You multiply the current value by ten and add the new digit
value *= 10;
value += digit * 0.01;
}
You will get the following steps for the 9990 input:
1: (0.00 * 10) + (9 * 0.01) = 0.09
2: (0.09 * 10) + (9 * 0.01) = 0.99
3: (0.99 * 10) + (9 * 0.01) = 9.99
4: (9.99 * 10) + (0 * 0.01) = 99.90

Computing Pi in Java

This weeks assignment in programming is to compute Pi in java using this as the basis for the assignment:
(for 80% of the marks):
USING A WHILE OR A DO-WHILE LOOP write a program to compute PI using the following equation:
PI = 3 + 4/(2*3*4) - 4/(4*5*6) + 4/(6*7*8) - 4/(8*9*10) + ...
Allow the user to specify the number of terms (5 terms are shown) to use in the computation.
Each time around the loop only one extra term should be added to the estimate for PI.
(for 20% of the marks):
Alter your solution from part one so that the user is
allowed to specify the precision required between 1 and 8 digits
(i.e. the number of digits which are correct; e.g. to 5 digits PI is 3.14159),
rather than the number of terms. The condition on the loop should be altered so that it
continues until the required precision is obtained. Note that you need only submit this
second version of the program (assuming you have it working).
I'm only able to use the above method to compute Pi, as thats what the lecturer wants. Ive got this so far, although the code keeps giving me the same wrong answer for every even number and a different wrong answer for each odd number. Im still on part one as i havent got the right answer yet to be able to progress onto part 2.
All help would be great, as the program needs to be submitted by tueday.
Thanks in advance!
import java.util.Scanner;
public class ComputePI {
public static void main(String[] args) {
System.out.print( "Please enter the amount of decimal "
+ "digits of PI, you would like to set it too");
Scanner termScan = new Scanner( System.in );
int term = termScan.nextInt();
termScan.close();
double pi = 3.0;
int loopCount = 2;
int number = 2;
while ( loopCount <= term )
{
if (loopCount % 2 == 0)
{
pi = pi + ( 4.0/ ((number) * (number+1) * (number+2)) );
}
else
{
pi = pi - ( 4.0 / ((number) * (number+1) * (number+2)) );
}
number = number + 2;
loopCount++;
}
System.out.print( "The Value of Pi in " + term +
" terms is equal to " + pi);
}
}
I am not going to give you code (you can figure it out for yourself, I'm certain), but I'll give you the location for where to look for the problem.
In the negative terms, you are adding 2 to each number multiplied together. However, you are adding 2 to each number in every iteration of the loop: the numberXXX + 2 part should probably just be numberXXX.
You are now also incrementing the numberXXX variables when loopCount is 1. In fact, the if (loopCount == 1) part is unnecessary, since you already initialize pi. You should just remove the if block there and switch the loopCount % 2 == X blocks around.
I'll also give you general advice about things you might want to consider in your code.
You don't need constants like 4.0 to be in a variable. Just replace fourConstant with 4.0.
You don't need to use an else if for the third block: if loopCount % 2 is not 0 it is definitely 1.
loopCount can only get integer values, so it should probably be an int. A double just consumes extra memory (this is not too problematic here, but may be in large programs) and can in some cases lead to errors (too large numbers may cause rounding errors).
You don't need three variables for numberOne, numberTwo and numberThree; they can always be represented as numberOne, numberOne + 1 and numberOne + 2.
You are incrementing the variables numerOne,numberTwo,numberThree in case the loopCount = 1. In this case you should just continue the loop without incrementing this variables. So change this:
if (loopCount == 1 )
{
pi = 3.0;
}
in:
if (loopCount == 1 )
{
pi = 3.0;
loopCount++;
continue;
}
And change this:
pi = pi - ( fourConstant / ((numberOne+2)*(numberTwo+2)*(numberThree+2)));
into:
pi = pi - ( fourConstant / ((numberOne)*(numberTwo)*(numberThree)));
Or you could just initialize loop count to 2 and remove the first if.
Additionally it would be better is loopCount and term were integer variables instead of Double since they are going to hold only integer values.

Learning Java - Do not fully understand how this sequence is calculated (Fibonacci) in for loop [duplicate]

This question already has answers here:
Java recursive Fibonacci sequence
(37 answers)
Closed 8 years ago.
I am learning Java and I have this code from the internet and running it in Eclipse:
public class Fibonacci {
public static void main (String [] args) {
for (int counter = 0; counter <= 3; counter++){
System.out.printf("Fibonacci of %d is: %d\n", counter, fibonacci(counter));
}
public static long fibonacci(long number) {
if ((number == 0) || (number == 1))
return number;
else
return fibonacci(number - 1) + fibonacci(number - 2);
}
}
I've tried to understand it but cannot get it. So I run through the code and counter gets passed in through the fibonacci method. As counter starts at 0 and this is what gets passed first, then 1 and I understand the method passes back 0 and then 1.
When it reaches 2: it will return 2-1 + 2-2 = 2 and it does return this.
When it reaches 3: it will return 3-1 + 3-2 = 3 but it does not return 3 it returns 2.
Please can someone explain to me why as I cannot figure this out?
Thanks
First, I have to tell you that this recursive version has a dramatic exponential cost. Once you understand how it works, my advice for you would be to learn about tail recursivity, write a tail-recursive solution, an iterative solution, and compare them to your current method for high values of "number".
Then, your function basically uses the mathematical definition of the Fibonacci sequence :
f0 = 1, f1 = 1, fn = fn-1 + fn-2 for all n >= 2
For example if we call fibonacci(3), this will return fibonacci(2) + fibonacci(1). fibonacci(2) will be executed first and will return fibonacci(1) + fibonnacci(0). Then fibonacci(1) will return immediately 1 since it is a terminal case. It happens the same thing with fibonnacci(0), so now we have computed fibonnacci(2) = 1 + 0 = 1. Let's go back to fibonacci(3) which has been partially evaluated at this point : 1 + fibonnacci(1). We just have to compute fibonnacci(1) and we can finally return 1 + 1 = 2.
Even in this little example, you can see that we evaluated twice fibonacci(1), that is why this version is so slow, it computes many times the same values of the sequence, and it gets worth when "number" is high.

Generating the list of random numbers with certain average difference

I have to generate a list of random numbers and they have to have a given average difference. For example, a given average difference is 10, so these numbers are good: 1 3 5 9 15 51. What I do, is multiply the given average difference by 2 and add 1. Like this:
while (i <= 50000)
{
i += Math.random() * givenAverageDiff * 2 + 1;
list.add(i);
}
But I never get 5000 or more. In fact, it's always 4,850 or less. Why? Let's say givenAverageDiff is 10. What's my mistake? How can I fix it?
P.S. Implementation in C or PHP is also good for me.
Because you are doing "+ 1".
Let us calculate the expected difference:
E(2*10*x+1)= 2*10*E(x)+1 = 2*10*0.5+1 = 10+1. So, on an average you will get 50000/11 numbers.
You need to pick something whose expected value is equal to 10. Change it to the following and it should work:
while (i <= 50000)
{
i += Math.random() * (givenAverageDiff-1) * 2 + 1;
list.add(i);
}
Think about it in terms of the ranges you create. With your current calculation,
i += Math.random() * givenAverageDiff * 2 + 1;
you are adding between 1 and 2*givenAverageDiff to your number. The sum of 1 through 2x is (2x)(2x+1)/2, and since there are 2x options we divide by 2x to get (2x)(2x+1)/(2*2x) = (2x+1)/2 = x + 0.5.
So what you want is to have 2x+1 options, which is easiest by using a range of [0,2*x]. You can get that by adding parenthesis:
i += Math.random() * (givenAverageDiff * 2 + 1);
If you want it to always increase, then you either need use a non-uniform distribution, or a uniform distribution with a smaller range. To get a range [n,2*x-n] use
i += Math.random() * ((givenAverageDiff - n) * 2 + 1) + n;
If you use a negative value for n you can widen the range, making it possible for numbers to decrease as well.

Categories