001.Java基础 ——程序流程控制和数组基础

顺序结构

程序从上到下逐行地执行,中间没有任何判断和跳转。

分支结构

根据条件,选择性地执行某段代码。 有if…elseswitch两种分支语句。

循环结构

根据循环条件,重复性的执行某段代码。

whiledo…whilefor三种循环语句。

注:JDK1.5提供了foreach循环,方便的遍历集合、数组元素。

 

// 1.导包
import java.util.Scanner;
class TestScanner{
    public static void main(String[] agrs){
        // 2.创建一个Scanner类的对象
        Scanner s = new Scanner(System.in);
        System.out.println("请输入一个字符串");
        // 3.调用此对象的相应的方法,完成键盘输入的值的获取
        //=> next():表示从键盘获取一个字符串
        String str = s.next();
        
        System.out.println(str);
    }
}

 

条件语句总结:

1.条件判断之间可以嵌套

2.①如果多个条件之间是“互斥”关系(即条件之间没有联系,没有公共部分),多个条件语句上下的顺序是自由的

   ②如果多个条件之间存在“包含”关系,要求范围小的要写在范围大的上面

说明:如果 if-else if-else条件的执行语句块{}只有一条语句的话,那么这一对{}可以省略,但是建议不要省略

 

switch语句

/*
switch(变量){
    case 值1:

    case 值2:

    case 值3:

    default:
        }
1.根据变量的值,选择相应的case去判断,一旦满足case条件,就执行case的相应语句。如果没有break或者已经到结尾的话,就会继续执行其下的case语句。
2.default:是可选的(可写,可不写),而且位置是灵活的
3.变量可以是哪些类型?char byte shor int 枚举 string(jdk1.7 以后的版本才可以放string类型的变量)
4.case 条件:其中条件只能是值,不能是取值范围
*/
package com.base.java;

public class TestSwitch1 {
    public static void main(String[] args ){
        int i = 2;
        switch (i){
            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");
                break; //=> default 是结构比较灵活,可以放在其他位置,但是习惯上写在最后,为了保险起见也加一个break      

        }
    }
}

 

习题与注意事项:

package com.base.java;
/*
习题:对学生成绩大于60分的,输出“合格”。低于60分的,输出“不合格”。
说明:当多个case语句处理的语句块一致时,可以统一的来书写。

习题:根据用于指定月份,打印该月份所属的季节。
3,4,5 春季 6,7,8 夏季  9,10,11 秋季 12, 1, 2 冬季,同理用下面这种方法

*/
public class TestSwitch02 {
    public static void main(String[] args){
        int score = 67;
        switch (score/10){
            case 10:
            case 9:
            case 8:
            case 7:
            case 6:
                System.out.println("及格");
                break;
            default:
                System.out.println("不及格");
        }
    }
}

  

无限循环:

for(;;){}

while(true){}

说明:在无限循环内部,要有条件终止的语句,使用break,若没有,那就是死循环。

练习:

// 100以内的质数(素数) 质数定义为在大于1的自然数中,除了1和它本身以外不再有其他因数。
package com.base.java;

public class TestPrimeNumber {
    public static void main(String[] args) {
        boolean flag = false;
        long start = System.currentTimeMillis();
        for (int i = 2; i <= 100000; i++) {
            for (int j = 2; j <= Math.sqrt(i); j++) { // j < i; 中的i改成 Math.sqrt(i)
                if (i % j == 0) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                System.out.println(i);
            }
            flag = false;
        }
        long end = System.currentTimeMillis();
        System.out.println("花费的时间为:" + (end - start)); // 23609,+break 提升了10倍速度 2356 ,i改成Math.sqrt(i) 速度为 190
    }
}

 break and continue

//=> 设置break标签,决定跳出哪层循环
public class BreakContinue {
    public static void main(String[] args) {
        lable: //=> 设置跳出标签 lable
        for (int i = 1; i < 5; i++) {
            for (int j = 1; j < 10; j++) {
                if (j % 4 == 0) {
                    break lable; // continue lable continue 也可以用标签
                    // System.out.println("永远不执行,还会报错"); continue 和 break 下面跟着的语句不会执行
                }
                System.out.print(j);  // 123
            }

        }
    }
}

 输出十万以内质数的第二种写法

// 输出十万以内质数的第二种写法,这个写法运用到了跳出循环的标签设置,修改后的代码如下
public class TestPrimeNumber {
    public static void main(String[] args) {
        // boolean flag = false;
        long start = System.currentTimeMillis();
        lable:for (int i = 2; i <= 100000; i++) {
            for (int j = 2; j <= Math.sqrt(i); j++) { // j < i; 中的i改成 Math.sqrt(i)
                if (i % j == 0) {
                    // flag = true;
                    // break;
                    continue lable;
                }
            }
            //if (!flag) {
                System.out.println(i);
            //}
            //flag = false;
        }
        long end = System.currentTimeMillis();
        System.out.println("花费的时间为:" + (end - start)); // 23609,+break 提升了10倍速度 2356 ,i改成Math.sqrt(i) 速度为 190
    }
}

  

 练习输出1000以内的完数

//1000以内的完数,完数是除了它本身,其他约数的和等于它的数,比如:6 = 1 + 2 + 3
public class YinShu {
    public static void main(String[] args) {
        int current = 0;
        for (int i = 1; i < 1000; i++) {
            for (int j = 1; j < i; j++) {
                if (i % j == 0) {
                    current += j;
                }
            }
            if (current == i) {
                System.out.println(i);
            }
            current = 0;  //  这里要注意

        }
    }
}

  数组

public class TestArray {
	public static void main(String[] args){
		// 1.如何定义一个数组
		// 1.1数组的声明
		String[] names;
		int[] scores;
		// 1.2初始化
		//第一种:静态初始化:初始化数组与给数组元素赋值同时进行
		names = new String[]{"Sam", "Daniel", "Jim"};
		//第二种:动态初始化:初始化数组与给数组元素赋值分开进行
		scores = new int[4];
		//2.如何调用相应的数组元素:通过数组元素的下角标的方式来调用
		//下角标从0开始,到n-1结束,其中n表示数组长度。
		scores[0] = 88;
		scores[1] = 58;
		scores[2] = 98;
		scores[3] = 68;
		// 3.数组的长度,通过数组的length属性。
		System.out.println(names.length); // 3
		System.out.println(scores.length); // 4
		// 4.如何遍历数组元素
		for(int i = 0;  i < name.length; i++){
			System.out.println(names[i]);
		}
	}
}

  

 数组元素的默认初始化值

public class TestArray {
	public static void main(String[] args) {
		String[] strs = new String[4];
		strs[0] = "AA";
		strs[1] = "BB";
		// strs[2] = "CC"; //=>如果有一项没有赋值,则遍历的时候会出现null
		strs[3] = "DD";
		// 遍历数组
		for (int i = 0; i < strs.length; i++) {
			System.out.println(strs[i]);
		}
		// 对于基于基本数据类型的变量创建的数组:byte,char,short,int,long,float.double,boolean
		// 1.对于byte short int long 而言:创建数组以后,默认值为0
		// 2.对于float double而言,默认值是0.0
		// 3.对于char而言,默认的为空格
		// 4.对于boolean而言,默认为false
		// 5.对于引用类型的变量构成的数组而言,默认初始化值为null。以String为例

	}
}

  注意:数组一旦初始化,其长度是不可变的。只能重新定义个数组,并且先把之前的数组值拷贝过来,再添加所需要的内容。

 多维数组的使用

package com.java.base;

public class TestArray {
	public static void main(String[] args) {
		int[] scores1 = new int[10];
		int[] scores2;
		String[][] names;
		// 1.二维数组的初始化
		scores2 = new int[][]{{1,2,3},{4,5,6},{6}}; // 静态初始化

		names = new String[6][5]; // 动态初始化的方式一
		names = new String[6][]; // 动态初始化的方式二
		names[0] = new String[5];
		names[1] = new String[4];
		names[2] = new String[9];
		names[3] = new String[5];
		names[4] = new String[2];
		names[5] = new String[8];
		// 错误的初始化方式
		// names = new String[][]; 什么都没写是错的
		// names = new String[][5]; 前面没有后面有是错的
		// 2.若何来引用具体的某一个元素
		int[][] i = new int[3][2]; // 另一种写法int[] i[] = new int[3][2]; 一样的
		i[1][0] = 90;
		i[2][1] = 100;
		// 3.关于数组的长度
		// 二维数组的长度,length属性
		System.out.println(i.lenght);
		// 二维数组中元素的长度
		System.out.println(i[0].lenght);
		// 4.如何遍历二维数组(嵌套for循环)
		for(int m =0; m < scores2.length; m++){
			for(int n = 0; n < scores2[m].length; n++){
				System.out.println(scores2[m][n]);
			}
		}


	}
}

 数组的常见异常:越界

public class TestArray {
    public static void main(String[] args) {
        // 1.数组下标越界异常:java.lang.ArrayIndexOutOfBoundsException
        int[] i = new int[10];
        i[0] = 100;
        // i[10] = 98; //=>这里的下标为10,则数组长度却为11,因此越界
        for (int j = 0; j <= i.length; j++) { // 此处如果是有“=”号,则又是越界,长度多1个
            System.out.println(i[j]);
        }
    }
}

 

数组的常见异常:空指针错误异常  

public class TestArray {
    public static void main(String[] args) {
        // 2.空指针异常:java.lang.NullPointerException
        // 第一种:
        boolean[] b = new boolean[3];
        b = null; // 此处将引用数据类型设置为null,指针就消失了,下面在b[1]访问数组会报错
        System.out.println(b[1]);

        // 第二种:
        String[] str = new String[4];
        System.out.println(str[3].toString()); // new之后的数组并没有赋值,这时候选择某个元素,则为null,再调用方法就是报错,空指针异常

        // 第三种:二维数组的
        int[][] j = new int[3][];
        j[2][0] = 12; // 这里是没有给 j[2]赋值,则j[2]是null,所以null没法指向[0]这里
    }
}

注意:

int[] x, y[];

// 相当于

// int[] x; //=> 声明一个一维数组

// int[] y[]; //=> 声明一个二维数组

x = y[];这种赋值是可以通过的,因为x是一维数组,y[]也是一个一维数组

数组的写法(以下写法都可以):

一维数组:int[] x 或者 int x[]

二维数组:int[][] y 或者 int[] y[] 或者 int y[][]

数组中涉及的常见算法

// 数组中涉及的常见算法
/*
 * 1.求数组的最大值,最小值,平均数,总和等
 * 2.数组的复制、反转
 * 3.数组元素的排序
 * */
public class TestArray3 {
    public static void main(String[] args) {
        int[] ary = new int[]{5, 21, 99, 2, 19, 6, 81, 19};
        // 求最大值
        int max = ary[0];
        for (int i = 0; i < ary.length; i++) {
            if (max < ary[i]) {
                max = ary[i];
            }
        }
        System.out.println(max);
        // 求最小值
        // 求总和
        // 求平均数
        // 比较简单,先不写了
    }
}

  

posted @ 2018-07-04 21:01  千行路  阅读(141)  评论(0编辑  收藏  举报