Reputation: 75
I have no idea how to phrase the title so feel free to make changes! I am stuck on this program that I have made involving a loop. I want the input to be 1 5
which means the code starts adding from 1 and all the way until 5, the expected output would be 1 + 2 + 3 + 4 + 5 = 15
but my code (see below) would print something like 1 + 2 + 3 + 4 + 5 + = 15
. How do I get rid of that unwanted addition symbol?
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int start = keyboard.nextInt();
int end = keyboard.nextInt();
double dend = (double)end;
double dstart = (double)start;
double n = (dend - dstart + 1);
double sum = (n/2)*(dend+dstart);
int intsum = (int)sum;
for (int i =start; i <= end; i++) {
System.out.print(i+" + ");
}
System.out.print(" = "+intsum);
}
Upvotes: 0
Views: 47
Reputation: 21
An alternate solution would be to count the number of iterations and check if it is on it's last iteration. If not, then print a "+".
Upvotes: 0
Reputation: 303
As already mentioned by Scary Wombat you can reduce the lopping by one but in your code you are doing string concatenation for each element which not good (because of immutability nature of string in java).
So better to use some mutable string object (either StringBuilder/StringBuffer) and also you can have look at Collectors.joining() (which is introduced in Java8) if you would like implement this using streams.
Upvotes: 0
Reputation: 324108
The logic could be something like:
for (int i =start; i <= end; i++)
{
if (i > start)
System.out.print(" + ");
System.out.print(i);
}
The idea is you only print "+" AFTER the first iteration of the loop.
Another option is to use a StringJoiner:
StringJoiner sj = new StringJoiner(" + ");
for (int i =start; i <= end; i++)
{
sj.add( i + "" ); // converts the "i" to a string
}
System.out.print( sj.toString() );
The StringJoiner will add the delimiter for you automatically as required.
Upvotes: 0
Reputation: 44824
You could reduce the looping by one, and then print again
for (int i =start; i < end; i++) {
System.out.print(i+" + ");
}
System.out.print(end);
System.out.print(" = "+intsum);
or you could have if
logic in your loop
for (int i =start; i <= end; i++) {
System.out.print(i);
if (i != end) System.out.print(" + ");
}
Upvotes: 1