[英]How to change the increment in a loop to more than one?
For one of my programming projects, I was told to make one of these charts: 对于我的一个编程项目,有人告诉我制作以下图表之一:
1 - 10 | *****
11 - 20 | **
21 - 30 | *******************
31 - 40 |
41 - 50 | ***
51 - 60 | ********
61 - 70 | **
71 - 80 | *****
81 - 90 | *******
91 - 100| *********
This is an array that when the user inputs numbers in a particular range it adds a *
for each value entered in that range. 这是一个数组,当用户在特定范围内输入数字时,它将为该范围内输入的每个值添加一个
*
。 I have already created a program that creates one of these charts. 我已经创建了创建这些图表之一的程序。 My next programming project tells me to only add an
*
for every five values entered in a particular range of numbers. 我的下一个编程项目告诉我,在特定数字范围内输入的每五个值仅添加一个
*
。 If less than 5 values are entered then no *
's will be printed. 如果输入的值小于5,则不会打印
*
。 I don't know how I should approach this problem. 我不知道该如何解决这个问题。
Here is the code for the chart: 这是图表的代码:
import java.util.Scanner;
public class SixFive
{
public static void main(String[] args)
{
int[] counts = new int[10];
Scanner scan = new Scanner(System.in);
System.out.println("Enter integers between 1-100");
while(scan.hasNextInt())
{
int num = scan.nextInt();
if (num < 1 || num > 100)
break;
counts[(num - 1) / 10]++;
}
scan.close();
for (int i = 0; i < 10; i++)
{
System.out.format("%2d -%3d ", i*10+1, i*10+10);
for (int j = 0; j < counts[i]; j++)
System.out.print("*");
System.out.println();
}
}
}
In your inner loop, replace the condition j < counts[i]
by j < counts[i] / 5
like this: 在您的内部循环中,将条件
j < counts[i]
替换为j < counts[i] / 5
如下所示:
for (int i = 0; i < 10; i++) {
System.out.format("%2d -%3d | ", i * 10 + 1, i * 10 + 10);
for (int j = 0; j < counts[i] / 5; j++)
System.out.print("*");
System.out.println();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.