Output a line
demand
- Use loops to complete
- Receive an integer from the keyboard
- Suppose the user enters a 6
- Then output 6 star flowers in one line
- 6
solve
- Code
import java.util.Scanner;
public class ppp {
public static void main(String[] args) {
// 固定的获得Scanner工具的写法
// 类型名称 变量名 = 值;
Scanner ipt = new Scanner(System.in);
// 使用工具的功能,得到一个整数
System.out.println("请输入内容:");
int a = ipt.nextInt();
System.out.println("从键盘接收到了一个整数,值为" + a);
for (int i = 0; i < a; i++) {
System.out.print("*");
}
}
}
Output multiple lines
demand
- Receive an integer from the keyboard
- If the user enters 2
- Then output two lines of content
- Each line of content is *****
-a line of content composed of five stars
solve
- Code
import java.util.Scanner;
public class ppp {
public static void main(String[] args) {
// 获得键盘输入的工具
Scanner ipt = new Scanner(System.in);
// 使用工具的方法
System.out.println("请问需要打印几行:");
int num = ipt.nextInt();
for (int i = 0; i < num; i++) {
// 需要重复做的内容
System.out.println("*****");
}
}
}
Output a rectangle
demand
- Receive an integer from the keyboard
- If the user enters 3
- Then output three lines of content
- Each row is composed of three*
solve
-
Code
import java.util.Scanner; public class ppp { public static void main(String[] args) { // 代码简化,输出矩形 int num = 4; for (int j = 0; j < num; j++) { // 输出一行星花,由三个符号组号 for (int i = 0; i < num; i++) { System.out.print("*"); } System.out.println(); } } }
Output a triangle
demand
- Receive an integer from the keyboard
- If the user enters 4
- Output four rows of triangles
- One symbol on the first line
- Two symbols on the second line
- 。。。。
solve
-
Code
import java.util.Scanner; public class ppp { public static void main(String[] args) { // 用户输入数字5,打印五行的三角形 int num = 6; // 行循环 for(int j=1;j<=num;j++){ for (int i = 0; i < j; i++) { System.out.print("*"); } System.out.println(); } } }
Output ninety-nine multiplication table
demand
- Output ninety-nine multiplication table
solve
- Code
import java.util.Scanner;
public class ppp {
public static void main(String[] args) {
// 行循环,一共需要输出九行,所以从1开始一直到9
for (int hang=1;hang<=9;hang++){
// 每一行的内容输出循环,当前行需要输出几次内容,由当前的hang行号决定
for(int lie=1;lie<=hang;lie++){
System.out.print(lie+"x"+hang+"="+hang*lie+"\t");
// System.out.print("*");
}
System.out.println();
}
}
}