戳人痛处

导航

[记]JAVA学习01 ing

在java中,每一行代码需要在class类中运行;

每个应用从main函数开始运行;

为了运行程序,main方法必须有以下特征;

public static void main(String[ ] args)

public:所有成员可以获取;

static:有该关键字的方法可以在没有创建包含main方法的情况下运行;

void:方法不返回任何值;

例如,以下以void声明的函数没有参数且无返回值;

void test()

 ========

在java中,每段代码以分号分割;

文档注释方法   /** 注释内容 */

=========

获取控制台输入

import java.util.Scanner; 
Scanner myVar = new Scanner(System.in);

该Scanner对象的方法,

Read a byte - nextByte()
Read a short - nextShort()
Read an int - nextInt()
Read a long - nextLong()
Read a float - nextFloat()
Read a double - nextDouble()
Read a boolean - nextBoolean()
Read a complete line - nextLine()
Read a word - next()

-------------------

获取输入并输出

import java.util.Scanner;

class MyClass {
    public static void main(String[ ] args) {
        Scanner myVar = new Scanner(System.in);
        System.out.println(myVar.nextLine());        
    }
}

==========

if语句

if (condition) {
   //Executes when the condition is true
}

例:

public class Program {
    public static void main(String[] args) {
        int x = 7;
        if(x < 42) {
            System.out.println("Hi");
        }
    }
}

 ==========

逻辑运算符 and && , or ||

==========

switch语句

switch (expression) {
   case value1 :
     //Statements
     break; //optional
   case value2 :
     //Statements
     break; //optional
    //You can have any number of case statements.
    default : //Optional
       //Statements
}

例:

public class Program {
    public static void main(String[] args) {
        int day = 3;
        switch(day) {
            case 1:
                System.out.println("Monday");
                break;
            case 2:
                System.out.println("Tuesday");
                break;
            case 3:
                System.out.println("Wednesday");
                break;
        }
    }
}

============

while循环

like c;

============

for 循环

like c;

============

do while循环

like c;

===========

int 数组

int[ ] arr;

 需定义容量以完成声明;

int[ ] arr = new int[5];

使用下标访问和修改;

arr[2] = 42;

===========

初始化数组

public class Program {
    public static void main(String[] args) {
        String[ ] myNames = { "A", "B", "C", "D"};
        System.out.println(myNames[2]);
    }
}

获取数组长度

public class Program {
    public static void main(String[] args) {
        int[ ] intArr = new int[5];
        System.out.println(intArr.length);
    }
}

===========

增强循环

遍历数组

public class Program {
    public static void main(String[] args) {
        int[ ] primes = {2, 3, 5, 7};
        
        for (int t: primes) {
            System.out.println(t); 
        }
    }
}

===========

多维数组

int[ ][ ] sample = { {1, 2, 3}, {4, 5, 6} };

 ===========

Getters & Setters 保护私有变量

============

构造函数:用于类初始化

public class Vehicle {
  private String color;
  Vehicle() {
     color = "Red";
  }
}
public class Vehicle {
  private String color;
  Vehicle(String c) {
    color = c;
  }
}

 

posted on 2022-02-07 18:49  戳人痛处  阅读(31)  评论(0编辑  收藏  举报