JAVA语言概述
1.JAVA语言的特点
1.面向对象性
两个要素:类, 对象
三个特征:封装, 继承, 多态
2.健壮性
(1)去掉了C语言中的指针’(2)自动垃圾回收机制,但仍然会出现内存溢出和内存泄漏;
3.跨平台性
一次编译,到处运行(write once run anywhere)
功劳归功于JVM(虚拟机)
2.开发环境搭建
JDK = JRE +开发工具集(例如javac等)
JRE = JVM +JAVA SE标准类库
3.注释(comment)
分类:
单行注释: //
多行注释:/* / (不可以嵌套使用)
文档注释: /* */
API文档:
API: application programming interface (提供的类库)
基本语法
关键字与保留字
标识符
简单地说就是:凡是自己可以起名字的地方都叫做标识符。例如类名、变量名、方法名、接口名、包名、、、
标识符的命名规则
由26个英文字母大小写,0-9,_或$组成,不能用数字开头;不能使用关键字和保留字但是可以包含;严格区分大小写;不能使用空格
Java中的名称命名规范
包名:多单词组成时所以字母都小写
类名、接口名:多单词组成时,所有单词的首字母大写
变量名、方法名:多单词组成时,第一个单词首字母小写,第二个单词开始每个单词首字母大写
常量名:所有字母都大写,多单词时每个单词用下划线连接。
在起名字时要有意义,最好能见名知意
变量
变量包括变量类型、变量名、存储的值
变量必须先声明,后使用;变量都定义在作用域内。在作用域(就是大括号内)内,它是有效的。换句话说,出了作用域就失效了;同一个作用域下,不能命名相同名字的类。
变量的分类——按数据类型
基本数据类型:数值型(整数类型(byte,short,int,long)、浮点类型(float,double)) 字符型(char)、布尔型(boolean)
注意long型变量必须以英文字母L结尾(大小写都可)
引用数据类型:类(class)(字符串属于类)、接口(interface)、数组(array)
byte 1字节=8bit位 -128~127
short 2字节 -2^15 ~2^15-1
int 4字节 -2^31 ~2^31-1
long 8字节 -2^63 ~ 2^63-1
float:单精度,尾数可以精确到7位有效数字
double:双精度,精度是float的两倍
Java的浮点型常量默认为double型,声明float型常数需要在后面加f或F
float 4字节 -3.403E38~3.403E38
double 8字节 -1.798E308~1.798E308
3.字符型:char(1字符=2字节)
定义char型变量,通常使用一对’ ',内部只能写一个字符。
表示方式:1.声明一个字符;2.转义字符;3.直接使用Unicode值来表示字符型常量,例如\u0043表示的是C
char c1 = '\n'; # \n是换行符,\t是制表符,相当于Tab键
如果是\\n则会输出\n
System.out.print("hello" +c1);
System.out.println("world");
System.out.println("你就不能参加\"单身\"party了!\\n很遗憾"); #双引号里面嵌入双引号需要添加单斜线\
4.布尔型(boolean)
只能取true 或false
/*
基本数据类型间的运算规则
前提:这里讨论只是7种基本数据类型变量间的运算,不包含boolean类型
1.自动类型提升
结论:当容量小的数据类型的变量与容量大的数据类型的变量做运算时,结果自动提升为容量大的数据类型(此时的容量大小指的是表示数的范围的大和小,比如:float容量要大于long的容量)
byte 、char 、short < int<long<float<double
**当byte、char、short三种类型的变量做运算时,结果为Int类型 **
*/
class VariableTest{
public static void main(String[] args){
byte b1 = 2;
int b2 = 129;
int b = b1 + b2;
System.out.println(b);
short s1 = 123;
double d1 = s1;
System.out.println(d1);
//*******************************************8
char c1 = 'a'; #a 等于97
int i3 = 10;
int i4= c1 + i3;
System.out.println(i4);
}
}
2.强制类型提升
自动类型提升的逆运算
/*
需要使用强转符()
2.注意点:强制类型转换,可能导致精度损失
class VariableTest3{
public static void main(String[] args){
double d1 = 12.3;
//精度损失案例
int i1 = (int) d1;//强制转换为int型,截断操作
System.out.println(i1);
//没有精度损失
long l1 = 123;
short s2 = (short)l1;
//精度损失案例
int l2 = 128;
byte b = (byte) l2;
System.out.println(b);//-128
}
}
class VariableTest4{
public stativ void main(String[] args) {
//1.编码问题:
long l = 123213; //没有加L也不报错,因为
它自动变成int型了
System.out.println(l);
//编译失败:过大的整数
//long l1 = 214325355432:
long l1 = 214325355432;
//*************************
//编译失败,大的往小的转不行
float f1 = 12.3;
//2.编码情况2:
//整形常量默认为Int型,浮点型默认为double型
byte b = 12;
//byte b1 = b+ 1: //编译失败,1默认为Int型
//float f1 = b + 12.3; //编译失败
}
}
字符串类型:String
String不是基本数据类型,它属于引用数据类型
/*
String类型变量的使用:
1.String属于引用数据类型,翻译为字符串
2.声明String类型变量时,使用一对""
3.String可以和八种基本数据类型做运算,且运算只能是连接运算+
4.运算的结果仍然是String类型
*/
String s = 123;//编译错误
String s1 = "123";
int = (int) s1;//编译错误
class StringTest {
public static void main(String[] args){
String s1 = "Hello World!";
System.out.println(s1);
String s2 = "a";
String s3 = "";
char c = '' //单引号内不能为空
//*************************
int number = 1001;
String numberStr = "学号:";
String info = numberStr + number;
System.out.println(info);
//***************************************
//练习1
char c = 'a'; //97 A:65
int num =10;
String str = "hello";
System.out.println(c + num + str);// 107hello
SYstem.out.println(c+str + num); //ahello10
System.out.println(c + (num+ str));//a10hello
System.out.println((c+ num) +str);//107hello
System.out.println(str + num + c);//hello10a
//练习2
//* *
System.out.println("* *");
System.out.println('*' + '\t' + '*'); //char相加变成int
System.out.println('*' + "\t" + '*');
System.out.println('*' + '\t' + "*");
System.out.println('*' +( '\t' + "*"));
}
}
按类中声明的位置来分类
成员变量、局部变量
/*
计算机中的不同进制的使用说明
对于整数,有四种表示方式:
二进制(binary):以数字0b或0B开头
十进制(decimal):
八进制(octal):以数字0开头
十六进制(hex):1-9及A-F,以0x或0X开头
相互转换时,都是先转换为二进制
*/
class BinaryTest {
public static void main(String[] args) {
int num1 = 0b110;
int num2 = 110;
int num3 = 0127;
int num4 = 0x110A;
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
System.out.println("num3 = " + num3);
System.out.println("num4 = " + num4);
}
}
二进制的最高位是符号位:0代表正数;1代表复数
00001110: 14
10001110: -14的原码
11110001: -14的反码(除符号位外,各个位置取反)
11110010: -14的补码 (反码+1)
计算机底层都以补码的方式来存储数据
二进制数据的存储方式:所有的数值,不管正负,底层都以补码的方式储存
正数:三码合一
运算符
算数运算符、赋值运算符、比较运算符(关系运算符)、逻辑运算符、位运算符、三元运算符
算数运算符
/*
运算符之一:算数运算符
+ - + - * / % (前)++ (后)++ (前)-- (后)-- +
*/
class AriTest {
public static void main(String[] args){
int num1 = 12;
int num2 = 5;
int result1 = num1 /num2;
System.out.println(result1);//2
int result2 = num1 / num2 *num2
System.out.println(result2);//10
double result3 = num1/ num2;
System.out.println(result3);//2.0 ,先计算出来是int型,再赋值给double,所以补个.0
double result4= num1 / (num2 +0.0);//2.4
double result5= ( double)num1 / num2 ;//2.4
double result6 =(double)(num1 / num2 );//2.0
// %:取余运算
//结果的符号与被模数的符号相同
//开发中经常使用%来判断能否被除尽的情况
int m1 =12;
int n1 = 5;
System.out.println("m1 % n1 = " + m1 % n1);//2
int m1 =-12;
int n1 = 5;
System.out.println("m1 % n1 = " + m1 % n1);//-2
int m1 =12;
int n1 =- 5;
System.out.println("m1 % n1 = " + m1 % n1);//2
int m1 =-12;
int n1 = -5;
System.out.println("m1 % n1 = " + m1 % n1);//-2
//(前)++ 先自增1,然后再运算
//(后) ++ 先运算然后再自增1
int a1 = 10;
int b1 = ++a;
System.out.println("a1 = "+ a1 + ",b1 =" +b1);
int a2 = 10;
int b2 =a2 ++;
System.out.println("a2 = "+ a2 + ",b2 =" +b2);
//注意点:
short s1 =10;
s1 = s1 +1;//编译失败
s1 = (short)(s1+1);//编译正确
s1++;//自增1不会改变本身变量的数据类型
//问题:
byte b1 = 127;
b1++;
System.out.println("b1=" + b1);//-128
//(前)-- 先自减1,然后再运算
//(后) -- 先运算然后再自减1
}
}
/*
练习:随意给出一个整数,打印显示它的个位数,十位数,百位数的值。例如:数字153的情况如下:个位数:3;十位数:5;百位数:1
*/
class AriExercise {
public static void main(String[] args) {
int num 187;
int bai = num / 100;
int shi = num %100 /10;
int ge = num % 10;
System.out.println()
赋值运算符
class SetValueTest {
public static void main(String[] args) {
//赋值符号: =
int i1 =10;
int i2 = 10;
int i2 ,j2;
//连续赋值
i2 =j2 =10;
int i3 =10,j3 = 20;
//********************************
int num1 =10;
num1 +=2;//num1 =num1+2
int num2 =12;
num2 %= 5;//num2 = num2 %5
short s1 = 10;
s1 = s1+2;//编译失败
s1 += 2;//不会改变变量本身的数据类型
//开发中,如果希望变量实现+2的操作,有几种方法?(前提是int num = 10;)
num =num +2;
num +=2;//该方法更好
//练习1
int i =1;
i *= 0.1;
System.out.println(i);//0,因为不改变数据类型,被截断结果变成0
i++;
System.out.println(i);//1
//练习2:
int m =2;
int n = 3;
n *= m++;//n=6, m=3
//练习3:
int n =10;
n += (n++) + (++n);//32(10+10+12)
逻辑运算符
& 逻辑与 |逻辑或 !逻辑非
&& 短路与 ||短路或 ^ 逻辑异或
a^b:当a和b相同时是false,不同时是true
/*
逻辑运算符的使用
说明:
逻辑运算符操作的都是布尔类型的变量
*/
class LogicTest {
public static void main(String[] args) {
//区分& 和 &&
//相同点1:& 与 && 的运算结果相同
//相同点2:当符号左边是true时,二者都会执行符号右边的运算
//不同点:当符号左边是false时,&继续执行符号右边的运算,&&不再执行符号右边的运算
//开发中推荐使用&&
boolean b1 = true;
int num1 =10;
if (b1 & (num1++ > 0)){
System.out.println("我现在在北京");
}else{
System.out.println("我现在在上海");
}
System.out.println("num1 = " + num1);
boolean b2 = true;
int num2 =10;
if (b2 & (num2++ > 0)){
System.out.println("我现在在北京");
}else{
System.out.println("我现在在上海");
}
System.out.println("num2 =" + num2);
//区分:| 与||
//相同点1:|与||的运算结果相同
//相同点2:当符号左边是false时,二者都会执行符号右边的运算
//不同点3:当符号左边是true时,|继续执行符号右边的运算,但||不再执行符号右边的运算
//开发中推荐使用||
boolean b3 = false;
int num3 =10;
if (b3 | (num3++ > 0)){
System.out.println("我现在在北京");
}else{
System.out.println("我现在在上海");
}
System.out.println("num3 =" + num3);
位运算符
/*
1.操作的都是整型的数据
2. <<:在一定范围内每向左移一位,相当于 *2
3. >>:在一定范围内,每向右移一位,相当于 /2
4. 面试题:最高效方式的计算2*8 ? 2<<3 或 8<<1
5. >>:被移位的二进制最高位是0,右移后,空缺位补0;最高位是1,空缺位补1
6. >>>:被移位二进制的最高位无论是0还是1,空缺位都用0补
7. & 二进制进行&运算,只有1&1时结果是1,否则是0
8. |二进制位进行|运算,只有0|0时结果是0,否则是1
9.^:相同时结果是0,不同时结果是1
~:各二进制码按补码各位置取反
class BitTest {
public static void main(String[] args){
int i = 21;
System.out.println("i << 2:" + (i<< 2));
System.out.println("i << 3:" + (i<< 3));
//练习:交换两个变量的值
int num1 = 10;
int num2 =20;
//方法一:
int temp = num1;
num1 = num2;
num2 = temp;
//方法二:弊端:1.相加操作可能超出存储范围;2.有局限性,只能适用数值类型
num1 = num1 +num2;
num2 = num1 - num2;
num1 = num1 - num2;
3.方法三;使用位运算符,只适用于数值类型
num1 = num1 ^num2;
num2 = num1 ^ num2;
num1 = num1 ^ num2;
三元运算符
/*
三元运算符
结构:(条件表达式)?表达式1: 表达式2
说明:1条件表达式的结果为boolean类型
2.根据条件表达式真或假,决定执行表达式1还是表达式2。如果表达式为true,则执行表达式1,如果为false则执行表达式2
3.表达式1和表达式2要求是一致的
4.三元运算符可以嵌套使用
5.凡是使用三元运算符的都可以改写为if,else,反之不一定,但是两种都行时优先使用三元运算符
*/
class SanYuanTest {
public static void main(String[] args) {
int m =12;
int n = 5;
int max = (m> n )? m: n;//判断大小
double num = (m> n )?2 : 1.0;
String maxStr = (m> n) ? "m大" : "n大";
String maxStr =(m> n )? "m大” : ((m == n) ? "一样大" : "n大";
//获取三个数的最大值
int n1 = 12;
int n2 = 30;
int n3 = -43;
int max1 = (n1 > n2 )? n1 : n2;
int max2 = (max1 > n3)? max1: n3;
程序流程控制
顺序结构,分支结构,循环结构
if else
/*
分支结构中的if else (条件判断结构)
*/
class IfTest {
public static void main(String[] args) {
//举例1
int heartBeats = 79;
if (headrtBeats < 60 || heartBeats > 100){
System.out.println("需要做进一步检查");
}
System.out.println("检查结束");
//举例2
int dage =23;
if (age <18){
System.ou.println("你就可以看动画片");
}else{
System.out.println("代算法");
}
}
}
如何从键盘获取不同类型的变量,使用Scanner类
具体实现步骤:
1.导包:import java.util.Scanner;
2.Scanner的实例化:Scanner scan = new Scanner(System.in);
3.调用Scanner类的相关方法,来获取指定类型的变量;
注意:需要根据对应的方法,来输入指定的类型的值,如果输入的数据类型与要求的类型不匹配时,会报异常:InputMisMatchException,导致程序终止
import java.util.Scanner;
class ScannerTest {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
System.out.println(num);
System.out.println("请输入你的姓名");
string name = scan.next();
System.out.println(name);
System.out.println("请输入年龄");
int age = scan.nextInt();
System.out.println(age);
System.out.println("请输入你的体重");
double weight = scan.nextDouble();
System.out.prontln(weight);
System.out.println("你相中我了吗?(true/false);
boolean isLove = scan.nextboolean();
System.out.println(isLove);
//对于char型Scanner没有提供相关的方法,只能获取一个字符串
System.out.println("请输入你的性别:(男/女);
String gender = scan.next();//"男"
char genderChar = gender.charAt(0);//获取索引为0 位置上的字符
System.out.println(genderChar);
}
}
例题1
import java.util.Scanner;
class IfTest {
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
System.out.println("请输入期末成绩(0-100);
int score = scan.nextInt();
if (score==100){
System.out.println("奖励一辆宝马");
}else if (score >80 && score <= 99){ //不能使用80 < score <=99这样的连续符号,因为前面运行完就是boolean型不能和后面的比较
System.out.println("奖励一台手机");
}else if (score>=60 && score< 80){
System.out.println("奖励一个ipad");
}else{
System.out.println("什么都没有");
}
}
}
例题二
/*
由键盘输入三个整数分别存入变量num1、num2、num3;对它们进行排序(使用if else ),并且从小到大输出;
if else可以嵌套使用
*/
import java.util.Scanner;
class IfTest2 {
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
System.out.println("请输入第1个整数");
int num1 = sacnextInt();
System.out.println("请输入第2个整数");
int num2 = sacnextInt();
System.out.println("请输入第3个整数");
int num3 = sacnextInt();
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+","+num1);
}else{
如何获取一个随机数:10-99
double value = (int) Math.random() * 90+10;//[0.0,10) --->[0.0,90.0) -->[10.0,100.0)-->[10,99]
//公式,[a,b] : (int) (Math.random() *(b-a+1) + a)
例题3
import java.util.Scanner;
class IfExer1{
public static vid main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("请输入你的身高");
int height = scan.nextInt();
System.out.println("请输入你的财富");
int wealth = scan.nextDouble();
System.out.println("请输入你是否帅:(true/false)");
int isHandsome = scan.nextBoolean();
if (height >= 100 && wealth >=1 && isHandsome){
System.out.println("我一定要嫁给他");
}else if (height >= 100 || wealth >= 1 ||isHandsome){
System.out.println("嫁吧,");
}else{
System.out.println("不嫁");
}
}
}
//方法二:
System.out.println("请输入你是否帅:(是/否);
String isHandsome = scan.next();
if (height >= 100 && wealth >=1 && isHandsome.equals(“是”)){
System.out.println("我一定要嫁给他");
}else if (height >= 100 || wealth >= 1 ||isHandsome.equals("是")){
System.out.println("嫁吧,");
}else{
System.out.println("不嫁");
switch- case结构
switch(表达式){
case 常量1:
语句1:
//break;
case 常量2:
语句2:
//break;
case 常量N:
语句N;
//break;
default:
语句:
//break;
}
说明:
1.根据switch表达式中的值,依次匹配各个case中的常量,一旦匹配成功,则进入相应case结构中,调用其执行语句。当调用完执行语句以后则仍然继续向下执行其他case结构中的执行语句,直到遇到break关键字或此switch-case结构末尾为止结束
== switch结构中的表达式只能是如下的6种数据类型之一:byte 、short、char、int、枚举类型(JDK5.0新增)、String类型(JDK7.0新增) ==
3.case之后只能声明常量,不能声明范围
4.default 是可选的,并且位置是可选的
class SwitchCaseTest {
public static void main(String[] args){
int number = 2;
switch(number){
case 0:
System.out.println("zero");
break
case 1:
System.out.println("one");
break
case 2:
System.out.println("two");
break
case 3:
System.out.println("three");
break
default:
System.out.println("other");
例题1.
/*如果swiech-case中的多个case的之星语句相同则可以考虑合并
*/
class SwitchTest {
public static void main(String[] args) {
int score =78;
switch(score/10){
case 0:
case1:
case2:
case3:
System.out.println("及格");
break;
例题2
/*
从键盘上输入2019年的month和day,要求通过程序输出输入的日期为2019年的第几天
import java.util.Scanner;
class SwitchTest2 {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("请输入2019年的月份")
int month =scan.nextInt();
System.out.println("请输入2019年的日")
int day = scan.nextInt();
int sumDay = 0;
switch(month){
case12:
case11:
case4:
sumDay += 31;
case3:
sumDay += 28;
case2:
sumDay += 31;
case1:
sumDay += day;
}
System.out.println("2019年" + month +"月" + day + "日是当年第" + sumDay);
例题3:从键盘分别输入年月日,并判断一年的第几天
import java.util.Scanner;
class SwitchTest3 {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("请输入年")
int month =scan.nextInt();
System.out.println("请输入月份")
int month =scan.nextInt();
System.out.println("请输入日")
int day = scan.nextInt();
int sumDay = 0;
switch(month){
case12:
case11:
case4:
sumDay += 31;
case3:
if ((year % 4 && year % 100 !=0) || year % 400 ==0){
sumDay += 29;
}else{
sumDay +=28;
}
case2:
sumDay += 31;
case1:
sumDay += day;
}
System.out.println(year +"年" + month +"月" + day + "日是当年第" + sumDay);
凡是可以使用switch case的结构都可以转换为if else结构,反之不行,如果都可优先使用switch case,因为switch case的执行效率稍高
程序流程控制:循环结构
for循环、while循环、do-while 循环
/*
For循环结果给的使用
1.循环结构的四个要素
1初始化条件、2循环条件(boolean类型)、3循环体、4迭代条件;
2.for循环的结构
for(1;2;4){
3
}
执行过程:1-2-3-4-2-3-4-...-2
*/
class ForTest {
public static void main(String[] args){
for (int i =1; i <=5;i++){
//i在for循环内有效,出了for循环就失效了
Systtem.out.println("Hello World");
练习1
int num =1;
for(System.outprint('a');num<= 3;System.out.print('c'),num++){
System.out.print('b');
}
//输出结果:abcbcbc
例题:遍历100以内的偶数,输出所有偶数的和
int sum =0;
for (int i = 1;i <=100;i++);{
if (i % 2 ==0){
System.out.print(i);
sum +=i;
}
}
System.out.println(sum);
例题2
class ForTest1{
public static void main(String[] args){
for(int i =1; i <= 150;i++){
System.out.print(i + "");
if(i % 3 ==0){
System.out.print("foo");
}
if(i % 5 ==0){
System.out.print("biz");
}
if(i % 7 ==0){
System.out.print("baz");
}
//换行
System.out.println();
}
}
}
例题3
输入两个正整数m和n,求其最大公约数和最小公倍数
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);
breeak;//一旦执行到break,就跳出循环
}
}
//获取最小公倍数
//1.获取两个中的较大值
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;
}
}
}
while循环
1.循环结构的四个要素
1初始化条件、2循环条件(boolean类型)、3循环体、4迭代条件;
2.while循环的结构
1
while(2){
3;
4;
}
执行过程:1-2-3-4-2-3-4…-2
for循环和while循环可以相互转换
class WhileTest{
public static void main(String[] args){
//遍历100以内的所有偶数
int i=1;
while (i <=100){
if(i %2 ==0){
System.out.println(i);
}
i++;
}
//出了while循环之后i还可以调用
System.out.println(i);//101
}
}
do-while 循环
1.循环结构的四个要素
1初始化条件、2循环条件(boolean类型)、3循环体、4迭代条件;
2.do-while循环结构
1
do{
3;
4;
}while(2);
执行过程:
1-3-4-2-3-4-…-2
说明:do-while至少会执行一次循环体
class DoWhileTest{
public static void main(String[] args){
//遍历100以内的偶数,并计算所有偶数的和和个数
int num = 1;
int sum =0;//记录总和
int count = 0;//记录个数
do{
if(num % 2 ==0){
System.out.println(num);
sum +=num;
count ++;
}
num++;
}while(num<= 100);
System.out.println(sum);
System.out.println(count);
}
}
例题: 从键盘读入个数不确定的整数,并判断读入的正数和负数的个数,输入为0时结束程序
说明:1.不在循环结构限制次数的结构:for(;;)或while(true)
2.结束循环由几种方式:
循环条件部分返回false;在循环体中执行break
import java.util.Scanner;
class ForWhileTest{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int positiveNumber = 0;//记录正数的个数
int negetiveNumber = 0;//记录负数的个数
while(true){ //也可以用for(;;){
int number = scan.nextInt();
if (number > 0){
positiveNumber++;
}else if (number <0){
negetiveNumber++;
}else{
break;
}
}
System.out.println(positiveNumber);
System.out.println(negetiveNumber);
}
}
嵌套循环
1.嵌套循环:将一个循环结构A声明在另一个循环结构B的循环体中,就构成了嵌套循环
2.外层循环:循环结构B
内层循环:循环结构A
class ForForTest{
public static void main(String[] args){
//System.out.println("******")
for(int j =1;j<=4;j++){
for(int i =1;i<=6;i++){
System.out.println('*');
}
System.out.println();
}
}
}
/*
*
**
***
****
*****
*/
for (int i =1;i<=5;i++){ //控制行数
for(int j=1;j<=i;j++){
System.out.print("*");
}
System.out.println();
}
例题1:实现九九乘法表
11=1
21=2 22=4
…
91=9 … 9*9=81
class NineNineTable{
public static void main(String[] args){
for(int i =1;i<=9;i++){
for (int j =1;j<=i;j++){
System.out.print(i+" * " +j + "=" +(i * j ));
}
System.out.println();
}
}
}
例题2:100以内的所有质数
class PrimeNumberTest{
public static void main(String[] args){
for(int i =2;i<=100;i++){ //遍历100以内的自然数
boolean isFlag = true;//标识i是否被j除尽,一旦除尽修改其值
for(int j=2;j <i;j++){ //j:被i去除
if(i % j ==0){
isFlag = false;
}
}
if(isFlag ==true){
System.out.println(i);
}
}
}
}
方法二,效率更高(优化)
class PrimeNumber1Test{
public static void main(String[] args){
//获取当前时间举例1970-01-01 00:00的毫秒数
long start = System.currentTimeMillis();
for(int i =2;i<=100;i++){ //遍历100以内的自然数
boolean isFlag = true;//标识i是否被j除尽,一旦除尽修改其值
//优化二
for(int j=2;j <= Math.sqrt(i);j++){ //j:被i去除
if(i % j ==0){
isFlag = false;
break;//优化1,只对本身非质数的自然数是有效的
}
}
if(isFlag ==true){
System.out.println(i);
}
}
//获取当前时间举例1970-01-01 00:00的毫秒数
long end = System.currentTimeMillis();
System.out.println("所花费的时间为:" + (end- start));
}
}
方法三
class PrimeNumber1Test{
public static void main(String[] args){
int count =0;
//获取当前时间举例1970-01-01 00:00的毫秒数
long start = System.currentTimeMillis();
label:for(int i =2;i<=100;i++){
for(int j =2;j<= Math.sqrt(i);j++){
if(i % j ==0){
continue label;
}
}
count++;
}
long end = System.currentTimeMillis();
System.out.println("质数的个数为" + count);
System.out.println("所花费的时间为:“ +(end- start));
特殊关键字的使用:break,continue
break和continue关键字的使用
break:在switch-case和循环结构都可以用,在循环中使用的作用是结束当前循环
continue:只能在循环结构中用,在循环中使用的作用是结束当次循环
两者的相同点:关键字后面不能声明执行语句
class BreakContinueTest{
public static void main(String[] args){
for(int i =1;i<= 10;i++){
if(i % 4 ==0){
break;//123
//continue;//123567910
}
System.out.print(i);
}
System.out.println();
//****************************
for (int i =1; i <= 4,i++){
for(int j =1;j<=10;j++){
if(j%4==0){
break;//默认跳出包裹此关键字最近的一层循环
}
System.out.print(j);
}
System.out.println();
}
//************************************
lable:for (int i =1; i <= 4,i++){
for(int j =1;j<=10;j++){
if(j%4==0){
//break lable;//结束指定标识的一层循环结构
continue lable;//结束指定标识的一层循环结构档次循环,结果为123123123123
}
System.out.print(j);
}
System.out.println();
}
}
}
例题:一个数如果恰好等于它的因子之和,这个数就称为”完数“。例如6=1+2+3.编程找出1000以内的所有完数。(因子:除去这个数本身的其他约数 )
int factor =0;
for(int i =1; i<= 1000;i++){
for (int j =1; j<= i/2;j++){
if (i % j ==0){
factor +=j;
}
if(i == factor){
System.out.println(i);
}
//重置factor
factor = 0;
}