Java—數組和方法。本站提示廣大學習愛好者:(Java—數組和方法)文章只能為提供參考,不一定能成為您想要的結果。以下是Java—數組和方法正文
以上兩步合並:int[] scores = new int[5];
3. 賦值 scores[0] = 76;
以上三步合並:int[] scores = {76, 80, 81, 82, 99};
等價於int[] scores = new int[]{76, 80, 81, 82, 99};
數組名.length:獲取數組的長度
Arrays類是java提供的一個工具類,在java.util包中。
foreach 並不是java中的關鍵字,是for語句的特殊簡化版本。
for (元素類型 元素變量:遍歷對象) {
執行代碼;
}
String[] subjects = new String[5];
subjects[0] = "Oricle";
subjects[1] = "PHP";
subjects[2] = "Linux";
subjects[3] = "Java";
subjects[4] = "Html";
//System.out.println("數組中第4個科目為:" + subjects[3]);
Arrays.sort(subjects);
for (int i = 0; i < subjects.length; i++) {
System.out.println(subjects[i]);
}
System.out.println("輸出數組中的元素:" + Arrays.toString(subjects));
for (String subject : subjects) {
System.out.println(subject);
}
在定義二維數組時,可以至指定行的個數,然後再為每一行分別指定列的個數,如果每行的列數不同,則創建的是不規則的二維數組。
String[][] names = {{"tom", "jack", "mike"}, {"zhangsan", "lisi", "wangwu"}};
for (int i= 0; i < names.length; i++) {
for (int j = 0; j < names[i].length; j++) {
System.out.println(names[i][j]);
}
}
定義方法:訪問修飾符 返回值類型 方法名(參數列表) {
方法體
}
package com.test;
public class Demo4 {
public static void main(String[] args) {
Demo4 demo = new Demo4();
demo.show();
double avg = demo.calcAvg();
System.out.println("平均成績為:" + avg);
}
public void show() {
System.out.println("Welcome to java!");
}
public double calcAvg() {
double java = 92.5;
double php = 83.0;
double avg = (java + php) / 2;
return avg;
}
}
返回值為:
Welcome to java!
平均成績為:87.75
把定義方法時的參數稱為形參,目的是用來定義方法需要傳入的參數的個數和類型;把調用方法時的參數稱為實參,是傳遞給方法真正被處理的值。
public static void main(String[] args) {
Demo4 demo= new Demo4();
demo.calcAvg(94, 81);
}
public void calcAvg(double score1, double score2) {
double avg = (score1 + score2) / 2;
System.out.println("平均分:"+avg);
}
定義:如果同一個類中包含了兩個或兩個以上方法名相同、方法參數的個數、順序或類型不同的方法,稱為方法的重載,也可稱為該方法被重載了。
方法的重載與方法的修飾符或返回值沒有關系
public class HelloWorld {
public static void main(String[] args) {
HelloWorld hello = new HelloWorld();
// 調用無參的方法
hello.print();
// 調用帶有一個字符串參數的方法
hello.print("java");
// 調用帶有一個整型參數的方法
hello.print(18);
}
public void print() {
System.out.println("無參的print方法");
}
public void print(String name) {
System.out.println("帶有一個字符串參數的print方法,參數值為:" + name);
}
public void print(int age) {
System.out.println("帶有一個整型參數的print方法,參數值為:" + age);
}
}
返回值為:
無參的print方法 帶有一個字符串參數的print方法,參數值為:java 帶有一個整型參數的print方法,參數值為:18