循环进阶经典练习题
案例一:输出1-100中被5整除的数,每行输出6个
package loopprc;
public class loopdemo01 {
//输出1-100中被5整除的数,每行输出6个
public static void main(String[] args) {
int j=0;
for (int i = 0; i <=100; i++) {
if (i%5==0){
System.out.print(i+"\t");
j++;
if (j%6==0){
System.out.println();
}
}
}
}
}
案例二:实现一个功能:
- 请录入10个int类型的数字,当你输入的数是666的时候,中断程序
- 判断其中录入的正数的个数并输出
- 判断系统的推出状态:是正常的推出还是被迫退出
Scanner sc = new Scanner(System.in);
int count = 0;
for (int i = 1; i <= 10; i++) {
System.out.println("请输入第一个:"+i+"数字");
int num = sc.nextInt();
if (num==666){
count = 1;
break;
}else {
count = 2;
}
}
if (count==1){
System.out.println("被迫退出");
}else {
System.out.println("正常退出");
}
案例三:输出乘法口诀
public static void chengfa(){
for ( int j =1; j <=9; j++) {
for (int i = 1; i <=j; i++) {
System.out.print(i+" * "+j+" = "+(i*j)+" ");
}
System.out.println();
}
}
第二种方法:
for (int i = 9; i >0; i--){
for ( int j =1; j <=i; j++){
System.out.print(i+" * "+j+" = "+(i*j)+" ");
}
System.out.println();
}
案例四:打印各种形状:
直角三角形:
public static void zhijiaosanjiao1(){
for (int i = 0; i <5; i++) {
for (int j =0; j <i; j++) {
System.out.print(" "+"*");
}
System.out.println(" ");
}
}
public static void zhijiaosanjiao(){
for (int i = 0; i <5; i++) {
for (int j =5; j >i; j--) {
System.out.print(" "+"*");
}
System.out.println(" ");
}
}
等腰三角形:
public static void dengyaosanjiao(){
for (int i = 0; i <5; i++) {
for (int s =5; s >i; s--) {
System.out.print(" ");
}
for (int j =0; j <=i; j++) {
System.out.print("*"+" ");
}
System.out.println(" ");
}
}
等腰倒立三角形
public static void dengyaosanjiao2(){
for (int i = 5; i >=0; i--) {
for (int s =5; s >i; s--) {
System.out.print(" ");
}
for (int j =0; j <=i; j++) {
System.out.print("*"+" ");
}
System.out.println(" ");
}
}
菱形:
public static void lingxing(){
for (int i = 0; i <5; i++) {
for (int s =5; s >i; s--) {
System.out.print(" ");
}
for (int j =0; j <=i; j++) {
System.out.print("*"+" ");
}
System.out.println(" ");
}
for (int i = 5; i >=0; i--) {
for (int s =5; s >i; s--) {
System.out.print(" ");
}
for (int j =0; j <=i; j++) {
System.out.print("*"+" ");
}
System.out.println(" ");
}
空心菱形:
public static void lingxing(){
for (int i = 0; i <5; i++) {
for (int s =5; s >i; s--) {
System.out.print(" ");
}
for (int j =0; j <=i; j++) {
if (j==0||j==i){
System.out.print(" "+"*");
}else {
System.out.print(" "+" ");
}
}
System.out.println(" ");
}
for (int i = 5; i >=0; i--) {
for (int s =5; s >i; s--) {
System.out.print(" ");
}
for (int j =0; j <=i; j++) {
if (j==0||j==i){
System.out.print(" "+"*");
}else {
System.out.print(" "+" ");
}
}
System.out.println(" ");
}
}
输出空心的诀窍就是首尾输出。