JAVA学习(小白向)—基本for语句—02021-05-25
1.累加和有步长的累加
package a6;
/**
*
* @author hengyuzuo
*
*/
public class forStatement {
/**
* **************************
* The entrance of the program.
* @param args
* **************************
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
forStatementTest();
}// Of main
/**
* **************************
* The Method
* **************************
*/
public static void forStatementTest() {
// TODO Auto-generated method stub
int tempN = 10;
System.out.println("1 add to " + tempN + " is " + added(tempN));
tempN =0;
System.out.println("1 add to " + tempN + " is " + added(tempN));
int tempStepLength = 1;
tempN = 10;
System.out.println("1 add to " + tempN + " with step length " + tempStepLength + " is: " + addedWithStep(tempN, tempStepLength));
tempStepLength = 20;
System.out.println("1 add to " + tempN + " with step length " + tempStepLength + " is: " + addedWithStep(tempN, tempStepLength));
}// Of forStatementTest
/**
* ***************************
* add form 1 to N
* @param paraN
* @return the sum
* ***************************
*/
public static int added(int paraN) {
// TODO Auto-generated method stub
int resultSum =0;
for (int i = 1; i <= paraN; i++) {
resultSum += i;
}// Of for
return resultSum;
}// Of added
/**
* ****************************
* add with step
* ****************************
*/
public static int addedWithStep(int paraN, int paraStepLength) {
// TODO Auto-generated method stub
int resultSum = 0;
for (int i = 1; i <= paraN; i += paraStepLength) {
resultSum += i;
}// Of for
return resultSum;
}// Of addedWithStep
}// Of class
运行结果:
1 add to 10 is 55
1 add to 0 is 0
1 add to 10 with step length 1 is: 55
1 add to 10 with step length 20 is: 1
for语言语法:
for(初始化; 布尔表达式; 更新) {
//代码语句
}
2.求出1-100的偶数和
package test1;
/**
*
* @author hengyuzuo
*
*/
public class TestDemo2 {
public static void main(String[] args) {
int sum = 0;
for( int i = 1; i <= 100; i++) {
if(i % 2 == 0) {
sum += i;
}// Of if
}// Of for
System.out.println("偶数和为:" + sum);
}// Of main
}// Of TestDemo2 class
运行结果
偶数和为:2550