我正在尝试创建一个程序,它列出了100到1000之间可被5或6整除的所有数字.这是我使用的代码:
public class divisibleBy5and6 {
public static void main (String[] args) {
j = 1;
int number = 100;
while (number < 1001) {
if (number % 6 == 0 || number % 5 == 0) {
System.out.print(number + ", ");
number++;
j++; }
if (j % 10 == 0 && j != 0) {
System.out.println();
j++; }
else {
number++;
}
}
Run Code Online (Sandbox Code Playgroud)
我曾经int j这样做,所以每行有9个.这是我的输出:
100, 102, 105, 108, 110, 114, 120, 125, 130,
132, 135, 138, 140, 144, 150, 155, 160, 162,
165, 168, 170, 174, 180, 185, 190, 192, 195,
198, 200, 204, 210, 215, 220, 222, 225, 228,
230, 234, 240, 245, 250, 252, 255, 258, 260,
264, 270, 275, 280, 282, 285, 288, 290, 294,
295, 300, 305, 310, 312, 315, 318, 320, 324,
325, 330, 335, 340, 342, 345, 348, 350, 354,
355, 360, 365, 370, 372, 375, 378, 380, 384,
385, 390, 395, 400, 402, 405, 408, 410, 414,
415, 420, 425, 430, 432, 435, 438, 440, 444,
445, 450, 455, 460, 462, 465, 468, 470, 474,
475, 480, 485, 490, 492, 495, 498, 500, 504,
505, 510, 515, 520, 522, 525, 528, 530, 534,
535, 540, 545, 550, 552, 555, 558, 560, 564,
565, 570, 575, 580, 582, 585, 588, 590, 594,
595, 600, 605, 610, 612, 615, 618, 620, 624,
625, 630, 635, 640, 642, 645, 648, 650, 654,
655, 660, 665, 670, 672, 675, 678, 680, 684,
685, 690, 695, 700, 702, 705, 708, 710, 714,
715, 720, 725, 730, 732, 735, 738, 740, 744,
745, 750, 755, 760, 762, 765, 768, 770, 774,
775, 780, 785, 790, 792, 795, 798, 800, 804,
805, 810, 815, 820, 822, 825, 828, 830, 834,
835, 840, 845, 850, 852, 855, 858, 860, 864,
865, 870, 875, 880, 882, 885, 888, 890, 894,
895, 900, 905, 910, 912, 915, 918, 920, 924,
925, 930, 935, 940, 942, 945, 948, 950, 954,
955, 960, 965, 970, 972, 975, 978, 980, 984,
985, 990, 995, 1000,
Run Code Online (Sandbox Code Playgroud)
这显然是不对的,因为我缺少像这样的数字115.我究竟做错了什么?
您需要从if/else语句中分隔数字增量.它应该在每次迭代时发生,无论是什么......
int j = 1;
int number = 100;
while (number < 1001) {
if (number % 6 == 0 || number % 5 == 0) {
System.out.print(number + ", ");
j++;
}
if (j % 10 == 0) {
System.out.println();
}
number++;
}
Run Code Online (Sandbox Code Playgroud)