This article is a mirror article of machine translation, please click here to jump to the original article.

View: 18002|Reply: 0

[Source] Java input lines print diamonds

[Copy link]
Posted on 10/15/2014 7:41:37 AM | | |
  1. package cn.jbit.nestedloops;
  2. import java.util.Scanner;
  3. /**
  4. * 输入行数打印菱形
  5. */
  6. public class Diamond {
  7.         public static void main(String[] args) {
  8.                 int rows = 0;        //菱形的行数
  9.                 Scanner input = new Scanner(System.in);
  10.                 System.out.print("请输入菱形行数:");
  11.                 rows = input.nextInt();

  12.                 while(rows%2 == 0){
  13.                         System.out.print("请输入奇数:");
  14.                         rows = input.nextInt();
  15.                 }

  16.                 int n = (rows+1)/2;
  17.                 //打印菱形的上半部分
  18.                 for(int i = 1; i <= n; i++){//外层循环变量i控制行数
  19.                         for(int j = 1; j <= n-i; j++){//内层循环变量j控制该行空格数
  20.                                 System.out.print(" ");
  21.                         }
  22.                         for(int k = 1; k <= 2*i-1; k++){//内层循环变量k控制该行*号数
  23.                                 System.out.print("*");
  24.                         }
  25.                         System.out.print("\n");
  26.                 }
  27.                 //打印菱形的下半部分
  28.                 for(int i = n-1; i >= 1; i--){
  29.                         for(int j = 1; j <= n-i; j++){
  30.                                 System.out.print(" ");
  31.                         }
  32.                         for(int k = 1; k <= 2*i-1; k++){
  33.                                 System.out.print("*");
  34.                         }
  35.                         System.out.print("\n");
  36.                 }
  37.         }
  38. }
Copy code
Print the diamond code




Previous:Look at the picture and guess the word, and guess it out and you are powerful!
Next:Java array sum code
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com