OO

Java入门

基本语法

Posted by Chen Jinhao on January 22, 2022

Java入门

输入输出

  • in.next()读入下一个单词
  • in.nextInt()读入下一个整数
  • in.nextLine()读入下一行
  • System.out.print()输出
  • System.out.println()输出并换行
package hello;

import java.util.Scanner;

public class Hello {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("hello");
		Scanner in=new Scanner(System.in);
		final int amount = 100;
		int price=in.nextInt();
		System.out.println(amount+"-"+price+"="+(amount-price));
	}
}

数组

数组的定义:$<类型>[\space]<名字> = new<类型>[元素个数]$

int[] numbers= new int[105];
  • 数组的元素个数可以是变量

    int n;
    n=in.nextInt();
    int[] numbers= new int[n];
    
  • 二维数组

    int[][] a = new int[3][5];
    

循环

  • for循环与while循环与C++相同

  • for-each循环遍历数组也可以for(int k: data)(只读)

函数

函数的定义:$<返回类型> <方法名称>(<参数表>) {<方法体>}$

public static void print_hello()
{
	System.out.println("hello");
	return;
}

包裹类型

基础类型 包裹类型
boolean Boolean
char Character
int Integer
double Double

常见的使用方式如下:

System.out.println(Integer.MAX_VALUE);
System.out.println(Character.isDigit('1'));
System.out.println(Character.isLetter('A'));
System.out.println(Character.isLetterOrDigit('1'));
System.out.println(Character.isLowerCase('a'));
System.out.println(Character.isUpperCase('A'));
System.out.println(Character.isWhiteSpace(' '));
System.out.println(Character.toLowerCase('A'));
System.out.println(Character.toUpperCase('a'));

Math类

  • abs绝对值
  • pow幂次
  • random随机数(0-1之间)
  • round四舍五入

字符串

  • 字符串的创建

    String s = new String("a string");
    String s = "a string";
    
  • 判断字符串相等不能用“==”

    String s = in.nextLine();
    System.out.println(s.equals("bye"));
    
  • 字符串的比较大小

    System.out.println(s1.compareTo(s2));
    System.out.println(s1.compareToIgnoreCase(s2));//不区分大小写
    
  • 字符串的长度s.length()

  • 访问String里的字符s.charAt(index)(不能用for-each循环来遍历)

  • 获得子串

    System.out.println(s.substring(n));//从n号位置到末尾
    System.out.println(s.substring(b,e));//从b号位置到e-1号位置
    
  • 寻找字符

    s.indexOf(c)寻找字符c,找不到返回-1

    s.indexOf(c,n)从n号位置开始寻找字符c

    s.indexOf(t)寻找字符串t

    s.lastIndexOf(c)从右边开始找(其余同理)

  • 其他String操作(注意对String的操作不会改动原字符串而是创建了新的字符串

    s.startsWith(t)判断是否以t开头

    s.endsWith(t)判断是否以t结尾

    s.trim()去掉首尾的空格

    s.replace(c1,c2)将所有的c1替换成c2

    s.toLowerCase()全部变成小写

    s.toUpperCase()全部变成大写