临渊羡鱼,不如退而结网

输入输出

输入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.util.Scanner;

public class InputTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// get first input
System.out.println("What is your name?");
String name = in.nextLine();

// get second input
System.out.println("How old are you?");
int age = in.nextInt();

// display output on console
System.out.println("Hello, " + name + ". Next yoar, you'll be " + (age + 1));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.base.learn;

import java.util.Scanner;

public class ScannerTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("请输入你的网名:");
String name = scanner.next();

System.out.println("请输入你的年龄:");
int age = scanner.nextInt();

System.out.println("请输入你的体重:");
double weight = scanner.nextDouble();

System.out.println("你是否单身(true / false):");
boolean isSingle = scanner.nextBoolean();

System.out.println("请输入的你的性别:");
char gender = scanner.next().charAt(0);

System.out.println("你的基本信息如下:");
System.out.println("网名:" + name + "\n年龄:" + age + "\n体重:" + weight + "\n单身:" + isSingle + "\n性别:" + gender);

scanner.close();
}
}

输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class OutputTest {
public static void main(String[] args) {
System.out.print("A,");
System.out.print("B,");
System.out.print("C,");
System.out.println();
System.out.println("END");
// A,B,C,
// END
double d = 1230000000;
System.out.println(d); // 1.23E9

double d1 = 3.1415926;
System.out.printf("%.2f\n", d1); // 3.14
System.out.printf("%.3f\n", d1); // 3.142

int n = 12345000;
// 把一个整数格式化成十六进制,并用0补足8位
System.out.printf("n=%d, hex=%08x", n, n); // n=12345000, hex=00bc5ea8
}
}

Java的格式化功能提供了多种占位符,可以把各种数据类型“格式化”成指定的字符串
注意,由于%表示占位符,因此,连续两个%%表示一个%字符本身

占位符说明
%d格式化输出整数
%x格式化输出十六进制整数
%f格式化输出浮点数
%e格式化输出科学计数法表示的浮点数
%s格式化字符串

随机数

如何产生一个指定范围的随机整数?

Math 类的 random() 的调用,会返回一个 [0,1) 范围的一个 double 型值

  • Math.random() * 100 —> [0,100)
  • (int)(Math.random() * 100) —> [0,99]
  • (int)(Math.random() * 100) + 5 —-> [5,104]

如何获取 [a,b] 范围内的随机整数呢?(int)(Math.random() * (b - a + 1)) + a

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.base.learn;

public class MathRandomTest {
public static void main(String[] args) {
double d1 = Math.random();
System.out.println(d1);

// 获取一个[0, 100]范围的随机整数
int num1 = (int) (Math.random() * 101); // [0.0, 1.0) --> [0.0, 101.0) --> [0, 100]

// 获取一个[1, 100]范围的随机整数
int num2 = (int) (Math.random() * 100) + 1; // [0.0, 1.0) --> [0.0, 100.0) --> [0, 99] --> [1, 100]

// 获取一个 [a, b] 范围的随机整数,举例 [4, 15]
// (int)(Math.random()*(b - a + 1)) + a

int num3 = (int) (Math.random() * (15 - 4 + 1)) + 4;
System.out.println(num3);
}
}

件语句

if-else

1
2
3
4
5
6
7
8
9
10
11
class IfTest {
public static void main(String[] args){
int n = 70;
if (n >= 60) {
System.out.println("及格了");
} else {
System.out.println("END");
}
}
}
// 及格了

if 语句只有一行语句时,可以省略花括号 {}、但是不推荐忽略花括号的这种写法

1
2
3
4
5
6
7
8
9
10
class IfTest {
public static void main(String[] args){
int n = 50;
if (n >= 60)
System.out.println("及格了");
else
System.out.println("END");
}
}
// END

多个if ... esle if ...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class IfTest1 {
public static void main(String[] args) {
int n = 70;
if (n > 90) {
System.out.println("优秀");
} else if (n >= 60) {
System.out.println("及格");
} else {
System.out.println("挂科");
}
System.out.println("END");
}
}
// 及格
// END

if 条件语句从上到下执行

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Main {
public static void main(String[] args) {
int n = 100;
if (n >= 60) {
System.out.println("及格了");
} else if (n >= 90) {
System.out.println("优秀");
} else {
System.out.println("挂科了");
}
}
}
// 及格了

浮点数在计算机中常常无法精确计算,并且计算可能出现误差,因此判断浮点数相等用 == 判断不靠谱

1
2
3
4
5
6
7
8
9
10
11
12
class IfTest2 {
public static void main(String[] args) {
double x = 1 - 9.0 / 10;
System.out.println(x); // 0.09999999999999998
if (x == 0.1) {
System.out.println("x is 0.1");
} else {
System.out.println("x is not 0.1");
}
}
}
// x is not 0.1

正确的方法是利用差值小于某个临界值来判断

1
2
3
4
5
6
7
8
9
10
11
12
class IfTest2 {
public static void main(String[] args) {
double x = 1 - 9.0 / 10;
System.out.println(x); // 0.09999999999999998
if (Math.abs(x - 0.1) < 0.00001) {
System.out.println("x is 0.1");
} else {
System.out.println("x is not 0.1");
}
}
}
// x is 0.1

在 Java 中,判断类型的变量值是否相等,可以使用 == 运算符。但是,判断引用类型的变量是否相等, == 表示”引用的是否相等”,或者说,是否指向同一个对象

例如,下面的两个String类型,它们内容是相同的,但是分别指向不同的对象,用 == 来判断,结果为 false

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Main {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "HELLO".toLowerCase();
System.out.println(s1); // hello
System.out.println(s2); // hello
if (s1 == s2) {
System.out.println("s1 = s2");
} else {
System.out.println("s1 != s2");
}
}
}
// s1 != s2

要判断引用类型的值是否相等,必须使用 equals() 方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Main {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "HELLO".toLowerCase();
System.out.println(s1); // hello
System.out.println(s2); // hello
if (s1.equals(s2)) {
System.out.println("s1 = s2");
} else {
System.out.println("s1 != s2");
}
}
}
// s1 = s2

要避免 NullPointerException 错误,可以利用短路运算符 &&

1
2
3
4
5
6
7
8
public class Main {
public static void main(String[] args) {
String s1 = null;
if (s1 != null && s1.equals("hello")) {
System.out.println("hello");
}
}
}

案例

心率检测,成年人心率的正常范围是每分钟60-100次。体检时,如果心率不在此范围内,则提示需要做进一步的检查

1
2
3
4
5
6
7
8
9
10
public class IfElseTest1 {
public static void main(String[] args) {
int heartBeats = 110;

if (heartBeats < 60 || heartBeats > 100) {
System.out.println("你需要进一步检查");
}
System.out.println("体检结束");
}
}

案例

定义一个整数,判定是偶数还是奇数

1
2
3
4
5
6
7
8
9
10
public class IfElesTest2 {
public static void main(String[] args) {
int a = 11;
if (a % 2 == 0) {
System.out.println(a + "是偶数");
} else {
System.out.println(a + "是奇数");
}
}
}

案例

考试成绩判定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/*
岳小鹏参加Java考试,他和父亲岳不群达成承诺:
如果:
成绩为100分时,奖励一辆跑车;
成绩为(80,99]时,奖励一辆山地自行车;
当成绩为[60,80]时,奖励环球影城一日游;
其它时,胖揍一顿。
说明:默认成绩是在[0,100]范围内
*/
public class IfElesTest3 {
public static void main(String[] args) {
int score = 55; // 成绩

// 默认成绩范围为[0,100]
if (score == 100) {
System.out.println("奖励一辆跑车");
} else if (score > 80) {
System.out.println("奖励一辆山地车");
} else if (score > 60) {
System.out.println("奖励环球影城玩一日游");
} else {
System.out.println("胖揍一顿");
}
}
}

案例

三个数大小比较

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class IfElesTest4 {
public static void main(String[] args) {
// 声明num1、num2、num3 三个变量并赋值
int num1 = 22, num2 = 32, num3 = 12;

if (num1 >= num2){
if (num3 >= num1)
System.out.println(num2 + "-" + num1 + "-" + num3);
else if (num3 <= num2)
System.out.println(num3 + "-" + num2 + "-" + num1);
else
System.out.println(num2 + "-" + num3 + "-" + num3);
}else { // num1 < num2
if (num3 >= num2)
System.out.println(num1 + "-" + num2 + "-" + num3);
else if (num3 <= num1)
System.out.println(num3 + "-" + num1 + "-" + num2);
else
System.out.println(num1 + "-" + num3 + "-" + num2);
}
}
}

switch case

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class SwitchTest {
public static void main(String[] args) {
int option = 2;
switch (option) {
case 1:
System.out.println("Selected 1");
break;
case 2:
System.out.println("Selected 2");
break;
case 3:
System.out.println("Selected 3");
break;
default:
System.out.println("Selected 4");
break;
}
}
}

switch 语句还可以匹配字符串。字符串匹配时,是比较”内容相等”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class SwitchTest {
public static void main(String[] args) {
String option = "Java";
switch (option) {
case "Python":
System.out.println("Python");
break;
case "C":
System.out.println("C");
break;
case "Java":
System.out.println("Java");
break;
default:
System.out.println("Go");
break;
}
}
}

案例

使用 switch-case 实现:对学生成绩大于 60 分的,输出“合格”。低于 60 分的,输出“不合格”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.base.learn;

import java.util.Scanner;

/**
* 使用switch-case实现:对学生成绩大于60分的,输出“合格”。低于60分的,输出“不合格”
*
*/
public class SwitchCaseTest3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入成绩:");
int score = scanner.nextInt();

switch (score / 60) {
case 0:
System.out.println("不及格");
break;
case 1:
System.out.println("及格了");
break;
default:
System.out.println("输入的成绩有误");
break;
}
scanner.close();
}
}

利用 switch 的穿透性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.base.learn;

import java.util.Scanner;

/**
* 从键盘上输入2023年的“month”和“day”,要求通过程序输出输入的日期为2023年的第几天。
* 利用 switch 的穿透性,更简单点
*
*/
public class SwitchCaseTest4 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);

System.out.println("请输入2023年的month:");
int month = scan.nextInt();

System.out.println("请输入2023年的day:");
int day = scan.nextInt();

//这里就不针对month和day进行合法性的判断了,以后可以使用正则表达式进行校验。
int sumDays = 0;//记录总天数

//写法2:推荐
switch(month){
case 12:
sumDays += 30;//这个30是代表11月份的满月天数
case 11:
sumDays += 31;//这个31是代表10月份的满月天数
case 10:
sumDays += 30;//这个30是代表9月份的满月天数
case 9:
sumDays += 31;//这个31是代表8月份的满月天数
case 8:
sumDays += 31;//这个31是代表7月份的满月天数
case 7:
sumDays += 30;//这个30是代表6月份的满月天数
case 6:
sumDays += 31;//这个31是代表5月份的满月天数
case 5:
sumDays += 30;//这个30是代表4月份的满月天数
case 4:
sumDays += 31;//这个31是代表3月份的满月天数
case 3:
sumDays += 28;//这个28是代表2月份的满月天数
case 2:
sumDays += 31;//这个31是代表1月份的满月天数
case 1:
sumDays += day;//这个day是代表当月的第几天
}

System.out.println(month + "月" + day + "日是2023年的第" + sumDays + "天");
//关闭资源
scan.close();
}
}

拓展

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.base.learn;

import java.util.Scanner;

/*
从键盘分别输入年、月、日,判断这一天是当年的第几天

注:判断一年是否是闰年的标准:
1)可以被4整除,但不可被100整除

2)可以被400整除

例如:1900,2200等能被4整除,但同时能被100整除,但不能被400整除,不是闰年
*/
public class SwitchCaseTest5 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入year:");
int year = scanner.nextInt();

System.out.println("请输入month:");
int month = scanner.nextInt();

System.out.println("请输入day:");
int day = scanner.nextInt();

//声明一个变量days,用来存储总天数
int sumDays = 0;

//累加[1,month-1]个月满月天数
switch (month) {
case 12:
sumDays += 30;//这个30是代表11月份的满月天数
case 11:
sumDays += 31;//这个31是代表10月的满月天数
case 10:
sumDays += 30;//9月
case 9:
sumDays += 31;//8月
case 8:
sumDays += 31;//7月
case 7:
sumDays += 30;//6月
case 6:
sumDays += 31;//5月
case 5:
sumDays += 30;//4月
case 4:
sumDays += 31;//3月
case 3:
sumDays += 28;//2月
//在这里考虑是否可能是29天
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
sumDays++;//多加1天
}
case 2:
sumDays += 31;//1月
case 1:
sumDays += day;//第month月的day天
}
//输出结果
System.out.println(year + "年" + month + "月" + day + "日是这一年的第" + sumDays + "天");
scanner.close();
}
}

案例

指定一个月份,输出该月份对应的季节

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.base.learn;

import java.util.Scanner;

/*
* 需求:指定一个月份,输出该月份对应的季节。一年有四季:
* 3,4,5 春季
* 6,7,8 夏季
* 9,10,11 秋季
* 12,1,2 冬季
*/
public class SwitchCaseTest33 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入月份:");
int month = input.nextInt();

switch (month) {
case 1:
case 2:
case 12:
System.out.println("冬季");
break;
case 3:
case 4:
case 5:
System.out.println("春季");
break;
case 6:
case 7:
case 8:
System.out.println("夏季");
break;
case 9:
case 10:
case 11:
System.out.println("秋季");
break;
default:
System.out.println("你输入得月份有误");
break;
}
input.close();
}
}

if-else与switch-case比较

  • 结论:凡是使用switch-case的结构都可以转换为if-else结构。反之,不成立。
  • 开发经验:如果既可以使用switch-case,又可以使用if-else,建议使用switch-case。因为效率稍高。
  • 细节对比:
    • if-else语句优势
      • if语句的条件是一个布尔类型值,if条件表达式为true则进入分支,可以用于范围的判断,也可以用于等值的判断,使用范围更广
      • switch语句的条件是一个常量值(byte,short,int,char,枚举,String),只能判断某个变量或表达式的结果是否等于某个常量值,使用场景较狭窄
    • switch语句优势
      • 当条件是判断某个变量或表达式是否等于某个固定的常量值时,使用if和switch都可以,习惯上使用switch更多。因为效率稍高。当条件是区间范围的判断时,只能使用if语句。
      • 使用switch可以利用穿透性,同时执行多个分支,而if…else没有穿透性。

循环结构

while 循环

1
2
3
4
5
6
7
8
9
10
11
class WhlieTest {
public static void main(String[] args) {
int sum = 0;
int x = 1;
while(x <= 100) {
sum += x;
x++;
}
System.out.println(sum); // 5050
}
}

do-while 循环

do…while 循环和 while 循环相似,不同的是,do…while 循环至少会执行一次

1
2
3
4
5
6
7
8
9
10
11
class WhlieTest1 {
public static void main(String[] args) {
int sum = 0;
int x = 10;
do {
sum += x;
x++;
}while(x < 10);
System.out.print(sum); // 10
}
}

for 循环

1
2
3
4
5
6
7
8
9
class ForTest {
public static void main(String[] args) {
int sum = 0;
for(int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println(sum); // 5050
}
}

对整形数组的所有元素求和,可以使用 for 循环实现

1
2
3
4
5
6
7
8
9
10
11
class ForTest1 {
public static void main(String[] args) {
int sum = 0;
int[] ns = {1, 4, 6, 8, 11, 23, 35};
for (int i = 0; i < ns.length; i++) {
System.out.println(i + "," + ns[i]);
sum += ns[i];
}
System.out.println(sum); // 88
}
}

灵活使用 for 循环,for 循环还可以缺少初始化语句,循环条件和每次迭代更新语句,如下
通常不建议这样写,某些情况下,是可以省略 for 循环的某些语句

1
2
3
// 不设置结束条件
for (int i=0; ; i++){
}
1
2
3
// 不设置结束条件和更新语句
for (int i=0; ;){
}
1
2
3
// 什么都不设置
for (; ;){
}

for each 循环

for 循环经常用来遍历数组,因为通过计数器可以根据索引来访问数组的每个元素,但是,很多时候,我们实际上真正想要访问的数组每个元素的值,Java 还提供了另一种 for each 循环,它可以更简单的遍历数组。

1
2
3
4
5
6
7
8
class ForTest2 {
public static void main(String[] args) {
int[] ns = {1, 4, 6, 8, 12, 29, 18};
for (int i : ns) {
System.out.println(i);
}
}
}

break 关键字

break 主要用在循环语句或者 switch 语句中,用来跳出整个语句块

1
2
3
4
5
6
7
8
9
10
11
12
class BreakTest{
public static void main(String[] args) {
int sum = 0;
for (int i = 1; ; i++){
sum += i;
if (i == 100){
break;
}
}
System.out.println(sum); // 5050
}
}

break 语句通常都是配合 if 语句使用,特别注意,break 语句总是能跳出自己所在的那层循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class BreakTest1 {
public static void main(String[] args) {
for (int i=1; i<=10; i++) {
System.out.println("i = " + i);
for (int j=1; j<=10; j++) {
System.out.println("j = " + j);
if (j >= i){
break;
}
}
System.out.println("---------");
}
}
}

continue 关键字

break 会跳出当前循环,也就是整个循环都不会执行了。而 continue 则是提前结束本次循环,直接继续执行下次循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class ContinueTest {
public static void main(String[] args) {
int[] ns = {1, 4, 6, 8};
for (int x : ns) {
if (x == 6) {
continue;
}
System.out.println(x);
}
}
}
// 1
// 4
// 8

使用 label 标签

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Java 中的标签是为循环设计的,是为了在多重循环中方便的使用 break 和 coutinue
*
**/
class BreakTest1 {
public static void main(String[] args) {
inner:
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
if(i == 1 && j == 1) break inner;
System.out.println(i + ", " + j);
}
}
System.out.println("结尾");
}
}

/*
0, 0
0, 1
0, 2
1, 0
结尾
*/

练习题

最大公约数,最小公倍数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* 求两个正整数的最大公约数和最小公倍数
*/
import java.util.Scanner;
class ForTest{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("请输入第一个正整数");
int m = scan.nextInt();

System.out.println("请输入第二个正整数");
int n = scan.nextInt();

// 获取最大公约数
int min = (m <= n)? m : n;
for(int i=min; i >= 1; i--){
if(m % i ==0 && n % i == 0){
System.out.println("最大公约数为:" + i);
break;
}
}

// 获取最小公倍数
int max = (m >= n)? m : n;
for(int i = max; i <= m * n; i++){
if(i % m == 0 && i % n == 0){
System.out.println("最小公倍数为:" + i);
break;
}
}
}
}

水仙花

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* 水仙花
*
**/
class ForTest2{
public static void main(String[] args){
for(int i = 100; i <= 999; i++){
int a = i / 100;
int b = i % 100 / 10;
int c = i % 10;
if(a*a*a + b*b*b + c*c*c == i){
System.out.println("此数值满足水仙花:" + i);
}
}
}
}

计算100内所有偶数的和

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 使用 do-while 遍历100以内所有的偶数,并计算所有偶数的和和偶数的个数
*
**/

class DoWhlieTest{
public static void main(String[] args){
int number = 1;
int sum = 0;
int count = 0;
do{
if(number % 2 == 0){
System.out.println(number);
sum += number;
count++;
}
number++;
}while(number <= 100);
System.out.println("总和为:" + sum);
System.out.println("个数为:" + count);
}
}

不确定整数的个数统计

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 从键盘输入个数不确定的整数,并判断读入的正数和负数的个数,输入为0时结束程序
*
**/
import java.util.Scanner;
class XunTest{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int positive_int = 0;
int negative_int = 0;
while(true){
int number = scan.nextInt();
if(number > 0){
positive_int++;
}else if(number < 0){
negative_int++;
}else{
break;
}
}
System.out.println("正整数的个数:" + positive_int);
System.out.println("负整数的个数:" + negative_int);
}
}

循环嵌套例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* 常见循环嵌套的例子
*
**/
class ForForTest{
public static void main(String[] args){
/*
**********
**********
**********
**********
**********
*/
for(int i = 1; i < 6; i++){
for(int j = 1; j <= 10; j++){
System.out.print("*");
}
System.out.println();
}

/*
*
**
***
****
*****
******
*/
for(int i = 1; i <= 6; i++){
for(int j = 1; j <= i; j++){
System.out.print("*");
}
System.out.println();
}

/*
*****
****
***
**
*
*/
for(int i = 1; i <= 6; i++){
for(int j = 1; j <= 6-i; j++){
System.out.print("*");
}
System.out.println();
}

// 乘法口诀表
/*
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
*/
for(int i = 1; i <= 9; i++){
for(int j = 1; j <= i; j++){
System.out.print(j + "*" + i + "=" + j*i + "\t");
}
System.out.println();
}
}
}

质数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* 100以内的所有质数的输出
* 质数:只能被1和它本身整除的自然数
*
**/
class PrimeNumberTest{
public static void main(String[] args){
boolean isFlag = true;
for(int i = 2; i <= 100; i++){
for(int j = 2; j < i; j++){
if(i % j == 0){
isFlag = false;
}
}
if(isFlag == true){
System.out.println(i);
}
isFlag = true;
}
}
}

质数查找优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* 100以内的所有质数的输出
* 质数:只能被1和它本身整除的自然数,优化版本
*
**/
class PrimeNumberTest{
public static void main(String[] args){
boolean isFlag = true;
int count = 0;
long start = System.currentTimeMillis();
for(int i = 2; i <= 100000; i++){
for(int j = 2; j <= Math.sqrt(i); j++){
if(i % j == 0){
isFlag = false;
break;
}
}
if(isFlag == true){
//System.out.println(i);
count++;
}
isFlag = true;
}
long end = System.currentTimeMillis();
System.out.println("质数的个数为:" + count);
System.out.println("所花费的时间为:" + (end - start));
}
}

最后的总结

家庭收支记账练习 Demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* 简单的家庭收支练习,主要针对之前学习的知识点进行回顾
*
**/
public class FamilyAccount{
public static void main(String[] args){
String details = "收支\t账户金额\t收支金额\t说 明\n";
int balance = 10000;
boolean isFlag = true;

do{
System.out.println("\n-----------------家庭收支记账软件-----------------\n");
System.out.println(" 1 收支明细");
System.out.println(" 2 登记收入");
System.out.println(" 3 登记支出");
System.out.println(" 4 退 出\n");
System.out.print(" 请选择< 1~4 > ");

char menu = Utility.readMenuSelection();
switch(menu){
case '1':
System.out.println("-----------------当前收支明细记录-----------------");
System.out.println(details);
System.out.println("--------------------------------------------------");
break;

case '2':
System.out.print("本次收入金额:");
int money1 = Utility.readNumber();
System.out.print("本次收入说明:");
String info1 = Utility.readString();
balance += money1;
details += "收入\t" + balance + "\t\t" + money1 + "\t\t" + info1 + "\n";
System.out.println("---------------------登记完成---------------------");
break;

case '3':
System.out.print("本次支出金额:");
int money2 = Utility.readNumber();
if(balance > money2){
balance -= money2;
}else{
System.out.println("支出超出账户可用额度!!!");
break;
}
System.out.print("本次支出说明:");
String info2 = Utility.readString();
details += "支出\t" + balance + "\t\t" + money2 + "\t\t" + info2 + "\n";
System.out.println("---------------------登记完成---------------------");
break;

case '4':
System.out.print("请确认是否退出(Y/N): ");
char exit = Utility.readConfirmSelection();
if(exit == 'Y') isFlag = false;
break;
}
}while(isFlag);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* Utility工具类:
* 将不同的功能封装为方法,就是可以直接通过调用方法使用它的功能,而无需考虑具体的功能实现细节。
*/
import java.util.Scanner;
public class Utility {
private static Scanner scanner = new Scanner(System.in);
/**
用于界面菜单的选择。该方法读取键盘,如果用户键入’1’-’4’中的任意字符,则方法返回。返回值为用户键入字符。
*/
public static char readMenuSelection() {
char c;
for (; ; ) {
String str = readKeyBoard(1);
c = str.charAt(0);
if (c != '1' && c != '2' && c != '3' && c != '4') {
System.out.print("选择错误,请重新输入:");
} else break;
}
return c;
}
/**
用于收入和支出金额的输入。该方法从键盘读取一个不超过4位长度的整数,并将其作为方法的返回值。
*/
public static int readNumber() {
int n;
for (; ; ) {
String str = readKeyBoard(4);
try {
n = Integer.parseInt(str);
break;
} catch (NumberFormatException e) {
System.out.print("数字输入错误,请重新输入:");
}
}
return n;
}
/**
用于收入和支出说明的输入。该方法从键盘读取一个不超过8位长度的字符串,并将其作为方法的返回值。
*/
public static String readString() {
String str = readKeyBoard(8);
return str;
}

/**
用于确认选择的输入。该方法从键盘读取‘Y’或’N’,并将其作为方法的返回值。
*/
public static char readConfirmSelection() {
char c;
for (; ; ) {
String str = readKeyBoard(1).toUpperCase();
c = str.charAt(0);
if (c == 'Y' || c == 'N') {
break;
} else {
System.out.print("选择错误,请重新输入:");
}
}
return c;
}

private static String readKeyBoard(int limit) {
String line = "";

while (scanner.hasNext()) {
line = scanner.nextLine();
if (line.length() < 1 || line.length() > limit) {
System.out.print("输入长度(不大于" + limit + ")错误,请重新输入:");
continue;
}
break;
}
return line;
}
}