[英]java program for print all numbers between -100 to 100 divisible by 3
I tried this many times, but if anyone can help with this solution I would be grateful.我尝试了很多次,但如果有人可以帮助解决这个问题,我将不胜感激。
There is my code, any other versions?有我的代码,还有其他版本吗?
int n=201;
int []array = new int[n];
int j=0;
for (int i = -100;i <= 100; i++)
{
if (i % 3 != 0)
{
array[j] = i;
j++;
}
}
for (int i = 0;i < j;i++)
{
System.out.println(array[i]);
}
There's no need to store the numbers since you want just to print them:无需存储数字,因为您只想打印它们:
for (int i = -100;i <= 100; i++)
if (i % 3 == 0)
System.out.println(i);
If you want to save such values in some collection, have a look at ArrayList<T>
(instead of array):如果您想将这些值保存在某个集合中,请查看
ArrayList<T>
(而不是数组):
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = -100;i <= 100; i++)
if (i % 3 == 0)
list.add(i);
for (int item : list)
System.out.println(item);
java program for print all numbers between -100 to 100 divisible by 3
java 程序用于打印 -100 到 100 之间可被 3 整除的所有数字
You don't need a list or array.您不需要列表或数组。 Just print the numbers.
只需打印数字。
Using the fact that that integer division drops the fraction (100/3 = 33)
and that 33*3 = 99
you can determine the starting and ending number divisible by 3
.利用 integer 除法降低分数
(100/3 = 33)
和33*3 = 99
的事实,您可以确定可被3
整除的起始和结束数字。 Then just increment the counter by 3
.然后只需将计数器增加
3
。
int start = -(100/3)*3;// first number divisible by three greater than -100.
int end = (100/3)*3; // last number divisible by three less than 100.
for(int i = start; i <= end; i+=3) {
System.out.println(i);
}
You can use the Stream API to print all numbers between -100 to 100 divisible by 3.您可以使用 Stream API 打印 -100 到 100 之间可被 3 整除的所有数字。
Like this...像这样...
IntStream.rangeClosed(-100, 100)
.filter((item) -> item % 3 == 0)
.forEach(System.out::println);
The rangeClosed()
method takes both the arguments and generates a Stream containing a sequence of numbers from -100 to 100 both inclusive . rangeClosed()
方法同时采用 arguments 并生成一个 Stream ,其中包含从 -100 到 100 的数字序列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.