Align decimals in a list of doubles in Java - java

Here's the code section:
System.out.println("The values of pi from term " + (userNum - 9) + " to term " + userNum + " are:");
for (int x = 1; x < userNum; x++)
{
if (x % 2 == 1)
sum = sum + (4.0/(2 * x - 1));
else
sum = sum - (4.0/(2 * x - 1));
System.out.println("Term " + (x) + ": " + sum);
}
And here's the output:
The values of pi from term 2 to term 11 are:
Term 1: 4.0
Term 2: 2.666666666666667
Term 3: 3.466666666666667
Term 4: 2.8952380952380956
Term 5: 3.3396825396825403
Term 6: 2.9760461760461765
Term 7: 3.2837384837384844
Term 8: 3.017071817071818
Term 9: 3.2523659347188767
Term 10: 3.0418396189294032
Term 10's decimal needs to align with the others. How can that be done in Java? Thanks.

System.out.printf resembles (but is not) the C printf method. You can use it do to something like:
int spaces = (int)Math.log10(Math.abs(userNum)) + 1;
String myFormat = "Term %" + spaces +"d: %.10f\n";
//inside the for loop
System.out.printf(myFormat , x, sum);
Edited: You can use %2d to have a number using 2 spaces, if the number is bigger then it will use more spaces.
More info:
PrintStream‌​ (search for printf method)

If you use Apache commons lang, you could use the StringUtils class to accomplish what you need:
System.out.println("Term " +
StringUtils.leftPad("" + x, (userNum.length() - x.length()), ' ')
+ ": " + sum);

It seems you want to add space after Term depending on the number of digits of x:
int j = String.valueOf(x).length();
String sp = "";
while( j++ < String.valueOf(userNum).length() )
sp += " ";
System.out.printf("Term %s %d : %.15f\n", sp, x, sum);

Related

Empty single quotation [duplicate]

This question already has answers here:
In Java, is the result of the addition of two chars an int or a char?
(8 answers)
Closed 5 years ago.
Can anyone explain why adding an empty single quotation (at the end of this code) creates 32? I have changed the integers 3 and 4 and every time I do this, the base number seems to be 32.
public static void main(String[] args) {
int number = 5;
System.out.println("Initial Value: " + number);
number = number*2;
number = number*2;
System.out.println("\n1. After doubling it twice: " + number);
number = number + 3;
number += 3;
System.out.println("\n2. After adding 3 twice: " + number);
number -= 12;
System.out.println("\n3. After subtracting 12: " + number);
number = number / 3;
System.out.println("\n4. After dividing by 3: " + number);
System.out.println();
number ++;
System.out.println("add 1: " + number);
number ++;
System.out.println("add 1: " + number);
number ++;
System.out.println("add 1: " + number);
number ++;
System.out.println("add 1: " + number);
System.out.println("\n5. After adding 1 four times: " + number);
number -= 1;
System.out.println("\n6. After decrementing once: " + number);
int remainder = number%= 3;;
System.out.println("\n7. Remainder when dividing by 3 is :" + remainder);
int a = 2, b = 3, c = 5;
double d1, d2, d3, d4;
d1 = a + b * c / 2;
d2 = (a + b * c) / 2;
d3 = (a + b) * c / 2;
d4 = (a + b) * (c / 2);
System.out.println("\n8. Values: " + d1 + " : " + d2 + " : " + d3
+ " : " + d4);
int p, q;
p = 10;
q = 10;
p += q++;
System.out.println("\n9. Result is: " + (p + q));
double d7 = 4.3, d8 = 34.7;
double truncatedSum = (4.3 + 34.7);
System.out.println("\n10. Sum is " + truncatedSum);
System.out.println("\n11.");
System.out.println("fred " + 3 + 4);
System.out.println(3 + 4 + " fred");
System.out.println("" + 3 + 4);
**System.out.println(' ' + 3 + 4);**
}
OUTPUT
Initial Value: 5
After doubling it twice: 20
After adding 3 twice: 26
After subtracting 12: 14
After dividing by 3: 4
add 1: 5
add 1: 6
add 1: 7
add 1: 8
After adding 1 four times: 8
After decrementing once: 7
Remainder when dividing by 3 is :1
Values: 9.0 : 8.0 : 12.0 : 10.0
Result is: 31
Sum is 39.0
11.
fred 34
7 fred
34
39
Here the thing
System.out.println(' ' + 3 + 4);
' ' is of char type which is a numeric data type in Java:
char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
and it corresponds to a numeric value of space character in UNICODE chart, e.g. 32.
Therefore, the result of this computation will be 32 + 3 + 4 or 39 as you can see in your output.
' ' + 3 + 4
as chars are numeric types in Java, ' ' stands for space character int value
Space is 32 in ASCII, so the result is:
32 + 3 + 4 = 39

Modify solution to use a single loop

I managed to solve this, below is my solution :
public class ProblemA001k {
public static void main(String[] args) {
System.out.println("Sum from 1" + " to " + divQ + ":" + sum2);
System.out.println();
divQ += q;
newQ += q;
sum1 = 0;
sum2 = 0;
}
key.close();
}
}
Now I was told to modify my solution so that it uses ONLY ONE LOOP.
I have 3 loops in the code above, even when I tried using only 2 loops I struggled. but ONE LOOP ? I don't know how to improve my code. Please help me.
This is a Mathematic problem.
If you know that you can find the sum of all integers from 1 to X, you just need to do X * (X+1) / 2.
You can find all the batch values easily.
Sum from 1 to 400: 80200
Sum from 401 to 450: 21275
Sum from 1 to 450: 101475
Will be found like this :
450 * 451 / 2 = 101475 (1 to 450)
400 * 401 / 2 = 80200 (1 to 400)
101475 - 80200 = 21275 (401 to 450)
With this, you can limit the loop to just calculate the values from q to n by incrementing by q
And a quick code to do it :
static void sum(int n, int q){
int i = q;
int sum, tmp=0;
while(i < n){
sum = i * (i+1) / 2;
System.out.println(String.format("Sum from %d to %d : %d", i-q+1 , i, sum - tmp));
System.out.println(String.format("Sum from %d to %d : %d", 1, i, sum));
tmp = sum;
i += q;
}
}
And I run it with
public static void main(String[] args){
sum(500, 50);
}
to have this result
Sum from 1 to 50 : 1275
Sum from 1 to 50 : 1275
Sum from 51 to 100 : 3775
Sum from 1 to 100 : 5050
Sum from 101 to 150 : 6275
Sum from 1 to 150 : 11325
Sum from 151 to 200 : 8775
Sum from 1 to 200 : 20100
Sum from 201 to 250 : 11275
Sum from 1 to 250 : 31375
Sum from 251 to 300 : 13775
Sum from 1 to 300 : 45150
Sum from 301 to 350 : 16275
Sum from 1 to 350 : 61425
Sum from 351 to 400 : 18775
Sum from 1 to 400 : 80200
Sum from 401 to 450 : 21275
Sum from 1 to 450 : 101475
The good think with this solution is the number of loop, this will increment by q instead of 1
Note : The solution is a quick implementation, this could be done better.
EDIT :
Thanks to Margaret Bloom in the comments to point out the name of this formula :) For more information, you are welcome to look at Triangular Number
This should do it:
int totalSum = 0;
int batchSum = 0;
for (int i = 1; i <= n; i++) {
totalSum += i;
batchSum += i;
if (i % q == 0) {
System.out.println("Sum from " + (i - q + 1) + " to " + i + ":" + batchSum);
System.out.println("Sum from 1 to " + i + ":" + totalSum);
batchSum = 0;
}
}
Edit:
The better Math way:
int lastTotalSum = 0;
for (int i = 1; i <= n / q; i++ ) {
int top = i * q;
int totalSum = top * (top + 1) / 2;
int batchSum = totalSum - lastTotalSum;
System.out.println("Sum from " + (top - q + 1) + " to " + top + ":" + batchSum);
System.out.println("Sum from 1 to " + top + ":" + totalSum);
lastTotalSum = totalSum;
}
I found a nice solution with java8 Streams:
int n=1000;
int q=50;
int length = n/q -1;
int[] previousSum={0};
IntStream.range(0, length).map(i -> (i+1)*q).forEach(s -> {
int sum=(s*(s+1))/2;
int batch = sum - previousSum[0];
previousSum[0] = sum;
System.out.println("Sum from " + (s - q + 1) + " to " + s + ":" + batch);
System.out.println("Sum from 1 to " + s + ":" + sum);
});
Do one loop iterating entire range and use indexes to decide whether to add, reset or print your sums.
Hope this gives your right idea, if you still dont know I can illustrate it a bit more.

Duplicating prime numbers of even numbers

This part of an assignment requires to check every even number in an array for 2 prime numbers that add up to that even number. I already managed to find all the primes between 2 and each even number and put those primes in a separate array list. I've already found how to find 2 prime numbers that add up to each even number; however when I check the output, it gives me multiple answers like this:
How many numbers would you like to compute:
12
Your two prime factors that add up to 4 are:
2 & 2
Your two prime factors that add up to 6 are:
3 & 3
Your two prime factors that add up to 8 are:
3 & 5
Your two prime factors that add up to 8 are:
5 & 3
Your two prime factors that add up to 10 are:
3 & 7
Your two prime factors that add up to 10 are:
5 & 5
Your two prime factors that add up to 12 are:
5 & 7
Your two prime factors that add up to 12 are:
7 & 5
All I want is ONE pair of primes that sum up to each even number in a loop. My code looks like this:
//For Loop looks at every even number in the arrayList
//for(int c = 0; c < len; c++) {
//Code for Numbers that come before every even number
//Code for Finding primes
//Finding prime numbers that add up to even number
int len3 = primeNumbers.size();
for(int f = 0; f < len3; f++) {
if(primeNumbers.get(f) + primeNumbers.get(f) == index) {
System.out.println("Your two prime factors that add up to " + index + " are: ");
System.out.println(primeNumbers.get(f) + " & " + primeNumbers.get(f));
break;
}
for(int g = 1; g < len3; g++) {
if(primeNumbers.get(f) + primeNumbers.get(g) == index) {
System.out.println("Your two prime factors that add up to " + index + " are: ");
System.out.println(primeNumbers.get(f) + " & " + primeNumbers.get(g));
break;
}
}
}
}
Try this. Your second loop should start from f. So if you do that u can remove the first if you have and then have this. I havent tested it. But try and let me know if it works.
for(int f = 0; f < len3; f++) {
for(int g = f; g < len3; g++) {
if(primeNumbers.get(f) + primeNumbers.get(g) == index) {
System.out.println("Your two prime factors that add up to " + index + " are: ");
System.out.println(primeNumbers.get(f) + " & " + primeNumbers.get(g));
}
}
}
When you call break statement it simply break current loop if your method only handle this logic simply change break statement to return. Hope this is you expect :
int len3 = primeNumbers.size();
for (int f = 0; f < len3; f++) {
if (primeNumbers.get(f) + primeNumbers.get(f) == index) {
System.out.println("Your two prime factors that add up to " + index + " are: ");
System.out.println(primeNumbers.get(f) + " & " + primeNumbers.get(f));
return;
}
for (int g = 1; g < len3; g++) {
if (primeNumbers.get(f) + primeNumbers.get(g) == index) {
System.out.println("Your two prime factors that add up to " + index + " are: ");
System.out.println(primeNumbers.get(f) + " & " + primeNumbers.get(g));
return;
}
}
}

Printing out frequency of letters instead of how many times?

I'm trying to change my code so that it prints how the frequency of the letters and not how many there is e.g. "I am a man I am a man" should give the same answer as "I am a man" since the relative proportions of each letter to the whole sequence is the same.
So the desired output would be:
Letter A: Count: 0.43
Letter I: Count: 0.14
Letter M: Count: 0.29
Letter N: Count: 0.14
So the count will always add up to 1.0.
At the moment, my code just counts and displays how many times the letter appears, is this simple to change?
//
You could try something like this to get the percent of total characters:
int total = 0;
for(int i = 0; i < lettersArray.length; i ++)
{
total += letterArray[i];
}
for (char characters = 'a'; characters <= 'z'; characters++) {
int index = characters - 'a';
//print out the analysis
System.out.println("'" + characters + "' entered " + (((double)letterArray[index] / (double)total))
+ " times");
}}}
System.out.println("'" + characters + "' entered " + letterArray[index] /
(double)line.length() + " times");

Monthly Asset Depreciation

I am writing a desktop application which will be used to calculate the monthly depreciation and Accumulation of an asset.
The accumulation is based on the number of months the user specifies.
therefore if the user specified 12 months, it should accumulate over those months.
Also the user should be able to view the accumulation value for for every month so far it is in the specified number of months. e.g if i select January it should give me the accumulated value for January and so on......
CHALLENGES : first challenge is getting the accumulation values for all the user specified months 2nd one is how to link this concept with my j form and my database since the codes i have works but how to fuse it into my program is a problem.
Depreciation Method: Straight line
below is a sample code
private void getAccumulation() {
try {
for (int row = 0; row <= 5; row++) {
double Cost_Of_Acquisition = 2000;
double Estimated_Residual_Value = 250;
int Estimated_Useful_Life = 5;
int depreciationMethod = 1;
System.out.println(" acquisition cost of asset = " + (int) Cost_Of_Acquisition);
System.out.println(" salvage value = " + (int) Estimated_Residual_Value);
System.out.println(" number of months = " + Estimated_Useful_Life);
System.out.println(" depreciation method = " + depreciationMethod);
for (int y = 1; y <= 5; y++) {
switch (depreciationMethod) {
case 1:
System.out.println(" straight line depreciation ");
double StraightLineDepreciation = ((Cost_Of_Acquisition - Estimated_Residual_Value) / Estimated_Useful_Life);
double AccumulatedDeprecaitionSL = (StraightLineDepreciation * y);
System.out.println("Asset number " + "1" + " uses straight line depreciation");
System.out.println(" depreciation charge for asset number " + "1" + " in month " + y + "=" + StraightLineDepreciation);
System.out.println("accumulated depreciation is " + AccumulatedDeprecaitionSL);
break;
case 2:
System.out.println(" sum of months digits depreciation ");
int SumofMonths = (0);
break;
}
}
}
}
}

Categories

Resources