1.累加
获取1-100的和,并打印
/*
获取1-100的和,并打印
*/
class Demo
{
public static void main(String[] args)
{
int sum = 0;
for(int i = 1; i <= 100; i++)
sum += i;
System.out.println("1-100的和为:" + sum);
//System.out.println("Hello World!");
}
}
2.计数器
获取1-100之间7的倍数的个数,并打印
/*
获取1-100之间7的倍数的个数,并打印
*/
class Demo
{
public static void main(String[] args)
{
int count = 0;
for(int i = 1; i <= 100; i++)
{
if(0 == i%7)
count++;
}
System.out.println("1-100之间7的倍数的个数为:" + count);
//System.out.println("Hello World!");
}
}
3.for嵌套循环
①打印下面的图形
*
**
***
****
*****
/*
打印下面的图形
*
**
***
****
*****
*/
class Demo
{
public static void main(String[] args)
{
//图形5行,5列
for(int i = 0; i < 5; i++) //第一层实现5行
{
for(int j = 0; j <= i; j++) //第二层实现*的数量
{
System.out.print("*");
}
System.out.println(); //控制换行
}
//System.out.println("Hello World!");
}
}
②打印九九乘法表
格式:
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
/*
打印九九乘法表
格式:
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
*/
class Demo
{
public static void main(String[] args)
{
//打印end行
int end = 9;
for(int i = 1; i <= end; i++) //第一层
{
for(int j = 1; j <= i; j++) //第二层
{
//System.out.print(j + "*" + i + "=" + i*j + " ");
System.out.print(j + "*" + i + "=" + i*j + "\t"); //制表符比空格稍微美观
}
System.out.println(); //控制换行
}
//System.out.println("Hello World!");
}
}
本文深入探讨了Java编程的基础知识及应用实例,包括累加求和、计数器使用、for循环嵌套等核心概念,并通过代码示例展示了如何在实际场景中应用这些技巧。
992

被折叠的 条评论
为什么被折叠?



