Java 筆記

本文记录了在学习Java过程中关于字符串比较(equals和compareTo)、字符操作(如isLetter,toUpperCase,isDigit等)、数值转换(二进制与十进制)、数组和枚举的使用等内容,适合初学者参考。
摘要由CSDN通过智能技术生成

一路波折兜兜轉轉終於開始了海外的兩年求學生活,課程中不免俗地需要碰到後端語言因此在此記錄下Java相關的筆記

字符

equals 用法

當我們要比較兩個字符串是否相等時使用。

跟javascript不同的是當我們使用 str1 == str2時比較的是內存中儲存的首地址

String Str1 = new String("runoob");
String Str2 = Str1;
boolean retVal;

retVal = Str1.equals( Str2 );
System.out.println("返回值 = " + retVal );

Compareto 用法

返回参与比较的前后两个字符串的asc码的差值,如果两个字符串首字母不同,则该方法返回首字母的asc码的差值

 String a1 = "a";
 String a2 = "c";        
 System.out.println(a1.compareTo(a2));//结果为-2

如果两个字符串不一样长,可以参与比较的字符又完全一样,则返回两个字符串的长度差值

// 按字母顺序排列 (in alphabetical order):
if(firstString.compareTo(secondString) < 0) {

  System.out.println(firstString.toLowerCase()+" "+secondString.toLowerCase());
}

注意:数字类型不能用compareTo,int跟int的比较不能用compareTo方法,直接用大于(>) 小于(<) 或者 等于(==) 不等于(!=)来比较即可

Character operations

注意此方法只能用在char

isLetter(c)true if alphabetic:
a-z or A-Z
isLetter('x') // true
isLetter('6') // false
isLetter('!') // false

toUpperCase(c)Uppercase version
toUpperCase('a')  // A
toUpperCase('A')  // A
toUpperCase('3')  // 3
isDigit(c)true if digit: 0-9.
isDigit('x') // false
isDigit('6') // true
toLowerCase(c)Lowercase version
toLowerCase('A')  // a
toLowerCase('a')  // a
toLowerCase('3')  // 3
isWhitespace(c)true if whitespace.
isWhitespace(' ')  // true
isWhitespace('\n') // true
isWhitespace('x')  // false

擷取字符串

String Str = new String("This is text");
 
System.out.print("返回值 :" );
System.out.println(Str.substring(4) );
 
System.out.print("返回值 :" );
System.out.println(Str.substring(4, 10) );

將char轉換為字串的標準方法

String.valueOf(char)

判斷字符是否為數字

System.out.println(Character.isDigit(1)); // 返回false
System.out.println(Character.isDigit("1")); // 返回true

數字

Binary

其實大專時候就有學過二進位轉十進位、十進位轉二進位。但是當時一直學不會,感覺實際上很少用到因此一直沒去理解,這次終於學會怎麼轉換,在這裡只介紹二進位跟十進位互轉,畢竟這是考試的範圍。

十進位轉二進位

主要的用法是我們用2除以該數,而取餘數(由下到上)就是所謂的二進位。要注意最後的1的餘數也要記得算!!

二進位二進位轉十進位

用2作為底數(十進位轉二進位時我們都是用2除)變成: 

對應二進位* 2(index平方) 

比如下圖是,第三個index為1 ,則: 1*2(3平方)

注意* index從0開始,且從右到左

 轉為整數

Integer.parseInt()

Java 中將浮點數舍入到小數點後 2 位

double random = Math.random();
 
        String roundOff = String.format("%.2f", random);
        System.out.println(roundOff);

 取的數字最後幾位

剛開始本來想直接使用substring 但是要知道substring只用於字符串,以下為更簡易的方式

 // 獲取倒數後兩個數字
int lastTowDigit = highwayNumber % 100;

隨機數

 System.out.println("Math.random()=" + Math.random());// 结果是个double类型的值,区间为[0.0,1.0)
        int num = (int) (Math.random() * 3); // 注意不要写成(int)Math.random()*3,这个结果为0,因为先执行了强制转换
        System.out.println("num=" + num);

按照字母數字循環輸出

import java.util.Scanner;

public class LoopPatterns {
   public static void main (String[] args) {
      Scanner scnr = new Scanner(System.in);
      int numRows;
      int numColumns;
      int currentRow;
      char currentRowLetter;
      int currentColumn;
      int currentColumnInteger;
   
      numRows = scnr.nextInt();
      numColumns = scnr.nextInt();

      /* Your code goes here */
      for(int i=1; i<=numRows; i++){
       for(int j=0; j<numColumns; j++){
         currentRowLetter = Character.toUpperCase((char)(96+i));
         currentColumnInteger = j+1;
         System.out.print(String.valueOf(currentRowLetter) + currentColumnInteger + " ");
        }
        System.out.println("");
      }
   }
}

Math.pow(x, y) 平方數

import java.lang.Math;

public class MyClass{
    public static void main(String []args){
       double answer = Math.pow(5, 4);
      // int answer = (int) Math.pow(5, 4); 強制轉換為整數

       System.out.println("5 raised to the power of 4 = " + answer);
       // 5*5*5*5 <= 輸出 5 raised to the power of 4 = 625.0

    }
}

平方根

public class Main {
  public static void main(String[] args) {
       double x = 4.0;
       System.out.printf("sqrt(%.2f) 為 %.2f%n", x, Math.sqrt(x));
       // 輸出為 sqrt(4.00) 為 2.00
  }
}

 絕對值

public class Test{
    public static void main(String args[]){
        Integer a = -8;
        double d = -100;
        float f = -90f;    
                                               
        System.out.println(Math.abs(a));
        System.out.println(Math.abs(d));    
        System.out.println(Math.abs(f));    
        // 8
        // 100.0
        // 90.0
    }
}

數組

建立陣列

int[] x = new int[5];
int[] y = {53, 26, 37, 94};

且若我們需要一個可以儲存n個資料的陣列,習慣上我們會以下程式新增:

// 正確
int[] x = new int[n];

// 錯誤
int[] x = new int[n-1];
public class example{
  public static void main(String[] args){
    int[] x = new int[3];
    x[0] = 32;
    x[1] = 57;
    x[2] = 43;
    for(int i=0;i<=2;i++){
       x[i] += 10;
       System.out.println(x[i]);
    }
    /* 輸出  42
            67
            53
    */
 }
}

二維陣列

public class example{
        public static void main(String[] args){
                int[][] x = new int[3][2];
                x[0][0] = 32; x[0][1] = 84;
                x[1][0] = 57; x[1][1] = 62;
                x[2][0] = 43; x[2][1] = 18;
                for(int i=0;i<=2;i++){
                        for(int j=0;j<=1;j++){
                                x[i][j] += 10;
                                System.out.println(x[i][j]);
                        }
                }
        }
}

       陣列方法 

方法說明
<ArrayList>.add(T)新增元素T進入指定的ArrayList
<ArrayList>.remove(index)刪除位置index的元素,其後的元素會自動補上
<ArrayList>.isEmpty()(boolean)判斷是否為空ArrayList
<ArrayList>.indexOf(T)(int)尋找元素T的位置
<ArrayList>.get(index)(class)取得位置index的元素
<ArrayList>.size()(int)取得大小
<ArrayList>.contains(T)(boolean)是否存在元素T

循環

基本上循環的方法跟javascript中使用的概念相同

for

public class Test {
   public static void main(String[] args) {
 
      for(int x = 0; x < 3; x = x+1) {
         System.out.print("value of x : " + x );
         System.out.print("\n");
      }
   }
}

for循環在Java中增強版:

從Java5,增強的for循環中進行了介紹。這主要是用於數組。

public class Test {

   public static void main(String args[]){
      int [] numbers = {10, 20, 30, 40, 50};

      for(int x : numbers ){
         System.out.print( x );
         System.out.print(",");
      }
      System.out.print("
");
      String [] names ={"James", "Larry", "Tom", "Lacy"};
      for( String name : names ) {
         System.out.print( name );
         System.out.print(",");
      }
      /*
        10,20,30,40,50,
        James,Larry,Tom,Lacy,
      */
   }
}

switch

public class Test {
   public static void main(String args[]){
      //char grade = args[0].charAt(0);
      char grade = 'C';
 
      switch(grade)
      {
         case 'A' :
            System.out.println("优秀"); 
            break;
         case 'B' :
         case 'C' :
            System.out.println("良好");
            break;
         case 'D' :
            System.out.println("及格");
            break;
         case 'F' :
            System.out.println("你需要再努力努力");
            break;
         default :
            System.out.println("未知等级");
      }
      System.out.println("你的等级是 " + grade);
   }
}

while

如果符合括號中的條件則一直循環,直到不在符合條件

public class Test {
   public static void main(String[] args) {
      int x = 10;
      while( x < 20 ) {
         System.out.print("value of x : " + x );
         x++;
         System.out.print("\n");
         /*
            value of x : 10
            value of x : 11
            value of x : 12
            value of x : 13
            value of x : 14
            value of x : 15
            value of x : 16
            value of x : 17
            value of x : 18
            value of x : 19
         */
      }
   }
}

do...while 

對於while語句而言,如果不滿足條件,則不能進入迴圈。但有時候我們需要即使不符合條件,也至少執行一次。
所以 do…while 迴圈至少會執行一次
public class Main {
  public static void main(String[] args) {
      int x = 10;
      do{
        System.out.print("至少輸出一次?");
      }while( x < 9 );
  }
}

關鍵字:

continue - 僅跳出當前循環,繼續下一次循環
public class Main {
  public static void main(String[] args) {
      int [] numbers = {10, 20, 30, 40, 50};
      for(int x : numbers ) {
         if( x == 30 ) {
	      continue;
         }
         System.out.print( x );
         System.out.print(" ");
      }
      System.out.print("done!");
      // 輸出 10 20 40 50 done!
  }
}
break - 用於跳出整段循環 ( 如果是巢狀循環,則循環中使用break語句,只能跳出內層循環,外層循環繼續執行)
public class Main {
  public static void main(String[] args) {
      int [] numbers = {10, 20, 30, 40, 50};
      for(int x : numbers ) {
         if( x == 30 ) {
	      break;
         }
         System.out.print( x );
         System.out.print(" ");
      }
      System.out.print("done!");
    // 輸出 10 20 done!
  }
}

return - 終止循環  ( 如果是請求循環,內部循環中使用返回語句,則外部循環均執行,直接傳回該方法的回傳值))

public class Main {
  public static void main(String[] args) {
      int [] numbers = {10, 20, 30, 40, 50};
      for(int x : numbers ) {
         if( x == 30 ) {
	      return;
         }
         System.out.print( x );
         System.out.print(" ");
      }
      System.out.print("done!");
    // 輸出 10 20
  }
}

列舉 Enum

Java枚舉是一個特殊的類,一般表示一組常數,例如一年的4個季節,一年的12個月份,一個星期的7天,方向有東南西北等。 Java 枚舉類別使用 enum 關鍵字來定義,每個常數使用逗號 , 來分割。

enum Color
{
    RED, GREEN, BLUE;
}
 
public class Test
{
    // 执行输出结果
    public static void main(String[] args)
    {
        Color c1 = Color.RED;
        System.out.println(c1);
        // 輸出 RED
    }
}
列舉優勢

列舉可以讓代碼更加嚴謹,並且避免許多錯誤,例如:

  • 非預期的選項
  • 拼寫錯誤
// 使用enum之前
public class OldGrade {
    public static final int A = 1;
    //以下略……
}

public class OldClass {
    public static final int English = 1;
    //以下略……
}

public class OldStudent {
    public void assignGrade(int grade) {
        //以下略……
    }
}

// 使用enum
public enum NewGrade {
    A, B, C, D, F, INCOMPLETE
}

public enum NewClass {
    ENGLISH, MATH
}

public class NewStudent {
    public void assignGrade(NewGrade grade) {
         //以下略……
    }
}

如此一來在編譯時期就可以檢出錯誤!

student1.assignGrade(NewGrade.A); //正確傳入
student1.assignGrade(NewClass.ENGLISH); //錯誤傳入,容易檢查
​​​​​​​
建構複雜的列舉

定義列舉時可以自定義建構式,但是不得公開(public)或受保護(protected),也不可於建構式中呼叫 super

  •      列舉實例必須最先定義。
  •     最後一個列舉實例必須加上分號(;)。
  •     新屬性不能在列舉實例之前宣告,需在列舉實例之後宣告。
  •      建構子有二個參數,所以每個列舉實例都要傳入二個參數。
  •      建構子是隱含性的private,private修飾詞可寫可不寫,不能變更為public。
public enum Grade {
    // 優先定義列舉實例,傳入二個參數
    A(9, "優異"),
    B(8, "佳"),
    C(7, "良好"),
    D(6, "普通"),
    F(5, "略差"),
    INCOMPLETE(4, "多努力");  // ’;’分號為必要,不可少

    // 新屬性需寫在列舉實例之後
    private int score;
    private String description;

    // 建構子預設為 private,可寫可不寫;不能定義為public
    // 建構子有二個參數,每次必定執行
    Grade(int score, String desc) {
        this.score = score;
        this.description = desc;
    }

    public int getScore() {
        return score;
    }

    public String getDescription() {
        return description;
    }
}
// 1. 取得Grade.A的分數:
int score = Grade.A.getScore(); //9
// 或 
Grade gradeInstance = Grade.A;
int score = gradeInstance.getScore(); //9

// 2. 取得Grade.A的說明:
String desc = Grade.A.getDescription(); //等級C
// 或
Grade gradeInstance = Grade.C;
String desc = gradeInstance.getDescription(); //等級C

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java笔记是由北京大学青鸟教育推出的一款专门针对Java语言的学习工具。它以全面、系统、实践为特点,通过详细的代码示例和清晰的讲解,帮助学习者全面掌握Java编程语言Java笔记采用了线上与线下相结合的学习模式。学员可以通过手机、平板电脑、电脑等设备在线学习,还可以在学习过程中随时记录自己的学习笔记。同时,北大青鸟还为学员提供线下实践环境,学员可以在实验室里亲自动手实践所学知识,加深理解和应用。 Java笔记的内容非常全面,包括了Java语言的基本语法、面向对象编程、异常处理、流操作、多线程、数据库操作等众多知识点。除了理论知识,Java笔记还提供了大量的实例代码,可供学员参考和模仿。这样的学习方式既帮助学员理解Java的基本概念,又能让他们运用所学知识解决实际问题。 与此同时,Java笔记还注重学员的互动交流。在学习过程中,学员可以利用笔记功能记录学习心得和疑惑,还可以在论坛上与其他学员进行讨论和交流。这种互动形式既能促进学员之间的学习互助,也能更好地帮助学员理解和应用所学知识。 总之,Java笔记是北大青鸟推出的一款专注于Java语言学习的工具,通过系统的课程设置、丰富的实例代码和互动交流的方式,帮助学员全面掌握Java编程知识,提升编程能力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值