Java核心技术笔记(2)

1、字符串

String类的substring方法可以从一个较大的字符串中提取一个子串,

public class Test {

	public static void main(String[] args) {
		String a="hello";
		String s=a.substring(0, 3);
		System.out.println(s);//结果为hel
	}
}

子串hel的长度为 3,3-0=3

当一个字符串与一个非字符串进行拼接的时候,后者会转成字符串。

public class Test {

	public static void main(String[] args) {
		int age=13;
		String a="hello"+age;
		System.out.println(a);//结果为hello13
	}
}

2、检测字符串是否相等

使用equals方法检测两个字符串是否相等。

对于表达式s.equals(t),如果字符串s和字符串t相等返回true,否则返回false。

如果不区分大小写可以使用equalsIgnoreCase方法。

不可以使用==这个方法。这个是判断两个字符串是否放在同一个位置。

3、输入

import java.util.Scanner;

public class Test {

	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
		String name=in.nextLine();//nextLine方法是输入一行可能包含空格
		System.out.println(name);
	}
}

如果想输入一个单词以空白符为分隔符,就调用String name=in.next();

读取一个整数就调用nextInt()方法

int age=in.nextInt();

读取浮点数就调用nextDouble()方法

Scanner类定义在

import java.util.*;
发布了137 篇原创文章 · 获赞 3 · 访问量 4867

猜你喜欢

转载自blog.csdn.net/qq_38054511/article/details/104228625
今日推荐