求1~100之间不能被3整除的数之和。 代码:
class ForDemo1 {
public static void main ( String[ ] args) {
int sum = 0 ;
for ( int i= 1 ; i<= 100 ; i++ ) {
if ( i% 3 != 0 ) {
sum += i;
}
}
System. out. print ( "1~100之间不能被3整除的数之和为:" + sum + "\n" ) ;
}
}
Break练习:循环录入某学生5门课的成绩并计算平均分,如果某分数录入为负,停止录入并提示录入错误。 代码:
import java. util. Scanner;
class ForDemo2 {
public static void main ( String[ ] args) {
Scanner input = new Scanner ( System. in) ;
for ( int i= 0 ; i< 5 ; i++ ) {
System. out. printf ( "第%d门课程的成绩为:" , i+ 1 ) ;
int score = input. nextInt ( ) ;
if ( score< 0 || score> 100 )
break ;
}
}
}
1~10之间的整数相加,得到累加值大于20的当前数。 代码:
class ForDemo3 {
public static void main ( String[ ] args) {
int sum = 0 ;
for ( int i= 1 ; i<= 20 ; i++ ) {
sum += i;
if ( sum> 20 ) {
System. out. println ( "累加值大于20的当前数: " + i) ;
break ;
}
}
}
}
continue练习:循环录入Java课的学生成绩,统计分数大于等于 80分的学生比例。 代码:
import java. util. Scanner;
class ForDemo4 {
public static void main ( String[ ] args) {
Scanner input = new Scanner ( System. in) ;
double num1 = 0 ;
System. out. print ( "请输入学生人数:" ) ;
double num = input. nextInt ( ) ;
for ( int i= 0 ; i< num ; i++ ) {
System. out. printf ( "学生%d的成绩:" , i+ 1 ) ;
int score = input. nextInt ( ) ;
if ( score>= 80 ) {
num1++ ;
continue ;
}
}
double rate = num1/ num;
System. out. println ( "分数大于等于 80分的学生比例:" + rate* 100 + "%" ) ;
}
}
使用for循环实现输出99乘法表。 代码:
class ForDemo5 {
public static void main ( String[ ] args) {
int i, j;
for ( i= 1 ; i< 10 ; i++ ) {
for ( j= 1 ; j<= i; j++ ) {
System. out. print ( j + "*" + i + "=" + i* j + "\t" ) ;
if ( j== i)
System. out. println ( ) ;
}
}
}
}
使用for循环实现将1~100中所有的偶数进行累加并输出累加结果。 代码:
class ForDemo6 {
public static void main ( String[ ] args) {
int sum = 0 ;
for ( int i= 1 ; i<= 100 ; i++ ) {
if ( i% 2 == 0 ) {
sum += i;
}
}
System. out. println ( "偶数累加结果为:" + sum) ;
}
}
分别使用三种循环结构(for, while, do-while)找出1~100中所有的质数(只能被1和自身整除的数)。 代码:
class ForDemo7 {
public static void main ( String[ ] args) {
int sum;
System. out. print ( "1~100中所有的质数为:" ) ;
for ( int i= 1 ; i<= 100 ; i++ ) {
sum = 0 ;
for ( int j= 1 ; j<= i; j++ ) {
if ( i% j == 0 )
sum++ ;
}
if ( sum == 2 )
System. out. print ( i + "," ) ;
}
System. out. println ( ) ;
}
}
使用for循环打印3种三角形。 代码:
class ForDemo8 {
public static void main ( String[ ] args) {
System. out. println ( "打印直边靠左三角" ) ;
for ( int i= 0 ; i< 5 ; i++ ) {
for ( int j= 0 ; j<= i; j++ ) {
System. out. print ( "*" ) ;
}
System. out. println ( ) ;
}
System. out. println ( "打印正等腰三角" ) ;
for ( int i= 0 ; i< 5 ; i++ ) {
for ( int j= 4 ; j> i; j-- ) {
System. out. print ( " " ) ;
}
for ( int k= 0 ; k<= i; k++ ) {
System. out. print ( "*" ) ;
}
if ( i>= 1 ) {
for ( int n= 0 ; n< i; n++ ) {
System. out. print ( "*" ) ;
}
}
System. out. println ( ) ;
}
System. out. println ( "打印直边靠右三角" ) ;
for ( int i= 0 ; i< 5 ; i++ ) {
for ( int j= 4 ; j> i; j-- ) {
System. out. print ( " " ) ;
}
for ( int k= 0 ; k<= i; k++ ) {
System. out. print ( "*" ) ;
}
System. out. println ( ) ;
}
}
}