print the last line of a loop [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
What I'm trying to do is print the results in increments of 5 - DONE. Then, print only the last line of the loop. For ex: if z=26, print results of z # 5, 10, 15, 20, 25. Then println with z # 26. I'm stuck and can't figure it out.
for (int i = 1; i <= z; i++) {
b = b + (b * y) + x + w;
if (i % 5 == 0)
//input 1
System.out.println("In " + i + " years, IRA value: " + b);
//input 2 - value of IRA when retirement is reached
System.out.println();

I don't know what initial values b, x, w and y got so I just initialized them somehow ..
But I think you want something like this:
public class HelloWorld{
public static void main(String []args){
int z = 26;
int b = 0;
int x = 1;
int w = 2;
int y = 1;
for (int i = 1;i<=z;i++) {
b = b+(b*y)+x+w;
if (i % 5 == 0)
System.out.println("In " + i + " years, IRA value: " + b);
}
System.out.print(z);
}
}
Output:
In 5 years, IRA value: 93
In 10 years, IRA value: 3069
In 15 years, IRA value: 98301
In 20 years, IRA value: 3145725
In 25 years, IRA value: 100663293
26

Change your condition to
if(i%5==0 || i==z)

Adding an or (|| i==z) in the if will do the work
for (int i = 1;i<=z;i++) {
b = b+(b*y)+x+w;
if (i%5==0 || i==z)
//input 1
System.out.println("In " + i + " years, IRA value: " + b);
//input 2 - value of IRA when retirement is reached
System.out.println();
//end
}

Related

Creating a chain of loops dynamically based on a List

I am practicing Java and I was trying to create a program to calculate the amount of ways an number could be divided using a set number of dividers.
For instance:
100 is the number and the dividers are 50,20,5. What are the possible divisions.
The answer would be:
Amount of 50 : 0, Amount of 20 : 0, Amount of 10 : 10
Amount of 50 : 0, Amount of 20 : 1, Amount of 10 : 8
Amount of 50 : 0, Amount of 20 : 2, Amount of 10 : 6
Amount of 50 : 0, Amount of 20 : 3, Amount of 10 : 4
Amount of 50 : 0, Amount of 20 : 4, Amount of 10 : 2
Amount of 50 : 1, Amount of 20 : 0, Amount of 10 : 5
Amount of 50 : 1, Amount of 20 : 1, Amount of 10 : 3
Amount of 50 : 1, Amount of 20 : 2, Amount of 10 : 1
Amount of 50 : 2
I wrote a code that asks the user an amount and 3 dividers. Now I am trying to figure out if there is a way to dynamically create a code for as many dividers as the user wants. The code is in a way very repetitive and there is a certain pattern to add another divider but I cannot figure out how to implement this dynamic change to the code.
The first code I came up with to do this is the following:
public class Test2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Insert the amount:");
int amount = scanner.nextInt();
List<Integer> dividers = new ArrayList<>();
System.out.println("Insert the first divider:");
int tempDivider = scanner.nextInt();
if (!dividers.contains(tempDivider)) {
dividers.add(tempDivider);
}
while (dividers.size()<3) {
System.out.println("Insert the next divider: (" + (3-dividers.size()) + " more to go)");
tempDivider = scanner.nextInt();
if (!dividers.contains(tempDivider)) {
dividers.add(tempDivider);
}
}
dividers.sort(Collections.reverseOrder());
System.out.print("Dividers are: ");
System.out.println(dividers);
int getal1 = dividers.get(0);
int getal2 = dividers.get(1);
int getal3 = dividers.get(2);
int fiftyAmount = amount / getal1;
int fiftyRemainder = amount % getal1;
for (int i = 0; i <= fiftyAmount; i++) {
int currentFiftyAmount = amount - (getal1 * i);
int twentyAmount = currentFiftyAmount / getal2;
int twentyRemainder = currentFiftyAmount % getal2;
if (twentyAmount == 0) {
StringBuilder output = new StringBuilder();
output.append("Amount of " + getal1 + " banknotes: " + i);
if (fiftyRemainder != 0) output.append(", Remainder: " + fiftyRemainder);
System.out.println(output);
} else {
for (int j = 0; j <= twentyAmount; j++) {
int currentTwentyAmount = currentFiftyAmount - (getal2 * j);
int tenAmount = currentTwentyAmount / getal3;
int tenRemainder = currentTwentyAmount % getal3;
if (tenAmount == 0) {
StringBuilder output = new StringBuilder();
output.append("Amount of " + getal1 + " banknotes: " + i + ", Amount of " + getal2 + " banknotes: " + j);
if (tenRemainder != 0) output.append(", Remainder: " + twentyRemainder);
} else {
StringBuilder output = new StringBuilder();
output.append("Amount of " + getal1 + " banknotes: " + i + ", Amount of " + getal2 + " banknotes: " + j +
", Amount of " + getal3 + " banknotes: " + tenAmount);
if (tenRemainder != 0) output.append(", Remainder: " + tenRemainder);
System.out.println(output);
}
}
}
}
}
}
I tried to make this more abstract to figure out a way to automate the creation of the extra dividing loops but I cannot figure it out.
The more abstract version I wrote is the following:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Insert the amount:");
int amount = scanner.nextInt();
List<Integer> dividers = new ArrayList<>();
System.out.println("Insert the first divider:");
dividers.add(scanner.nextInt());
int divider;
while (dividers.size()<2) {
System.out.println("Insert the next divider: (" + (2-dividers.size()) + " more to go)");
divider = scanner.nextInt();
if (!dividers.contains(divider)) {
dividers.add(divider);
}
}
dividers.sort(Collections.reverseOrder());
System.out.print("Dividers are: ");
System.out.println(dividers);
int divided1Amount = amount / dividers.get(0);
int divided1Remainder = amount % dividers.get(0);
for (int i = 0; i <= divided1Amount; i++) {
int currentDivided1Amount = amount - (dividers.get(0) * i);
int divided2Amount = currentDivided1Amount / dividers.get(1);
int divided2Remainder = currentDivided1Amount % dividers.get(1);
if (divided2Amount == 0) {
StringBuilder output = new StringBuilder();
output.append(dividers.get(0) + ":" + i);
if (divided1Remainder != 0) {
output.append(", Remainder: " + divided1Remainder);
}
System.out.println(output);
} else {
StringBuilder output = new StringBuilder();
output.append(dividers.get(0) + ":" + i + "," + dividers.get(1) + ":" + divided2Amount);
if (divided2Remainder != 0) {
output.append(", Remainder: " + divided2Remainder);
}
System.out.println(output);
}
}
}
}
This is also available on GitHub: https://github.com/realm1930/rekendin/blob/master/src/Main.java
Could anybody please enlighten me. I am sorry if I am not clear at my description of the issue.
Thanks
While a fixed number of dividers can be well approached with nested loops, I suggest for the general case to write the solution as a recursive function.
This problem is a good fit for dynamic programming. What I mean by this is that the problem can be broken down into simpler subproblems, and in this way the solution is naturally implemented with recursion. For instance, in your example of expressing 100 as a sum of multiples of 50, 20, and 10, there are three solutions found that all use one 50:
Amount of 50 : 1, Amount of 20 : 0, Amount of 10 : 5
Amount of 50 : 1, Amount of 20 : 1, Amount of 10 : 3
Amount of 50 : 1, Amount of 20 : 2, Amount of 10 : 1
Look at this as solving the subproblem of finding the ways that value 50 can be expressed as multiples of 20 and 10 (that is, 50 is equal to 20*0 + 10*5, 20*1 + 10*3 and 20*2 + 10*1). So you can divide-and-conquer the original problem in this sense.
Let X be the number (e.g. 100) to express, and D1, D2, ... DN the dividers. Here is a possible outline:
If there is just one divider, N = 1, it is easy: there just zero or one solution depending on whether D1 divides X.
Otherwise, possible solutions might have D1 with any multiple from 0, 1, ..., X/D1. So make a loop m1 = 0, 1, ..., X/D1, and recursively solve the subproblem having X' = X - m1*D1 and the remaining dividers D2, ..., DN. This subproblem has one fewer divider, so after enough recursions it reduces to the N = 1 case.
That solves the problem. Note, though, that fully recursing may result in a combinatorially vast number of subproblems to solve. So for efficient solution it is a good idea to store or "memoize" the solutions of previously-solved subproblems in a table so that work isn't repeated.
Other thoughts:
Let Q be the greatest common divisor (GCD) of all the dividers {D1, ..., DN}. If X isn't divisible by Q, then there are no solutions, in which case we can skip the above recursive search entirely. E.g. there is no way to express X = 103 with dividers 50, 20, and 10. This GCD test can also be applied to every subproblem so that some recursive calls can return early.
This problem is a kind of Diophantine equation, more specifically, it is related to the Frobenius coin problem and Frobenius numbers. There is a mathoverflow post discussing it.

Java ,int x = 5; System.out.println(" x + 5 is " + x + 5); System.out.println("x += 5 is " + x += 5); why second println is mistake?

Java
int x = 5;
System.out.println(" x + 5 is " + x + 5);//correct
System.out.println("x += 5 is " + x += 5);// why wrong?
Even though, these 2 println is including calculation but why second println is error.Thanks
What you are doing causes an error because the + is seen as an operator to seperate parts of the string. Try placing that part between brackets like:
System.out.println("x += 5 is " + (x += 5));
This might fix it as you exclude the + from the string. Hope this helps you a bit, and that I am correct in my statement.

Printing from a loop

I need to print the factors of a perfect number. Here's the gist of my main class:
ArrayList<Integer> perfNums = new ArrayList<>();
Scanner in = new Scanner(System.in);
System.out.print("Enter the upperbound: ");
upperbound = in.nextInt();
for (int i = 1; i <= upperbound; i++) {
if (isPerfect(i)) { //boolean to check if number is a perfect number
perfNums.add(i);
}
}
System.out.println("Perfect numbers between 1 and " + upperbound + " are:");
for (int i = 0; i < perfNums.size(); i++) {
System.out.print(perfNums.get(i) + " = ");
printFactor((int)perfNums.get(i));
System.out.println();
}
Here's the printFactor class.
private static void printFactor(int number){
int factor = 1;
while(factor < number){
if (number%factor == 0) System.out.print(factor+ " + ");
//I don't know how to print the + sign otherwise.
factor++;
}
}
And here's a sample output:
Enter the upperbound: 10000
Perfect numbers between 1 and 10000 are:
6 = 1 + 2 + 3 +
28 = 1 + 2 + 4 + 7 + 14 +
496 = 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248 +
8128 = 1 + 2 + 4 + 8 + 16 + 32 + 64 + 127 + 254 + 508 + 1016 + 2032 + 4064 +
I've got the main gist of it but I've struggled with an output issue. Due to the restrictions of my online submission system, my output needs to fit exact specifications.
My question is how do I go about printing all the factors of my perfect number but removing the + sign at the end? (e.g)6 = 1 + 2 + 3
I'm not too sure of many methods to print from a while loop. Would a for-loop be better for my goals? Or are there alternative methods to print the factors of a number?
The least amount of change to address this might be something like this:
private static void printFactor(int number)
System.out.print(1);
int factor = 2;
while (factor<number) {
if (number%factor == 0) System.out.print(" + " + factor);
factor++;
}
}
1 is always a factor, so you can print that before the loop and then prepend + to every subsequent factor.
You should cache the output you want to print into a StringBuilder. Then you are able to remove the last plus sign before you print the whole String. It also has a better performance.
private static void printFactor(int number)
{
StringBuilder output = new StringBuilder();
int factor = 1;
while (factor < number)
{
if (number % factor == 0)
output.append(factor + " + ");
factor++;
}
// remove last plus sign
output.deleteCharAt(output.length() - 1);
// print the whole string
System.out.print(output.toString());
}
Since factor starts from value 1 and number % 1 == 0 will always be true, you might print 1 first and then flip factor and + in System.out.print. Like this:
private static void printFactor(int number) {
if(number > 0) {
System.out.print(1);
}
int factor = 2;
while (factor<number) {
if (number % factor == 0) {
System.out.print(" + " + factor);
}
factor++;
}
}
Not the best solution, but it will do the job.
Try to create a variable String numb and use substring method like this:
String numb ="";
while(factor<number){
if(number%factor == 0)
numb= numb + factor+ " + ";
factor++;
}
System.out.print(numb.substring(0, numb.trim().length()-1));
Just for the sake of using Java 8 :)
private static void printFactor(int number){
System.out.println(IntStream.range(1, number)
.filter(p -> number % p == 0)
.mapToObj(i -> String.valueOf(i))
.collect(Collectors.joining(" + ")));
}
Thanks everyone for the quick response. You all have been a lifesaver, and I managed to pick up some new things to consider when I code in the future.
Anyway, while waiting for a reply I was fiddling with the code and came up with a rather inelegant solution, if anybody's interested. Here's the changes to the main class:
System.out.println("Perfect numbers between 1 and " + upperbound + " are:");
for(int i=0; i<perfNums.size(); i++){
System.out.print(perfNums.get(i) + " = ");
outputString = printFactor2(perfNums.get(i));
if(outStr.endsWith(" + ")) outStr = outStr.substring(0, outStr.length()-3);
//because the submission system would cry foul with even a single extra space
System.out.println(outStr);
}
And here's the changes to the printFactor class:
private static String printFactor2(int number){
String out = "";
int factor = 1;
while(factor<number){
if(number%factor == 0) out += factor + " + ";
factor++;
}
return out;
}
Basically, what I did was append the factors to a string, then removing the trailing + sign using the substring method. On hindsight, I probably should've called the substring method inside the printFactor class instead. Something like return out.substring(0, out.length()-3); perhaps?
Nevertheless, thanks everyone!

Average incorrect : decimal point always .0 [duplicate]

This question already has answers here:
How to make the division of 2 ints produce a float instead of another int?
(9 answers)
Closed 5 years ago.
I'm pretty new to arrays and am trying to create a simple program that calculates the average of 5 numbers. However, when the average is calculated, it always has a decimal point of 0 rather than what it should be, but I'm not sure why..
For example, if I type in 4, 4, 4, 4, 3, it displays 3.0 as the average rather than 3.8. Please help!
int[] boxes = new int[5];
for (int i = 1 ; i <= 5 ; i++)
{
System.out.print("Enter number " + i + " > ");
int n = Integer.parseInt(kb.nextLine());
boxes[i-1] = n;
}
double mean = ( boxes[0] + boxes[1] + boxes[2] + boxes[3] + boxes[4] ) / 5;
System.out.println("The average of those five numbers is: " + mean);
Thank you!! :)
it is because the operation is done with integers , change your 5 to 5.0
I cannot answer you the specifics but there is a huge topic in java called type casting. I reckon, you read it. This is a good puzzle for you to solve yourself. Reminds me of my past :)
Fast fix: change 5 -> 5.0D.
Why? Let's look at dividing process more detail:
You get sum from all numbers: ( boxes[0] + boxes[1] + boxes[2] + boxes[3] + boxes[4] ), result -> int.
You divide sum(int type) / 5(int type) = result also int type 3.8 -> 3.
Last one its autocast int -> double.
That's why you get what you see.
Solution 1 :
- You can use 5.0 instead of 5 to have a double division.like that:
double mean = ( boxes[0] + boxes[1] + boxes[2] + boxes[3] + boxes[4] ) / 5.0;
Solution 2 :
- You can use a double cast of your sum like that:
double mean = (double)( boxes[0] + boxes[1] + boxes[2] + boxes[3] + boxes[4] ) / 5;
To improve your answer:
You can use int n=kb.nextInt(); instead of int n = Integer.parseInt(kb.nextLine());
You can count the sum in for loop like that:
int[] boxes = new int[5];
int sum=0;
for (int i = 1 ; i <= 5 ; i++)
{
System.out.print("Enter number " + i + " > ");
int n=kb.nextInt();
boxes[i-1] = n;
sum +=boxes[i-1];
}
double mean = sum / 5.0;
System.out.println("The average of those five numbers is: " + mean);

Making a method analyzing a given value [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want to make a method that analyze a given value
void method(int value)
if this value equals for example 7, I want output to be like this :
7 = 12 * 0 + 7
if value = 13 output : 13 = 12 * 1 + 1
if value = 24 output : 24 = 12 * 2 + 0
if value = 39 output : 39 = 12 * 3 + 3
if value = 289 output : 289 = 12 * 24 + 1
and so on
12 is constant
How can I make this ?
Looks like you are looking for
12 * x + y
This means:
x = value / 12;
y = value % 12;
void method(int value) {
int x = value / 12;
int y = value % 12;
System.out.print(value + " = 12 * " + x + " + " + y);
}
The method that you are looking for could be something like the snippet that I have written above.
Here is the complete code:
public class SingleItemView {
public static void main(String[] args) {
SingleItemView.getNumber(14); // Pass the value for which you need the expression
}
public static void getNumber(int n) {
int temp1 = 0;
int temp2 = 0;
if (n > 12) {
temp1 = n / 12;
temp2 = n % 12;
System.out.println(n + " = 12 * " + temp1 + " + " + temp2);
} else {
System.out.println(n + " = 12 * 0 + " + n);
}
}
}
In your main method you are passing value to the method for which you need to expression.

Categories