𝓝𝓮𝓶𝓸&博客

【Java】机考常用操作

注释

首先要说的就是注释,在机考中一定要写注释,不然会扣分。
CTRL + /单行注释//...
CTRL + SHIFT + /多行注释/*...*/
ALT + SHIFT + J添加Javadoc注释

输入输出

输入

JDK 1.5.0新增的Scanner类为输入提供了良好的基础。
一般用法为:

import java.io.* 
import java.util.* 
public class Main {
	public static void main(String args[]) { 
		Scanner cin = new Scanner(new BufferedInputStream(System.in)); 
	}
}

当然也可以直接:

Scanner cin = new Scanner(System.in); //加 Buffer 速度会快一些
  • 读一个整数:int n = cin.nextInt();
    相当于scanf("%d", &n);cin >> n;
  • 读一个字符串:String s = cin.next();
    相当于scanf("%s", s);cin >> s;
  • 读一个浮点数:double t = cin.nextDouble();
    相当于scanf("%lf", &t);cin >> t;
  • 读一整行:String s = cin.nextLine();
    相当于gets(s);cin.getline(...);
  • 判断是否有下一个输入:可以用cin.hasNext()cin.hasNextInt()cin.hasNextDouble()

在刷牛客网时,遇到一类机试(华为机试)是采用ACM模式下的算法,这样针对不同的输入输出就需要有一个大致的了解。

牛客网题目链接:https://ac.nowcoder.com/acm/contest/5657#question

首先对与Java的输入,要用Scanner:

Scanner in = new Scanner(System.in);

读取字符或行:

in.hasNext()
in.hasNextLine()

使用的方法总结:

采用has xxxx的话,后面也要用next xxxx。比如前面用hasNextLine,那么后面要用 nextLine 来处理输入。

具体区别参考:笔试在线判题系统输入输出(剑指Offer类和传统ACM的OJ模式

以下是针对各种输入输出条件下举例实现的Java代码:

特别注意:无论是输入还是输出,我们最终的数据都是一个一个字符串,即使是nextInt(),也是读取某个字符串之后解析为int。

1.多组空格分割的两个整数 (无行数,结束字符限制)

题目描述:

输入包括两个正整数a,b(1 <= a, b <= 10^9),输入数据包括多组。
输出a+b的结果

输入示例:

1 5
10 20

输出示例

6
30
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) { 
            int a = in.nextInt();
            int b = in.nextInt();
            System.out.println(a + b);
        }
    }
}

2.第一行组数接空格分割的两个正整数 (行数限制)

题目描述:

输入第一行包括一个数据组数t(1 <= t <= 100)
接下来每行包括两个正整数a,b(1 <= a, b <= 10^9)
输出a+b的结果

输入示例:

2
1 5
10 20

输出示例:

6
30
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        for(int i = 0; i < num; i++) { // 注意 while 处理多个 case
            int a = in.nextInt();
            int b = in.nextInt();
            System.out.println(a + b);
        }
    }
}

3.空行分割的两个正整数,0 0 结束 (结束符限制)

题目描述:

输入包括两个正整数a,b(1 <= a, b <= 10^9),输入数据有多组, 如果输入为0 0则结束输入
输出a+b的结果

输入示例:

1 5
10 20
0 0

输出示例:

6
30
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        
        while (in.hasNext()) {
            int a = in.nextInt();
            int b = in.nextInt();
            if(a ==0 && b == 0) break;
            System.out.println(a + b);
        }
    }
}

4. 每行第一个为个数后带空格分割整数,0结束 (结束符限制,每行有个数限制)

题目描述:

输入数据包括多组。
每组数据一行,每行的第一个整数为整数的个数n(1 <= n <= 100), n为0的时候结束输入。
接下来n个正整数,即需要求和的每个正整数。

每组数据输出求和的结果

输入示例:

4 1 2 3 4
5 1 2 3 4 5
0

输出示例:

10
15
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        
        while (in.hasNext()) { 
            int n = in.nextInt();
            if(n == 0) break;
            int sum = 0;
            for (int i = 0; i < n; i++) {
                sum += in.nextInt();
            }
            System.out.println(sum);
        }
    }
}

5.第一行组数接第一个个数接空格分开的整数 (行数限制,每行有个数限制)

题目描述:

输入的第一行包括一个正整数t(1 <= t <= 100), 表示数据组数。
接下来t行, 每行一组数据。
每行的第一个整数为整数的个数n(1 <= n <= 100)。
接下来n个正整数, 即需要求和的每个正整数。

每组数据输出求和的结果

输入示例:

2
4 1 2 3 4
5 1 2 3 4 5

输出示例:

10
15
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
    
        Scanner in = new Scanner(System.in);
        
        int num = in.nextInt();
        for (int i = 0; i < num; i++){
            int n = in.nextInt();
            int sum = 0;
            for(int j = 0; j < n; j++){
                sum += in.nextInt();
            }
            System.out.println(sum);
        }
    }
}

6.每行第一个为个数后带空格分割整数 (无结束限制,每行有个数限制)

题目描述:

输入数据有多组, 每行表示一组输入数据。
每行的第一个整数为整数的个数n(1 <= n <= 100)。
接下来n个正整数, 即需要求和的每个正整数。

每组数据输出求和的结果

输入示例:

4 1 2 3 4
5 1 2 3 4 5

输出示例:

10
15
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) { 
            int n = in.nextInt();
            int sum = 0;
            while (n > 0) {
                sum += in.nextInt();
                n--;
            }
            System.out.println(sum);
        }
    }
}

7.多组空格分隔的正整数 (无结束限制,每行无个数限制,需要当作字符串处理)

题目描述:

输入数据有多组, 每行表示一组输入数据。
每行不定有n个整数,空格隔开。(1 <= n <= 100)。

每组数据输出求和的结果

输入示例:

1 2 3
4 5
0 0 0 0 0

输出示例:

6
9
0
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) { 
            String[] s = in.nextLine().split(" ");
            int sum = 0;
            for (int i = 0; i < s.length; i++) {
                sum += Integer.parseInt(s[i]);
            }
            System.out.println(sum);
        }
    }
}
// 扩展:第一行组数接空格分开的多个整数 (有行数限制,每行无个数限制,需要当作字符串处理)
// 需要注意的是:读取行数后,要加一行in.nextLine();再读下面的行。
// eg: 每组数据输出求和的结果
// 3
// 1 2 3
// 4 5
// 0 0 0 0 0
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        in.nextLine();  // 注意:跳过行数所在行
        for (int i = 0; i < num; i++ ){
            String[] s = in.nextLine().split(" ");
            int sum = 0;
            for(int j = 0; j < s.length; j++){
                sum += Integer.parseInt(s[j]);  // 将字符转成整数类型
            }
            System.out.println(sum);
        }
    }
}

8.第一行个数第二行字符串

题目描述:

输入有两行,第一行n
第二行是n个空格隔开的字符串

输出一行排序后的字符串,空格隔开,无结尾空格

输入示例:

5
c d a bb e

输出示例:

a bb c d e
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        in.nextLine();
        while (in.hasNext()) { 
            String[] s = in.nextLine().split(" ");
            Arrays.sort(s);
            for (int i = 0; i < s.length; i++) {
                System.out.print(s[i] + " ");
            }
            
        }
    }
}

9.多行空格分开的字符串

题目描述:

多个测试用例,每个测试用例一行。
每行通过空格隔开,有n个字符,n<100

对于每组测试用例,输出一行排序过的字符串,每个字符串通过空格隔开

输入示例:

a c bb
f dddd
nowcoder

输出示例:

a bb c
dddd f
nowcoder
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) { 
            String[] s = in.nextLine().split(" ");
            Arrays.sort(s);
            for (String c:s) {
                System.out.print(c + " ");
            }
            System.out.println();
        }
    }
}

10.多行逗号分开的字符串 (逗号和空格的区别就是最后一个字符输完的时候",“还是” " )

题目描述:

多个测试用例,每个测试用例一行。
每行通过,隔开,有n个字符,n<100

对于每组用例输出一行排序后的字符串,用','隔开,无结尾空格

输入示例:

a,c,bb
f,dddd
nowcoder

输出示例:

a,bb,c
dddd,f
nowcoder
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
            String[] s = in.nextLine().split(",");
            Arrays.sort(s);
            int l = s.length;
            for (int i = 0; i < l - 1; i++) {
                System.out.print(s[i] + ",");
            }
            System.out.println(s[l-1]);
        }
    }
}

有行数限制,每行无个数限制

输入:

3
1 2 3 4
5 6 7
8

读取:

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int line = in.nextInt();
		// 由于不定长,所以都加入列表容器中比较好
		List<List<Integer>> lists = new ArrayList<>();
		
        for (int i = 0; i < line; i++) {
            String[] strs = in.nextLine().split(" ");
			List<Integer> list = new ArrayList<>();
            for (int j = 0; i < strs.length; j++) {
				list.add(Integer.valueOf(strs[j]));
			}
			lists.add(new ArrayList<>(list));
        }
    }
}

注意

特别注意:无论是输入还是输出,我们最终的数据都是一个一个字符串,即使是nextInt(),也是读取某个字符串之后解析为int。

下面简述一下next() 与 nextLine() 区别:

  • next()nextXxx(): next()会自动消去有效字符前的空格,只返回输入的字符,不能得到带空格的字符串。
  • nextLine():nextLine()方法返回的是Enter键之前的所有字符,它是可以得到带空格的字符串的,可以得到空白。

所以,如果两者连用的话

Scanner in = new Scanner(System.in);
int a = in.nextInt();
int b = in.nextInt();
String str = in.nextLine();

输入:

1 2
(回车)

输出:

1 2 (空字符串)

因为next()的读取顺序是这样的

  • 1 2(回车)
  • [1] 2(回车):nextInt()有效字符串赋值给a
  • 1[ 2](回车):nextInt()有效字符串(自动消去有效字符前的空格)赋值给b
  • 1 2[(回车)]:nextLine()遇到回车,被赋值为空字符串

Java中nextInt()后接nextline()吞回车问题
原因:

  • nextInt()函数在缓冲区中遇到“空格”、“回车符”等空白字符时会将空白字符前的数据读取走,但空白字符不会被处理掉。
  • nextLine()函数是在缓冲区中读取一行数据,这行数据以“回车符”为结束标志,nextLine()会把包括回车符在内的数据取走。
    nextInt()后的nextLine()函数,因为nextInt()将“回车符”留在了缓冲区,nextLine()读取时遇到的第一个字符便是“回车符”,所以直接结束读取。

所以,如果需要避免这种情况,我们可以在两者之间加入一个nextLine()来回收掉回车。

Scanner in = new Scanner(System.in);
int a = in.nextInt();
int b = in.nextInt();
in.nextLine();

String str = in.nextLine();

输出

  • 一般可以直接用:

    • System.out.print():****不换行
    • System.out.println():****换行(line new)

    例如:

    System.out.println(n); // n 为 int 型
    
  • 同一行输出多个整数可以用:

    System.out.println(new Integer(n).toString() + " " + new Integer(m).toString());
    
  • 对于输出浮点数保留几位小数的问题,可以使用DecimalFormat

    import java.text.*; 
    // 这里 0 指一位数字,# 指除 0 以外的数字(用来省略末尾的0)
    DecimalFormat f = new DecimalFormat("#.00#"); 
    DecimalFormat g = new DecimalFormat("0.000"); 
    double a = 123.45678, b = 0.12; 
    System.out.println(f.format(a)); 
    System.out.println(f.format(b)); 
    System.out.println(g.format(b)); 
    

大数字

BigIntegerBigDecimal 是在java.math包中已有的

  • BigInteger表示整数
  • BigDecimal表示浮点数(使用前得先设置 DecimalFormat 类,为大数字设置保留几位小数)

注意:因为大数字不是基本数据类型,所以不能直接用符号运算,如 加(+)减(-)来运算大数字。需要用方法

例如:

(import java.math.*) // 需要引入 java.math 包
BigInteger a = BigInteger.valueOf(100); 
BigInteger b = BigInteger.valueOf(50); 
BigInteger c = a.add(b) // c = a + b; 

主要有以下方法可以使用:

BigInteger add(BigInteger other) 
BigInteger subtract(BigInteger other) 
BigInteger multiply(BigInteger other) 
BigInteger divide(BigInteger other) 
BigInteger mod(BigInteger other) 
int compareTo(BigInteger other) 
static BigInteger valueOf(long x) 
//输出大数字时直接使用 System.out.println(a) 即可。

数组

注意:所有的变量在声明的时候都不会分配内存赋值和实例化才会分配内存
即 Person p;不分配内存,p = null;分配内存。

声明数组

数组直接用new int[5]来给它分配空间。

方法一:

int a[] = null;	//声明一维数组
//int[] a = null; 也行,个人习惯
a = new int[10];//分配内存给一维数组

方法二:

int[] a = new int[10];	//声明数组的同时分配内存

遍历数组

例如:

//一维数组
String[] str = new String[3];
str[0]="张三";
str[1]="李四";
str[2]="王五";

for循环

数组元素下标的合法区间:[0, length-1]。
我们可以用for循环通过下标来遍历数组中的元素,遍历时可以读取元素的值或者修改元素的值。

例如:

// for形式遍历数组
for(int i=0;i<str.length;i++) {
	System.out.println("一维数组:for:"+str[i]);
}

for-each

增强for循环for-each是JDK1.5新增加的功能,专门用于读取数组或集合中所有的元素,即 对数组进行遍历。
格式:对象遍历集合数组

for(类 对象: 集合数组) {
	//操作
}

例如:

// 增强for-each形式,用变量s遍历所有数组
for(String s:str) {
	System.out.println("一维数组增强:for:"+s);
}

注意:foreach不能进行赋值修改操作,毕竟你赋的值都给了变量s,而不是给了数组。
但是根据Java的值传递规则(想要了解具体内容可查看Java值传递),所以我们可以得出以下结论:
如果foreach循环操作的数据类型是基本数据类型,则在foreach中修改数组内容无效;
如果foreach循环操作的数据类型是引用数据类型,则修改数组内容有效。

建议:****foreach只用于遍历(查找),需要操作(增删改)数组时直接使用传统的for循环较好

遍历二维数组元素

for(int i = 0;i < arr4.length;i++){
    for(int j = 0;j < arr4[i].length;j++){
        System.out.print(arr4[i][j] + "  ");
    }
    System.out.println();
}
​```

数组排序

通常情况下我们可以使用Arrays.sort()来对数组进行排序。

例如,我们要对数组排序:

int[] ints={1,4,7,2,5,8,3,6,9};

public class Arrays
extends Object
This class contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists.
The methods in this class all throw a NullPointerException, if the specified array reference is null, except where noted.

The documentation for the methods contained in this class includes briefs description of the implementations. Such descriptions should be regarded as implementation notes, rather than parts of the specification. Implementors should feel free to substitute other algorithms, so long as the specification itself is adhered to. (For example, the algorithm used by sort(Object[]) does not have to be a MergeSort, but it does have to be stable.)

This class is a member of the Java Collections Framework.
上面说的很清楚,是操作数组(manipulating arrays),这就是我们的类叫 Arrays 的原因。

全体升序

Arrays.sort(int[] a)直接对数组进行升序排序
例如:

System.out.println("升序排序:");
Arrays.sort(score);
System.out.println(Arrays.toString(score));	//这里我偷了个懒。。把他变成字符串输出了

程序运行结果:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

部分升序

Array.sort(int[] a , int fromIndex, int toIndex)对数组的从fromIndex到toIndex([from, to))进行升序排序。(前闭后开

例如:

System.out.println("\n部分升序排序:");
int[] ints2 = {1,4,7,2,5,8,3,6,9};

//对数组的[2,6)位进行排序
Arrays.sort(ints2, 2, 6);

//输出
for (int i=0;i<ints2.length;i++)
{
    System.out.print(ints2[i]+" ");
}

程序运行结果:

部分升序排序:
9 8 4 5 6 7 3 2 1 

降序

因为sort()方法默认为升序排序,所以要实现降序排序的话,要新建一个比较器Comparator,从而实现自定义比较。

注意:要实现降序排序,得通过包装类型数组基本类型数组是不行的

Comparator接口可以实现自定义排序,实现Comparator接口时,要重写compare方法
int compare(Object o1, Object o2)返回一个基本类型的整型

  • 如果要按照升序排序,则(其实就是一个数轴,0就是自己,1就比自己大,-1就比自己小)
    • o1小于o2,返回-1负数
    • 相等,返回0
    • o1大于o2,返回1正数
  • 如果要按照降序排序,则
    • o1小于o2,返回1(正数)
    • 相等,返回0
    • o1大于o2,返回-1(负数)

看到这里,可能有人就懵了,凭什么升序是这样安排的,降序是那样安排的呢??

理解:
其实设计compare()的大佬是按照我们正常思维来设计的,即 两个数相比较,小于取负,等于取0,大于取正
设计sort()的大佬也是是按照我们正常思维来设计的,即 升序,从小到大排列。
而设计排序的大佬需要用到这个比较的方法,所以sort()的正常思维升序与compare()的正常思维就相统一了
如果我们要实现降序,只需把compare()方法反过来,即 两个数相比较,小于取正,等于取0,大于取负

或者说,也可以这么理解,要达到升序排列,就得将较大的数移到后面去,与较小的数进行交换,所以大于就为1(即 交换),小于就为-1(即 不交换)。

例如:

System.out.println("\n降序排序:");
//要实现降序排序,得通过包装类型数组,基本类型数组是不行的
Integer[] integers = {1,4,7,2,5,8,3,6,9};
Arrays.sort(integers, new Comparator<Integer>()
{
	public int compare(Integer o1, Integer o2)
	{
//		if(o1 < o2) { 
//			return 1;
//		}else if(o1 > o2) {
//			return -1;
//		}else {
//			return 0;
//		}

		return o2-o1;	//与“小于取正,等于取0,大于取负”相同效果
	}
});

//输出
for (Integer integer:integers)
{
	System.out.print(integer+" ");
}

程序运行结果:

降序排序:
9 8 7 6 5 4 3 2 1 

字符串

String类用来存储字符串。
例如:

String a = "Hello"; 

字符串连接

可以直接用+号,如

String a = "Hello"; 
String b = "world"; 
System.out.println(a + ", " + b + "!"); // output "Hello, world!" 

字符串查找

String提供了两种查找字符串的方法,即 indexOf()lastIndexOf() 方法。

  • indexOf(String s)用于返回参数字符串 s 在指定字符串中首次出现的索引位置
    当调用字符串的indexOf()方法时,会从当前字符串的开始位置搜索 s 的位置。

    • 如果没有检索到字符串 s,该方法返回-1
    String str ="We are students";
    int size = str.indexOf("a"); // 变量 size 的值是 3 
    
  • lastIndexOf(String str)用于返回字符串最后一次出现的索引位置。
    当调用字符串的lastIndexOf()方法时,会从当前字符串的开始位置检索参数字符串 str,并将最后一次出现 str 的索引位置返回。

    • 如果没有检索到字符串 str,该方法返回-1
    • 如果lastIndexOf()方法中的参数是空字符串"",则返回的结果与 length 方法的返回结果相同。

获取指定索引位置的字符

使用charAt()方法可将指定索引处的字符返回。

String str = "Hello world";
char mychar = str.charAt(5); // mychar 的结果是 w 

获取子字符串

通过String类substring()方法可对字符串进行截取。

这些方法的共同点就是都利用字符串的下标进行截取,且应明确字符串下标是从 0 开始的。在字符串中空格占用一个索引位置。

  • substring(int beginIndex)从begin开始,到结尾结束

    String str = "Hello world";
    String substr = str.substring(3); //获取字符串,此时 substr 值为 lo world
    
  • substring(int beginIndex, int endIndex)begin和end区间是前闭后开的,[begin, end)

注意:其实这个区间前闭后开针对字符来说的,看下面举的例子,0~3截取了Hel这三个字符,即 [0, 3),第0、1、2个字符。
- beginIndex:开始截取子字符串的索引位置
- endIndex:子字符串在整个字符串中的结束位置

> **理解:**但是,我们可以**从存储机制去理解**它。
Hello World 在系统里是这样存储的:
![](https://img2020.cnblogs.com/blog/1542615/202003/1542615-20200306201431142-1619575710.png)
我们截取了地址0~3,所以截取了Hel这三个字符。

```
String str = "Hello world";
String substr = str.substring(0,3); //substr 的值为 Hel
```

去除空格

trim()方法返回字符串的副本,清除了左右两端的空格

String str = "        hello           ";
System.out.println(str.trim());
//程序运行结果:hello

字符串替换

replace(String oldChar,String newChar)方法可实现将指定的字符或字符串替换成新的字符或字符串。

  • oldChar:要替换的字符或字符串
  • newChar:用于替换原来字符串的内容

注意:如果要替换的字符 oldChar 在字符串中重复出现多次,replace()方法会将所有 oldChar 全部替换成 newChar。需要注意的是,要替换的字符 oldChar 的大小写要与原字符串中字符的大小写保持一致。

String str= "address";
String newstr = str.replace("a", "A");// newstr 的值为 Address

判断字符串是否相等(切不可使用==)

注意:基本数据类型使用==,而引用数据类型(类)则一般使用equals()

  • equals(String otherstr)
    如果两个字符串具有相同的字符和长度,则使用equals()方法比较时,返回 true。

注意:equals()方法比较时,区分大小写

  • equalsIgnoreCase(String otherstr)

注意:equalsIgnoreCase()方法与equals()类似,不过在比较时忽略了大小写

equals()与==的区别:

  • ==:
    • 如果作用于基本数据类型的变量(如 byte,short,char,int,long,float,double,boolean),则直接比较其存储的“值”是否相等
    • 如果作用于引用类型的变量(如 String类),则比较的是所指向的对象的地址(即 是否指向同一个对象)。
  • equals()方法:是基类Object中的方法,因此对于所有的继承于Object的类都会有该方法。在Object类中,equals()方法是用来比较两个对象的引用是否相等,即 是否指向同一个对象。

是不是感觉equals()在Object类中跟==好像是一样的描述啊??没错,就是一样的,不是我写错了!

Java中Object类是所有类的父类,它里面定义了equals()方法:

public boolean equals(Object obj) {
	return (this == obj);
}

若object1.equals(object2)为true,则表示equals1和equals2实际上是引用同一个对象。

注意:对于equals()方法,equals()方法不能作用于基本数据类型的变量。

  • 如果没有对equals()方法进行重写,则比较的是引用类型的变量所指向的对象的地址;
  • String类对equals方法进行了重写,用来比较指向的字符串对象所存储的字符串内容是否相等
    其他的一些自带的引用数据类型,如 Double,Date,Integer等,都对equals()方法进行了重写,用来比较指向的对象所存储的内容是否相等

按字典顺序比较两个字符串

compareTo()方法为按字典顺序比较两个字符串,该比较基于字符串中各个字符的 Unicode 值,按字典顺序将此 String 对象表示的字符序列与参数字符串所表示的字符序列进行比较。

  • 如果按字典顺序此 String 对象位于参数字符串之前,则比较结果为一个负整数
  • 如果按字典顺序此 String 对象位于参数字符串之后,则比较结果为一个正整数
  • 如果这两个字符串相等,则结果为0.

字母大小写转换

  • 字符串的toLowerCase()方法可将字符串中的所有字符从大写字母改写为小写字母,
  • toUpperCase()方法可将字符串中的小写字母改写为大写字母。
str.toLowerCase();
str.toUpperCase();

字符串分割

使用split()方法可以使字符串按指定的分隔字符或字符串对内容进行分割,并将分割后的结果作为字符串数组返回。

str.split(String regex);:****regex为分割字符串的分割符,也可以使用正则表达式。

注意:没有统一的对字符串进行分割的符号,如果想定义多个分割符,可使用符号“|”。(这个是正则表达式的“或”概念)

例如,“,|=”表示分割符分别为“,”和“=”。

String str = "hello world";
String[] s = str.split(" ");
for(int i=0; i<s.length; i++) {
	System.out.println(s[i]);
}

程序运行结果:

hello
world

字符串变数字

用对应类的parse方法即可,如

String t = "123";
Integer.parseInt(t);

switch case 语句

switch case 语句判断一个变量与一系列值中某个值是否相等,每个值称为一个分支。

当我们遇到多个if语句的时候,可以尝试用switch来简化整个代码。

语法格式:

switch(expression){
    case value:
       // 语句
       break; // 可选
    case value:
       // 语句
       break; // 可选
	case value:
	case value:
		// 语句(前两个判断的公共语句)
		break;
    //你可以有任意数量的case语句
    default: // 默认(可选)
       // 语句
}

语句规则:

  • switch 语句中的变量类型可以是: byte、short、int 或者 char。从 Java SE 7 开始,switch 支持字符串 String 类型了。
    同时 case 标签必须为常量 或 字面常量。

  • switch 语句可以拥有多个 case 语句。每个 case 后面跟一个要比较的值和冒号。

  • case 语句中的值的数据类型必须与变量的数据类型相同,而且只能是常量或者字面常量。

  • 当变量的值与 case 语句的值相等时,那么 case 语句之后的语句开始执行,直到 break 语句出现才会跳出 switch 语句。

  • 当遇到 break 语句时,switch 语句终止。程序跳转到 switch 语句后面的语句执行。case 语句不必须要包含 break 语句。
    如果没有 break 语句出现,程序会继续执行下一条 case 语句,直到出现 break 语句。

  • switch 语句可以包含一个 default 分支,该分支一般是 switch 语句的最后一个分支(可以在任何位置,但建议在最后一个)。default 在没有 case 语句的值和变量值相等的时候执行。default 分支不需要 break 语句

  • switch case 执行时,一定会先进行匹配,匹配成功返回当前 case 的值,再根据是否有 break,判断是否继续输出,或是跳出判断。

实例:

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':	// 如果没有 break 语句出现,程序会继续执行下一条 case 语句,直到出现 break 语句。
         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);
   }
}

程序运行结果:

良好
你的等级是 C

调用递归(或其他动态方法)

在主类中 main 方法必须是 public static void 的,在 main 中调用非 static 类时会有警告信息,可以先建立对象,然后通过对象调用方法。

其他注意的事项

  • Java 是面向对象的语言,思考方法需要变换一下,里面的函数统称为方法,不要搞错。
  • Java 里的数组有些变动,多维数组的内部其实都是指针,所以 Java 不支持 fill 多维数组

注意:数组定义后必须初始化,如 int[] a = new int[100];

  • 布尔类型为 boolean,只有 true 和 false 二值,在 if (...) / while (...) 等语句的条件中必须为 boolean 类型。

注意:在 C/C++中的 if (n % 2) 在 Java 中无法编译通过。

  • 下面在 java.util 包里 Arrays类的几个方法可替代 C/C++里的 memset、qsort/sort

    int[] a = {9,8,7,6,5,4,3,2,1};
    Arrays.sort(a) //java 自带的优化后的快速排序
    Arrays.fill(a, 3);	//用3填充数组,结果为3,3,3,3,3,3,3,3,3
    

注意:Arrays类,不是Array类。
数组类Array:Java中最基本的一个存储结构。
Array代表的是一个数组类型
静态类Arrays:专门用来操作array,提供搜索、排序、复制等静态方法。
Arrays代表的是能操作数组们(所有数组)

posted @ 2020-03-07 17:38  Nemo&  阅读(952)  评论(0编辑  收藏  举报