In: Computer Science
Any idea why the code below prints the numbers up and down instead of sideways?
They should print like this:
299 297 275 273 264
260 253 247 242 234
231 221 220 209 208
Found 15 integers totaling 3733
Mine prints like this:
299
297
275
273
264
260
253
247
242
234
231
221
220
209
208
Number of multiples are: 15 The sum of multiples are: 3733
public static void main(String[] args) { //start of the main { int highestNumber = 300; int countOfNumbers = 0; int totalSum = 0; while (highestNumber >= 200) { if ((highestNumber % 11 == 0) && (highestNumber % 13 != 0)) { System.out.println(highestNumber + ""); countOfNumbers++; totalSum += highestNumber; if (countOfNumbers % 5 == 0) System.out.println(); } if ((highestNumber % 13 == 0) && (highestNumber % 11 != 0)) { System.out.println(highestNumber + ""); countOfNumbers++; totalSum += highestNumber; if (countOfNumbers % 5 == 0) System.out.println(); } highestNumber = highestNumber - 1; } System.out.println("Number of multiples are: " + countOfNumbers + " The sum of multiples are: " + totalSum); } } }
It is solved by removing ln from println which prints a newline character. And also included space in both the print statements. (These have been commented for reference).
CODE
import java.util.*;
// Compiler version JDK 11.0.2
class Dcoder
{
public static void main(String[] args) { //start of the main
{
int highestNumber = 300;
int countOfNumbers = 0;
int totalSum = 0;
while (highestNumber >= 200) {
if ((highestNumber % 11 == 0) && (highestNumber % 13 != 0)) {
System.out.print(highestNumber + " ");// remove ln from println
// and include space
countOfNumbers++;
totalSum += highestNumber;
if (countOfNumbers % 5 == 0)
System.out.println();
}
if ((highestNumber % 13 == 0) && (highestNumber % 11 != 0)) {
System.out.print(highestNumber + " ");// same editing here also
countOfNumbers++;
totalSum += highestNumber;
if (countOfNumbers % 5 == 0)
System.out.println();
}
highestNumber = highestNumber - 1;
}
System.out.println("Number of multiples are: " + countOfNumbers + " The sum of multiples are: " + totalSum);
}
}
}
Refer below for output preview.
Please Upvote if you found it helpful :)