java 学习

javac Junior.java

java Junior

 

 

Employee.java

// import java.io.*;//下面的命令行将会命令编译器载入 java_installation/java/io 路径下的所有类


public class Employee {
    String name;
    int age;
    String disgnation;
    double salary;
    public Employee(String name){
        this.name=name;
    }
    public void empAge(int empAge){
        age=empAge;
    }
    public void empDesignation(String empDesignation){
        disgnation = empDesignation;
    }
    public void empSalary(double empSalary){
        salary = empSalary;
    }
    public void printEmployee(){
        System.out.println("name is:"+name);
        System.out.println("age is:"+age);
        System.out.println("disgnation is:"+disgnation);
        System.out.println("salary is:"+salary);
    }
    public static void main(String[] args){
        System.out.println("hi");
    }
}

EmployeeTest.java

//下面的命令行将会命令编译器载入 java_installation/java/io 路径下的所有类
import java.io.*;


public class EmployeeTest {
    public static void main(String[] args){
        // HelloWorld hello = new HelloWorld();
        // hello.main(args);
        Employee empOne = new Employee("runoob1");
        Employee empTwo = new Employee("runoob2");
        empOne.empAge(25);
        empOne.empDesignation("senior engineer");
        empOne.empSalary(30000);
        empOne.printEmployee();

        empTwo.empAge(22);
        empTwo.empDesignation("junior engineer");
        empTwo.empSalary(10000);
        empTwo.printEmployee();
    }
}

Junior.java

/*
 * 这里是Java的进阶学习:Java的数据结构以及其用法,Java字符串的用法
 */
import java.util.StringTokenizer;
public class Junior {
    static String[] createArray(){
        //创建一个字符串数组,并且返回这个数组;
        String liStr[] = new String[50000];
        for(int i=0;i<50000;i++){
            liStr[i] = "s"+i;
        }
        return liStr;
    }
    static void costSets(String[] arg){
        long starttime = System.currentTimeMillis();
        for(int i=0;i<50000;i++){
            // String s="hello";
            // String n="girl";
            arg[i] = "hello";
        }
        long endtime=System.currentTimeMillis();
        System.out.println("string set s cost time:"+(endtime-starttime));
    }
    static void costNewsets(String[] arg){
        long starttime = System.currentTimeMillis();
        for(int i=0;i<50000;i++){
            // String s=new String("hello");//这种new的方式,更加消耗时间,上面直接赋值的方式更快
            // String n=new String("girl");
            arg[i] = new String("hello");
        }
        long endtime=System.currentTimeMillis();
        System.out.println("string set new s cost time:"+(endtime-starttime));
    }
    static void costIntern(String[] arg){
        long starttime = System.currentTimeMillis();
        for(int i=0;i<50000;i++){
            arg[i] = new String("hello");
            arg[i] = arg[i].intern();
        }
        long endtime=System.currentTimeMillis();
        System.out.println("string set intern s cost time:"+(endtime-starttime));
    }
    static void updateStr(){
        String li[] = createArray();
        costSets(li);
        costNewsets(li);
        costIntern(li);
        // double d=0.4d;
        // String d="hi girl";
        char d='A';
        // int d=10;
        // float d=2.2f;
        // long d=20;//short d=20;
        // System.out.format("%f %n", d);//%f 可以拼接float,double
        System.out.format("%s %n", d);//%s 可以拼接String,char
        // System.out.format("%d %n", d);//%d 可以拼接int,short,long
    }
    static void appendStr(){
        //比较字符串相加,跟字符串append的性能
        long starttime = System.currentTimeMillis();
        for(int i=0;i<5000;i++){
            String ret = "hi girl"+"hi boys"+"hi everyone"+"hi guys";
        }
        long endtime=System.currentTimeMillis();
        System.out.println("string plus string cost time:"+(endtime-starttime));
        long starttime1 = System.currentTimeMillis();
        for(int i=0;i<5000;i++){
            StringBuffer ret = new StringBuffer();
            //+"hi boys"+"hi everyone"+"hi guys"
            ret.append("hi girls,");
            ret.append("hi boys,");
            ret.append("hi everyone,");
            ret.append("hi guys,");
            // System.out.println("stringbuffer append:"+ret);
        }
        long endtime1=System.currentTimeMillis();
        System.out.println("stringbuffer append cost time:"+(endtime1-starttime1));

    }
    static void strUsage(){
        //字符串的一些基本用法
        String str="Hello World";
        String lowerStr="hello wor-=ld";
        // Object objStr = str;
        // System.out.println("turn string to object:"+str.compareTo(objStr.toString()));
        // System.out.println("tolowercase:"+str.toLowerCase());//toLowerCase|toUpperCase,改变大小写
        // System.out.println(str.compareTo(lowerStr));//比较字母,排除符号干扰
        // System.out.println(str.compareToIgnoreCase(lowerStr));//忽略大小写的比较,如果除了大小写,
        //其他的都一样,就返回0,也就是没有差异,被认作是一样的
        // int index=str.lastIndexOf("World");//if not in str,return -1,then return the last index of the str
        // int index=lowerStr.indexOf("l");//if not in str,return -1,then return the first index of the str
        // System.out.println(index);
        // System.out.println(lowerStr.substring(0, 4));//substring(start-index,end-index)---切片,include start,except end
        // System.out.println(lowerStr.substring(4));//substring如果只有一个参数,就是从当前参数一直到最后
        // System.out.println(lowerStr.replace("l", "@"));// replace所有的l to @,跟replaceAll是一样的
        // System.out.println(lowerStr.replaceFirst("o", "kk"));//只replace第一个o to kk
        // System.out.println(lowerStr.replaceAll("l", "xl"));
        // String reverseStr = new StringBuffer(str).reverse().toString();
        // System.out.println(reverseStr);
        String runoob = "www.runoob.com";
        String[] split_li;
        // split_li = lowerStr.split("o");//split用法跟python一样,切割之后,就变成数组,需要先定义一个数组来接收它的返回值
        // for(String element:split_li){System.out.println(element);}
        // split_li=runoob.split("\\.");//.需要转意符\转换一下
        // for(int index=0;index<split_li.length;index++){
        //     System.out.println(split_li[index]);
        // }
        StringTokenizer splitStr=new StringTokenizer(str, "9");//这个类StringTokenizer默认是根据空格分割字符串,也可以传入自定义分隔符
        // System.out.println(splitStr);
        // while(splitStr.hasMoreElements()){
        //     System.out.println(splitStr.nextElement());//有点类似python的生成器next取值
        // }
        boolean match = str.regionMatches(true,9, lowerStr,11, 2);//str从第9个字符开始,lowerStr从第11个字符开始,各取2个字符进行比较
        //如果第一个参数是true,表示忽略大小写差异,如果第一个参数没有boolean值,就按照上面一行的意思理解
        // System.out.println(match);
        String li[] = new String[50000];
        // costSets(li);
        // costNewsets(li);

    }
    public static void main(String[] args){
        // strUsage();
        // updateStr();
        appendStr();
    }
}

HelloWorld.java

/*
 * 从hello world开始,沿着菜鸟教程的目录,顺下来,把Java的基础语法,循环,数据类型,函数,变量类型,都看得差不多了。
 */
import java.util.Arrays;//引入Arrays类,做一些数组的增删改查操作
public class HelloWorld {
    /*
     * java 注释,Java输出helloworld    
    * java 注释,Java输出helloworld
    */
    static boolean bool;//类变量
    static byte by;
    private static char ch='A';
    static double d;
    static float f;
    static int i;
    static long l;
    static short sh;
    static String str;
    String variable;//实例变量
    public String public_name;
    private double private_salary;//私有变量
    public void setName(String name){
        public_name = name;
    }
    public void setSalary(double salary){
        //配合私有变量,设置变量值
        private_salary=salary;
    }
    public double getSalary(){
        //配合私有变量,获取变量值
        return this.private_salary;
    }
    String ret(){
        return "这里的返回值跟function定义的类型有关,没有返回值会报错";
    }
    // void test(){
        // return 0//如果function有返回值,必须在function前面定义返回值类型,如果function没有返回值,
        //就在function前写上void,function前必须写点啥来局限它
    // }
    public void printVariable(){
        System.out.printf("salary:%s, name:%s %n", private_salary, public_name);
    }
    public static String getType(Object test){
        // 尝试用type()python的用法,失败,没有类似的关键字方法
        return test.getClass().getName().toString();
    }
    public HelloWorld(){
        // 当该类有实例化对象的时候,就会自动加载执行这里的代码。如果没有实例化对象,
        // 就在main里面运行,是无法执行这里的代码的
        // this.dataType();
        System.out.println("Hello World"); // 注释符号just like javascript
    }
    void dataType(){
        // int a=20;
        // int b=30;
        // int c;
        // c = a+b;//byte,short,都不能计算,这两个类型有什么用
        // long a=20;
        // long b=10;
        // long c;
        // float a=23.4f;
        // float b=12.3f;
        // float c;
        // double a=10D;
        // double b=20.3;
        // double c=0.;//double 可以是10D|10.|10 三种写法
        // c = a+b;
        // boolean c=true;//Java bool值,都是小写true|false
        // c=false;
        // char c_='L';//char 只能定义一个字母,单纯字母而已,包括大小写都可以;String才是字符串跟python一样的字符串
        // System.out.println(c_);
        // System.out.printf("size:%1$s,min:%2$s, max:%3$s  %n","1", "2", "3");
        // System.out.printf("character size:%1$d, ",Character.SIZE);//%n是换行符\n,放在后面如果下一行代码,是看不出来空行的,
        // System.out.println((int)Character.MIN_VALUE);
        // System.out.println((int)Character.MAX_VALUE);
        // System.out.printf("byte :%d,%d,%d %n", Byte.SIZE,Byte.MIN_VALUE,Byte.MAX_VALUE);
        // System.out.printf("short :%d,%d,%d %n", Short.SIZE,Short.MIN_VALUE,Short.MAX_VALUE);
        // System.out.printf("double :%s,%s,%s %n", Double.SIZE,Double.MIN_VALUE,Double.MAX_VALUE);
        // System.out.printf("float :%s,%s,%s", Float.SIZE,Float.MIN_VALUE,Float.MAX_VALUE);
        // System.out.println("Bool :" + bool);
        // System.out.println("Byte :" + by);
        // System.out.println("Character:" + ch);
        // System.out.println("Double :" + d);
        // System.out.println("Float :" + f);
        // System.out.println("Integer :" + i);
        // System.out.println("Long :" + l);
        // System.out.println("Short :" + sh);
        // System.out.println("String :" + str);
        // final float FINALFLOAT = 2.3f;//常量可以用小写驼峰体,一般都是用大写用于跟字面量区分开来
        // float floatObj = FINALFLOAT+1;
        // int decimal = 100;
        // int octal = 0144;//100 int数字类型的八进制写法
        // int t = 0x34;
        // int hexa =  0x64;//100 int数字类型的十六进制写法
        // System.out.printf("%s, %s, %s, %s", decimal, octal, t, hexa);
        // char a = '\u1110';
        // String b = "\u0001";
        // System.out.println(a);
        //容量从小到大排列,容量就是占用的内存大小:byte,short,char,int,long,float, double
        //不能对boolean类型做转换,不能把对象类型转换成不相关类的对象,把容量大的类型转成容量小的类型需要用强制转换,
        //转换时会丢失精度或者溢出,从浮点数到整数是直接舍弃小数部分而不是四舍五入
        // int intObj = 10;
        // byte byteObj = (byte)intObj;//这里就相当于python的byte(intObj),这就是强制类型转换,对应的概念是自动类型转换,
        // byte byteTest = 20;
        // int byteTurnInt = byteTest-5;//自动类型转换,有前提条件,从小转大才可以。
        // System.out.printf("%s , %s %n",byteObj,byteTurnInt);
        // byte s=10;
        // char s1 = s;//从byte到char也有损失,不能转
        // short s2=(int)s1;//从int转换到short会有损失就无法编译通过,不能转;从char到short,从short到char亦是如此
        // System.out.printf("%s , %s %n",s,s1);
        float f=0.4f;
        double d=0.4d;
        System.out.printf("int cut after the point:%s, float:%s, double:%s %n",(int)23.9, f, d);
    }
    void variableTest(){
        //Java变量
        int a,b,c;
        a=10;
        b=20;
        // c=c+b;//局部变量,必须在声明的时候,初始化它,否则编译会报错
        c=a+b;
        variable+="实例变量";//实例变量有默认值,默认值就是它的数据类型的默认值
        bool=true;
        System.out.println(c);
        System.out.printf("类变量:%s,实例变量:%s %n", bool, variable);
        this.setName("peter");//这里的this,就有点像python里面的self对象,可以调用类自己的方法和变量
        this.setSalary(2000.45);
        this.printVariable();
        System.out.println(ch);
    }
    void logicMath(){
        //这里掰扯一下i++,跟++i
        int a1=10;
        int b1=a1++;//这里是先赋值再运算,先运行a1=b1,再运算a1=a1+1
        System.out.println("a1 after a1++:"+a1);
        int c=++a1;//这里先运算再赋值,先运算a1=a1+1,再赋值给c=a1.
        System.out.printf("a=%s, b=%s ,c=%s %n", a1, b1, c);
        int a = 5;//定义一个变量;
        boolean b = (a<4)&&(a++<10);
        System.out.println("使用短路逻辑运算符的结果为"+b);
        System.out.println("a的结果为"+a);
        int d=a++;//d=a=5,a=a+1=6;
        System.out.printf("d=%s, a=%s %n", d, a);
        int d1=d++;//d1=d=5,d=d+1=6;
        System.out.printf("d1=%s, d=%s %n", d1, d);
        int d2=d1++;//d2=d1=5,d1=d1+1=6;
        System.out.printf("a的结果为%s, d=%s,d1=%s,d2=%s,d1=%s %n", a, d, d1, d2, d1);
        a=a++;
        System.out.println(a);
        a=a++;
        System.out.println(a);
        a=a++;
        System.out.println(a);
        int c2;
        c2=(a!=5)?20:30;//if a!=5 is true,then c2=20,else c2=30;java ==|!= 跟python一样用法
        System.out.println(c2);
        // long s=1;
        // boolean is_int = s instanceof long;//这里试过了short,char,int,double,float,long都报错,只有String不报错
        String name = "hi girl";
        boolean result = name instanceof String;
        System.out.println(result);
    }
    void roundTest(int cutRound){
        //循环测试
        //斐波那契数列
        int a=1;
        int b=2;
        int c=a+b;
        while (b<cutRound){
            a=c+b;
            b=a+c;
            if(b>100)continue;
            c=a+b;
            System.out.printf("斐波那契数列:a=%s,b=%s,c=%s %n", a, b, c);
        }
        this.whileRound();//do...whild for 循环示例
    }
    void whileRound(){
        //do while
        int x=10;
        do{
            // if(x==10)continue;//这里会卡死,如果满足条件判断,continue,就会跳到while条件判断中去,
            //如果while中的条件为假则直接跳出循环,但是如果while条件为真,则卡死在这里
            if(x==10)break;
            x++;
            System.out.println("do...while:"+x);
        }while(x<11);

        //for
        int [] li = {10, 20, 39,};
        String [] s_li = {"peter","john","bob",};
        System.out.println("length of s_li:"+s_li.length);
        for(int x1=2;x1<5;x1++){
            System.out.println("for 循环:"+x1);
        }
        for (int x0:li){
            System.out.print(x0);
            System.out.print(",");//这里输出的就是li里面的每个元素,就跟li[index]效果是一样的
        }
        for (String s:s_li){
            if(s=="bob")break;
            System.out.print(s);
            System.out.print("、");
        }
        System.out.print("\n");
        //这里的for循环,跟javascript很像
        for(int index=0;index<li.length;index++){
            if(index==1){index+=1;System.out.println("if index:"+index);}else{
                System.out.println("length of li:"+li.length);
            }
            System.out.printf("index:%s, real item:%s %n",index,li[index]);
        }

    }
    void switchTest(){
        //switch
        int grade=70;
        switch(grade){
            case 90:
            System.out.print("bravol");
            break;
            case 80:
            case 70:
            System.out.print("good");
            break;
            case 60:
            System.out.print("try harder");
            break;
            default:
            System.out.print("unknown grade");
        }
        System.out.print("\n");
        System.out.println("your grade is:"+grade);
    }
    static int[] arrayTest(int[] list){
        //这里如果加上static,就可以直接在main里面调用它,不必实例化一个对象出来,用这个对象来调用它。
        int[] li;//创建一个整型数组,里面的元素都是int类型。这里没有给出初始化数组元素值,后面就不能赋值,会报错。
        int[] li_5 = new int[5];//创建一个整型数组,长度为5
        for(int i=0;i<5;i++){
            li_5[i] = i;   
        }
        int max=list[0];
        for(int i=0;i<list.length;i++){
            if(list[i]>max){
                max=list[i];
            }
        }
        System.out.println("max:"+max);
        Arrays.sort(list);//数组排序
        for(int element:list){System.out.print(element);System.out.print("、");};
        System.out.println();
        int index=Arrays.binarySearch(li_5, 3);//数组二分查找,排序过的数组中查找指定元素
        System.out.println(index);
        Arrays.fill(li_5, 0);// 数组用0来填充li_5里面的每一个值。
        for(int element:li_5){System.out.print(element);System.out.print(", ");}
        System.out.println();
        // System.out.println("for append li_5:"+li_5[0]);
        int[] result = new int[list.length];
        for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
            //把list reverse的结果赋值给result
            result[j] = list[i];
        }
        // System.out.println(list);//Java如果直接打印数组,得到的是数组的内存地址
        int total=0;
        for(int element:result){
            System.out.print(element+",");
            total += element;
        }
        System.out.println();
        System.out.println("total:"+total);
        String[][] twoLi = new String[3][4];//这里创建一个3rows*4cols的二维数组
        // twoLi[0] = new String[3];
        // twoLi[1] = new String[4];
        twoLi[0][0] = "hi";
        System.out.println(twoLi[2][3]);//string默认值是null,占位符
        return result;
        
    }
    //Java里面main方法必须设置成公有方法,否则Java解释器无法运行该类
    public static void main(String[] args) {
        // main是python的__main__入口,每个文件只能有一个main,这一点是相同的。
        // 所以在Java中如果这个类有main,同一个文件的其他类就不能有main函数。
        // 如果Java文件有变化,需要重新编译,再run,否则看不到修改效果。
        HelloWorld helloObj = new HelloWorld();
        // 在类里面调用类方法,需要在调用之前,先实例化一个类对象出来,然后才可以调用该方法,Java里面并没有self对象,
        // Java里面有this对象,还没有摸清楚,它要怎么用
        // helloObj.dataType();
        // helloObj.variableTest();
        // helloObj.logicMath();
        // helloObj.roundTest(100);
        // helloObj.switchTest();
        // int[] ret = helloObj.arrayTest(new int[]{10, 20, 30});
        // System.out.println("ret:"+ret);
        System.out.println("ret:"+arrayTest(new int[]{11,33,22,}));
        // String letter;
        // letter = "_$%123";
        // System.out.println("字符串的使用需要先声明一个变量的类型,再给它赋值:"+letter);
        // // 类示例化一个对象
        // Dog dog = new Dog("muyangquan");
        // System.out.println("dog-getclass:"+getType(dog));//函数的返回值要怎么获取,还有待知晓
        // // 对象给类属性赋值
        // dog.setAge(20);
        // dog.getAge();
        // dog.size=10;

        // // 对象调用类方法
        // dog.run();
        // dog.sleep();
        // dog.eat();
    }
}
class Dog{
    // char s = 'h';
    String breed;
    int age;
    int size;
    String color;
    public Dog(String dog_name){
        // 这里是构造方法,需要与类同名
        System.out.println("public dog-name:"+dog_name);
    }
    void setAge(int age_arg){
        age=age_arg;
    }
    public int getAge(){
        // int 指定了返回的数据类型,必须是数字
        System.out.println("puppy age is:"+age);
        return age;
    }
    void eat(){
        breed="bianmu";
        System.out.println(age);
        System.out.println(breed);
    }
    void run(){
        String name;
        name="puppy";
        System.out.format("run size is: %s, name is: %s",size, name);
        System.out.println("");// println 自带换行功能,format不带换行。python print是Java的println+format
    }
    void sleep(){
        System.out.println("sleep function:"+size);
    }
}

 

posted @ 2022-12-25 22:05  dream-子皿  阅读(22)  评论(0编辑  收藏  举报