for 循环的进阶用法
求100以内奇数偶数和
public class forDemo2 {
public static void main(String[] args) {
int oddSum = 0;
int eveSum = 0;
for (int i = 0; i <= 100; i++) {
if (i % 2 == 0) {
oddSum += i;
} else {
eveSum += i;
}
}
System.out.println("奇数的和为:"+oddSum);
System.out.println("偶数的和为:"+eveSum);
System.out.println("总和为:"+oddSum+eveSum);
}
}
用while或for循环输出1-1000之间能被5整除的数,并且每行输出3个
public class forDemo3 {
public static void main(String[] args) {
for (int i = 0; i <=1000; i++) {
if(i%5==0)
{
System.out.print(i+"\t");
}
if(i%15==0){
System.out.println();
}
}
System.out.println("============================");
int a=0;
while (a<=1000){
a++;
if(a%5==0){
System.out.print(a+"\t");
}
if(a%15==0){
System.out.println();
}
}
}
}
打印九九乘法表
public class forDemo4 {
public static void main(String[] args) {
for (int i = 1; i <=9; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(i+"*"+j+"="+(i*j)+"\t");
}
System.out.println();
}
}
}
遍历数组元素
public class forDemo5 {
public static void main(String[] args) {
int[] number={1,2,3,4,5};
for (int x:number) {
System.out.println(x);
}
}
}
打印三角形
public class LabeDemo1 {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 5; j >=i ; j--) {
System.out.print(" ");
}
for(int j=1;j<=i;j++){
System.out.print("*");
}
for(int j =1;j<i;j++){
System.out.print("*");
}
System.out.println();
}
}
}
打印爱心
public class heart {
public static void main(String[] args) {
int i, j;
for(i = 0; i < 3; i++){
for (j = 5; j > 2 * i; j--){
System.out.print(" ");
}
for (j = 0; j < 4 * i + 5; j++){
System.out.print("*");
}
for (j = 0; j < 9 - 4 * i; j++){
System.out.print(" ");
}
for (j = 0; j < 4 * i + 5; j++){
System.out.print("*");
}
System.out.println();
}
for (i = 0; i < 3; i++){
for (j = 0; j < 29; j++){
System.out.print("*");
}
System.out.println();
}
for (i = 0; i < 7; i++) {
for (j = 1; j <= 2 * i +1; j++){
System.out.print(" ");
}
for (j = 27; j > 4 * i; j--){
System.out.print("*");
}
System.out.println();
}
for (i = 0; i < 14; i++) {
System.out.print(" ");
}
System.out.println("*");
}
}
输出结果