目录内容较多,如果您一时没有检索到想要的内容,我表示很抱歉,诚邀您和我们一起加入每日一练QQ群聊(1070868149),我们互相督促,共同提高。
文章目录
- 00001、判断用户输入的数字是否在已知的数中
- 00002、观察程序的输出结果
- 00003、了解基本数据类型的取值范围
- 00004、给出汉字“你”“我”“他”在Unicode中的位置
- 00005、编写一个应用程序,输出全部的希腊字母
- 00006、根据用户要求的级别和密码长度,随机产生密码
- 00007、输入年月日,判断是今天是今年的第几天
- 00008、输出一个范围内的素数
- 00009、求任意两个正整数的最大公约数和最小公倍数
- 00010、break与continue的比较
- 00011、Scanner 类中hasNextDouble()等方法的用法
- 00012、编写应用程序求1!+ 2!+…… 10!
- 00013、分别用do-while和for循环计算1 + 1/2!+ 1/3!+ ……的前20项和
- 00014、如果一个数恰好等于它的因子之和,这个数就成为完数,编写程序求解1000之内的所有完数
- 00015、使用for循环语句计算8 +88 + 888 +……前10项之和
- 00016、输出满足1+2+3+……n<8888的最大整数n
- 00017、java中对于同一个类的不同对象,可以进行赋值操作
- 00018、计算任意几个数的和
- 00019、创建一个圆锥,要求底面积封装成一个对象
- 00020、输入一个数,判断这个数是否在已知数组中
- 00021、展示当前机器上的时间
- 00022、转换字符数组中的大小写
- 00023、创建一个对象数组并对每个对象的属性值进行操作
- 00024、验证_类的字节码进入内存,类中的静态块儿就会被立即执行
- 00025、设计一个CPU、Text、PC、HardDisk,其中Text是主类
- 00026、抽象类声明的对象可以成为其子类对象的上转型对象,调用子类重写的方法
- 00027、String两个常用的构造方法:String(char[] a)和String(char[] a, int startIndex, int count)
- 00028、字符串的并置——存放在动态区还是常量池?
- 00029、String类中常用方法(1)_public int length()
- 00030、String类中常用方法(2)_public boolean equals(String s)
- 00031、String类中常用方法(3)_public boolean startsWith(String s)、public boolean endsWith(String s)
- 00032、String类中常用方法(4)_public int compareTo(String s)、public int compareToIgnoreCase(String s)
- 00033、按照字典序列对String数组进行排序
- 00034、String类中常用方法(5)_public boolean contains(String s)
- 00035、String类中常用方法(6)_public int indexOf(String s) 、public int lastIndexOf(String s)、public int indexOf(String str, int startpoint)
- 00036、String类中常用方法(7)_public String substring(int Satrtpoint)
- 00037、String类中常用方法(8)_public String trim()
00001、判断用户输入的数字是否在已知的数中
/*
* Objective: to find whether there is a number in a pile
* Time: 19/5/2021
* Author: Lanyan
* */
import java.util.*;
public class Review00001 {
public static void main(String[] args) {
int start = 0, end, middle;
int[] a = {12, 45, 67, 89, 123, -45, 67}; // Building an array —— the pile
for(int i = 0; i < a.length; i++) {
for(int j = i + 1;j < a.length; j++) {
if(a[i] > a[j]) {
int t = a[i]; a[i] = a[j]; a[j] = t; //From left to right, from small to large
}
}
}
Scanner scanner = new Scanner(System.in);
System.out.println("Please input a number that you want search:");
int number = scanner.nextInt();
int count = 0;
end = a.length;
middle = (start + end)/2;
while(number != a[middle]) { //find number by dichotomy
if(number > a[middle]) start = middle;
else if(number < a[middle]) end = middle;
middle = (start + end)/2;
count++;
if(count>a.length/2) break;
}
if(count > a.length/2) //output the result;
System.out.printf("%d is not in the array",number);
else
System.out.printf("%d is int the array",number);
}
}
运行结果:
00002、观察程序的输出结果
/*
* Objective: Observe the output of the program
* Time: 20/05/2021
* Author: Lanyan
* */
public class Review00002 {
public static void main(String[] args) {
for(int i = 20302; i<=20322; i++) {
System.out.print((char)i);
}
}
}
运行结果:
00003、了解基本数据类型的取值范围
/*
* Objective: Understand the range of values for basic data types
* Time: 20/5/2021
* Author: Lanyan
* */
public class Review003 {
public static void main(String[] args) {
System.out.println("The range of byte is:"+ Byte.MIN_VALUE + " to " + Byte.MAX_VALUE);
System.out.println("The range of short is:"+ Short.MIN_VALUE + " to " + Short.MAX_VALUE);
System.out.println("The range of int is:"+ Integer.MIN_VALUE + " to " + Integer.MAX_VALUE);
System.out.println("The range of long is:" + Long.MIN_VALUE + " to " + Long.MAX_VALUE);
System.out.println("The range of float is:" + Float.MIN_VALUE + " to " + Float.MAX_VALUE);
System.out.println("The range of Double is:" + Double.MIN_VALUE + " to " + Double.MAX_VALUE);
}
}
运行结果:
00004、给出汉字“你”“我”“他”在Unicode中的位置
/*
* Objective: Find out the Unicode number of '你''我''他'
* Time: 20/05/2021
* Author: Lanyan
* */
public class Review00004 {
public static void main(String[] args) {
char p1 = '你';
char p2 = '我';
char p3 = '他';
System.out.println("你 ———>"+ (short)p1);
System.out.println("我 ———>"+ (short)p2);
System.out.println("他 ———>"+ (short)p3);
}
}
运行结果:
00005、编写一个应用程序,输出全部的希腊字母
/*
* Objective: Output all the Greek letter
* Time: 20/05/2021
* Author: Lanyan
* */
public class Review00005 {
public static void main(String[] args) {
int startGletter = 879, endGletter = 1024; //the start number and end number of the Greek letter
for(int i = startGletter + 1; i< endGletter; i++) {
System.out.print("| "+(char)i+" ");
if(((i-startGletter)%12 == 0) && (i!=startGletter)) { //Control output format
System.out.print("|\n");
System.out.println("——————————————————————————————————————————————————");
}
}
}
}
运行结果:
00006、根据用户要求的级别和密码长度,随机产生密码
/*
* Objective: Random password generator
* Time: 21/5/2021
* Author: Lanyan
* */
import java.util.*;
public class Review00006 {
public static void main(String[] args) {
System.out.println("What strength password do you want? Please select:");
System.out.println("A: COMMON, only have numbers!");
System.out.println("B: ENHANCE, it's a sequence of mix number and normal string!");
System.out.println("C: SUPERSTRONG, it's not only have number, normal string, and rare character!");
Scanner scanner = new Scanner(System.in);
String slection = scanner.next();
System.out.println("Please input the number of password's bits:");
int bitPassword = scanner.nextInt();
switch(slection) {
case "A":
System.out.println("Password generation successful!\nYour psssword:"+ getRandomNumStr(bitPassword));
break;
case "B":
System.out.println("Password generation successful!\nYour psssword:"+ getRandomCharStr1(bitPassword));
break;
case "C":
System.out.println("Password generation successful!\nYour psssword:"+ getRandomCharStr2(bitPassword));
break;
}
}
static String getRandomNumStr(int n) { //Generates a random sequence of numbers
Random random = new Random();
StringBuilder randomStr = new StringBuilder();
for (int i = 0; i < n; i++) {
randomStr.append(random.nextInt(10));
}
return randomStr.toString();
}
public static String getRandomCharStr1(int n) { //Generates a random sequence of mix number with normal string
String codes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random random = new Random();
StringBuilder randomStr = new StringBuilder();
for (int i = 0; i < n; i++) {
randomStr.append(codes.charAt(random.nextInt(62)));
}
return randomStr.toString();
}
public static String getRandomCharStr2(int n) { //Generates a random sequence of mix number with rare string
String codes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+=";
Random random = new Random();
StringBuilder randomStr = new StringBuilder();
for (int i = 0; i < n; i++) {
randomStr.append(codes.charAt(random.nextInt(75)));
}
return randomStr.toString();
}
}
运行结果:
A级密码(6):
B级密码(12):
C级密码(18):
00007、输入年月日,判断是今天是今年的第几天
/*
* Objective: to find what's the day of this year
* Time: 22/5/2021
* Author: Lanyan
* */
import java.util.*;
public class Review00007 {
public static void main(String[] args) {
int day, month, year, num = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("请依次输入年、月、日");
year = scanner.nextInt();
month = scanner.nextInt();
day = scanner.nextInt();
switch (month) {
case 12:num += 30;
case 11:num += 31;
case 10:num += 30;
case 9:num += 31;
case 8:num += 31;
case 7:num += 30;
case 6:num += 31;
case 5:num += 30;
case 4:num += 31;
case 3:num += 28;
case 2:num += 31; //一月份加0天
case 0:num += day;break;
}
if (((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) && (month > 2)) //判断是不是闰年
num++;
System.out.printf("这一天是这一年的第%d天", num);
}
}
运行结果
00008、输出一个范围内的素数
/*
* Objective: to fine prime within the range
* Time: 23/05/2021
* Author:lanyan
* */
import java.util.*;
public class Review00007 {
public static void main(String[] args) {
System.out.println("Please input the range:");
Scanner scanner = new Scanner(System.in); //input the range
int range = scanner.nextInt();
if(range < 2)
System.out.println("there is no prime numbers under 2!");
else {
int i = 2, j = 2; //There is no prime numbers under 2, so the start of i is 2,
for(i = 2; i<=range; i++) { //Iterate through all the numbers in the range
for(j = 2; j<=i/2; j++)
if(i%j==0) break; //once exist,break out of this loop
if(j>i/2) System.out.print(i + " ");
}
}
}
}
运行结果:
00009、求任意两个正整数的最大公约数和最小公倍数
package fundNumber;
import java.util.*;
public class Main {
public static void main(String[] args) {
System.out.println("Please input the numbers:");
Scanner scanner = new Scanner(System.in);
int number1 = scanner.nextInt();
int number2 = scanner.nextInt();
System.out.println("The maximum common factor is :" + MaxcommonFactor.factor(number1, number2));
System.out.println("The minimum common factor is :" + MincommonMultiple.factor(number1, number2));
}
}
package fundNumber;
class MaxcommonFactor {
/*find the maximum common factor*/
public static int factor(int number1, int number2) {
int maxcomFactor = 0;
for(int i = 1; i<=(number1 > number2 ? number2 : number1); i++) {
if((number1 % i == 0) && (number2 % i == 0)) maxcomFactor = i;
}
return maxcomFactor;
}
}
package fundNumber;
class MincommonMultiple {
/*find the minimum common Multiple*/
public static int factor(int number1, int number2) {
int mincomMultiple = 0;
for(int i = (number1 > number2 ? number1 : number2); i<=number1*number2; i++) {
if((i % number1 == 0) && (i % number2 == 0)) {
mincomMultiple = i;
break; //make sure the number is the minimum
}
}
return mincomMultiple;
}
}
运行结果:
00010、break与continue的比较
/*
* Objective: The difference of break and continue
* Time: 25/05/2021
* Author: Lanyan
* */
public class Review00008 {
public static void main(String[] args) {
int sum = 0;
/*The continue*/
for(int i = 1; i<=10; i++) {
if(i%2 == 0) continue; //calculate 1 + 3 + 5 +7 +9
sum +=i;
}
System.out.println("sum = " + sum);
/*The break*/
int i, j;
for(i = 2; i<=100; i++) { //find the number of primes up to 100
for(j = 2; j<=i/2; j++)
if(i%j == 0) break;
if(j>i/2) System.out.print(i + " ");
}
}
}
运行结果:
00011、Scanner 类中hasNextDouble()等方法的用法
/*
* Objective: to judge if the type of the number is useful
* Author: Lanyan
* Time: 27/05/2021
* */
import java.util.*;
public class Review00009 {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
double sum = 0;
int n = 0;
while(scanner.hasNextDouble()) {
double x = scanner.nextDouble();
n++;
sum += x;
}
System.out.printf("the sum of %d numbers is:\n",n,sum);
System.out.printf("the average of the numbers is: %f\n",sum/n);
}
}
import java.util.*;
public class Review00009 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
if(scanner.hasNextDouble()) {
System.out.println(scanner.nextDouble());
}
if(scanner.hasNextInt()){
System.out.println(scanner.nextInt());
}
}
}
运行结果(分别对应上下两个程序):
结果分析:
- Scanner需要创建对象来调用方法;
- hasNextByte()、hasNextInt()、hasNextLong()、hasNextDouble()输出的值是boolean型,若键入的值在其范围,则是真,否则假,如输入带小数点的值3.14,hasNextDouble()为true,hasNextByte()、hasNextInt()、hasNextLong()为false;
- 程序运行至hasNextDouble()已经要求输入数据,并对输入的数据进行判断,如果为真,进行下一步操作;
- 从键盘输入数据时,经常用scanner对象先调用hasNextXXX()方法等待用户在键盘输入数据,然后再调用nextXXX()方法获取用书输入的数据。
00012、编写应用程序求1!+ 2!+…… 10!
/*
* Objective: calculating factorial of 1!+ 2!+…… 10!
* Author: Lanyan
* Time: 27/05/2021
* */
public class Review00010 {
public static void main(String[] args) {
int num = 1;
int sum = 0;
for(int i = 1; i<=10; i++) {
for(int j = 1; j<=i; j++) num*=j;
sum+=num;
}
System.out.println("the result is:"+sum);
}
}
运行结果:
00013、分别用do-while和for循环计算1 + 1/2!+ 1/3!+ ……的前20项和
/*
* Objective: use do-while or for circle calculate 1 + 1/2!+ 1/3!+ ……1/20!
* Author: Lanyan
* time: 27/05/2021
* */
/*
* Objective: use do-while or for circle calculate 1 + 1/2!+ 1/3!+ ……1/20!
* Author: Lanyan
* time: 27/05/2021
* */
public class Review00011 {
public static void main(String args[]) {
double sum1 = 0, i = 1, a = 1;
do {
sum1 += a;
i++;
a*=(1/i);
}while(i<=20);
System.out.println("The result of do-while:" + sum1);
double sum2 = 0, j, b = 1;
for(j = 1; j<=20; j++) {
b*=(1/j);
sum2 +=b;
}
System.out.println("The result of for:" + sum1);
}
}
运行结果:
程序分析:
出现阶乘时要注意范围问题,本次问题可以转换为小数来求解。
00014、如果一个数恰好等于它的因子之和,这个数就成为完数,编写程序求解1000之内的所有完数
/*
* Objective: Find all the beauty numbers under 1000
* Author: Lanyan
* Time: 28/05/2021
* */
public class BeautyNumber {
public static void main(String[] args) {
int sum; //record the sum of factor
int i, j;
for(i = 1; i<=1000; i++) {
for(j = 1, sum = 0; j<i; j++) {
if(i%j == 0) sum+=j;
}
if(sum == i) //judge the beauty number
System.out.print(" "+i);
}
}
}
运行结果:
程序注意:
每次要将sum归零,这个很重要。
00015、使用for循环语句计算8 +88 + 888 +……前10项之和
/*
* Objective: calculate the sum of 8 + 88 + 888 + ……8x10
* Author: Lanyan
* Time: 28/05/2021
* */
public class Sum888 {
public static void main(String[] args) {
long sum = 0;
int unit = 8;
for(int i = 1; i<=10; i++) {
sum+=unit;
unit = unit*10 + 8;
}
System.out.println("sum = "+sum);
}
}
运行结果:
00016、输出满足1+2+3+……n<8888的最大整数n
/*
* Objective: find the n of 1+2+3+……n<8888
* Author: Lanyan
* Time: 28/05/2021
* */
public class Maximum {
public static void main(String[] args) {
int i, sum = 0;
for(i = 1; i<8888; i++) {
sum += i;
if(sum>=8888) break;
}
System.out.println("The maximum number is:" + (i-1));
}
}
运行结果:
程序注意:
求最大整数等边界类问题时要注意变量值的临界点。
00017、java中对于同一个类的不同对象,可以进行赋值操作
/*
* Objective: the different objects of the same class can assignment by each other
* Author: Lanyan
* Time: 29/05/2021
* */
package point;
public class Main {
public static void main(String[] args) {
Point p1, p2;
p1 = new Point();
p2 = new Point();
System.out.println("The quote of p1:"+p1);
System.out.println("The quote of p1:"+p2);
p1.setXY(11, 22);
p2.setXY(-11, -2);
System.out.println("The x-coordinate of p1:"+p1.x );
System.out.println("The y-coordinate of p1:"+p1.y );
System.out.println("The x-coordinate of p2:"+p2.x );
System.out.println("The y-coordinate of p2:"+p2.y );
p1 = p2;
System.out.println("p2 assignment to p1:\n");
System.out.println("The quote of p1:"+p1);
System.out.println("The quote of p1:"+p2);
System.out.println("The x-coordinate of p1:"+p1.x );
System.out.println("The y-coordinate of p1:"+p1.y );
System.out.println("The x-coordinate of p2:"+p2.x );
System.out.println("The y-coordinate of p2:"+p2.y );
}
}
package point;
public class Point {
int x, y;
void setXY(int m, int n) {
x = m;
y = n;
}
}
运行结果:
00018、计算任意几个数的和
/*Objective: calculate the sum of any number
*Author: Lanyan
*Time: 29/05/2021
* */
public class Sum {
public static void main(String[] args) {
System.out.println(getSum(1,2,3));
System.out.println(getSum(1,2,3,4));
}
static int getSum(int ...x) {
int sum = 0;
for(int n:x) {
sum += n;
}
return sum;
}
}
00019、创建一个圆锥,要求底面积封装成一个对象
/*
* Objective: Combination and reuse
* Author: Lanyan
* Time: 30/05/2021
* */
package Combination;
public class Main {
public static void main(String[] args) {
Circle circle = new Circle(); //Create a circle entity
circle.setRadius(10); //Set radius by circle
Circular circular = new Circular(); //Create a circular entity
System.out.println("the link of circle:"+ circle);
System.out.println("the link of circular:"+ circular);
circular.setHeight(5);
circular.setBottom(circle);
System.out.println("the link of circle:"+ circle);
System.out.println("the link of circular:"+ circular);
System.out.println("motivate the radius of circle, the circle of circular also changed");
circle.setRadius(20);
System.out.println("The circle of bottom"+ circular.getVolumeRadius());
System.out.println("creat the circle again, and the link to the circle will changed");
circle = new Circle();
System.out.println("the link of circle:"+ circle);
System.out.println("but not afftet for cirlular to use");
System.out.println("the link of circular.bottom:"+ circular.bottom);
}
}
package Combination;
public class Circle {
double radius, area;
void setRadius(double r) {
radius = r;
}
double getRadius() {
return radius;
}
double getArea() {
return 3.14*radius*radius;
}
}
package Combination;
public class Circular {
Circle bottom; //Encapsulates the bottom as an object
double height;
void setBottom(Circle c) {
bottom = c;
}
void setHeight(double h) {
height = h;
}
double getVolume() {
if(bottom == null) return -1;
else return bottom.getArea()*height/3.0;
}
double getVolumeRadius() {
return bottom.radius;
}
public void setBottomRadius(double r) {
bottom.setRadius(r);
}
}
运行结果:
00020、输入一个数,判断这个数是否在已知数组中
/*
* Objective: find a number weather in a array or not
* Author: Lanyan
* Time: 30/05/2021
* */
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in) ;
int[] a = {12,34,9,23,45,90,123,19,34};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
System.out.println("Please input a number, jarge weather the number in the array or not:");
int number = scanner.nextInt();
int index = Arrays.binarySearch(a, number);
if(index >= 0)
System.out.println("the a[" + index +"] is " + number + ";");
else {
System.out.println("There is no "+ number +"in the array.");
}
}
}
运行结果:
00021、展示当前机器上的时间
/*
* Objective: show the time of this machine
* Author: Lanyan
* Time: 31/05/2021
* */
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date date = new Date();
System.out.println("The time of this machine is: " + date.toString());
}
}
运行结果:
00022、转换字符数组中的大小写
public class BssicPackage {
public static void main(String[] args) {
char[] a = {'a', 'b', 'c', 'D', 'E', 'F'};
for(int i = 0; i< a.length; i++){
if(Character.isLowerCase(a[i]))
a[i] = Character.toUpperCase(a[i]);
else if(Character.isUpperCase(a[i]))
a[i] = Character.toLowerCase(a[i]);
}
for(int i = 0; i<a.length; i++){
System.out.print(" " + a[i]);
}
}
}
运行结果:
00023、创建一个对象数组并对每个对象的属性值进行操作
package objectArray;
public class Main {
public static void main(String[] args) {
Student[] stu = new Student[10];
for(int i = 0; i<stu.length; i++){
stu[i] = new Student(i + 100);
}
for(int i = 0; i< stu.length; i++){
System.out.print(stu[i].number + " ");
}
}
}
package objectArray;
public class Student {
int number;
Student(int numeber){ //construction method
this.number = numeber;
}
}
运行结果:
00024、验证_类的字节码进入内存,类中的静态块儿就会被立即执行
public class Main {
static{
System.out.println("first");
}
public static void main(String[] args) {
AAA a = new AAA(); //static block enter the memory
System.out.println("third");
}
}
class AAA{
static {
System.out.println("second");
}
}
00025、设计一个CPU、Text、PC、HardDisk,其中Text是主类
package computer;
public class Text {
public static void main(String[] args) {
CPU cpu = new CPU();
HardDisk disk = new HardDisk();
cpu.setSpeed(2200);
disk.setAmount(200);
PC pc = new PC();
pc.setCpu(cpu);
pc.setHD(disk);
pc.show();
}
}
package computer;
public class PC {
private CPU cpu;
private HardDisk HD;
public void setCpu(CPU cpu) {
this.cpu = cpu;
}
public void setHD(HardDisk HD) {
this.HD = HD;
}
public void show(){
System.out.println("Speed is: "+cpu.getSpeed());
System.out.println("HardDisk is: "+HD.getAmount());
}
}
package computer;
public class CPU {
private int speed;
public void setSpeed(int m){
speed = m;
}
public int getSpeed(){
return speed;
}
}
package computer;
public class HardDisk {
private int amount;
public void setAmount(int m){
amount = m;
}
public int getAmount(){
return amount;
}
}
运行结果:
00026、抽象类声明的对象可以成为其子类对象的上转型对象,调用子类重写的方法
package abstractClass;
public class Main {
public static void main(String[] args) {
GileFriend girl = new ChinaGirlfriend(); //transition
Boy boy = new Boy();
boy.setGirlfriend(girl);
boy.showGirlFriend();
girl = new AmericanGirlfriend(); //transition
boy.setGirlfriend(girl);
boy.showGirlFriend();
}
}
package abstractClass;
public class Boy {
GileFriend friend;
void setGirlfriend(GileFriend friend){
this.friend = friend;
}
void showGirlFriend(){
friend.speak();
friend.cooking();
}
}
package abstractClass;
public abstract class GileFriend {
abstract void speak();
abstract void cooking();
}
package abstractClass;
public class ChinaGirlfriend extends GileFriend{
void speak(){
System.out.println("你好");
}
void cooking(){
System.out.println("水煮鱼");
}
}
package abstractClass;
public class AmericanGirlfriend extends GileFriend{
void speak(){
System.out.println("Hello");
}
void cooking(){
System.out.println("Roast beef");
}
}
运行结果:
00027、String两个常用的构造方法:String(char[] a)和String(char[] a, int startIndex, int count)
public class Main {
public static void main(String[] args) {
char[] a = {'j', 'a', 'v', 'a'};
String s = new String(a);
System.out.println(s);
char[] b = {'h', 'e', 'l', 'l', 'o'};
String q = new String(b, 0, 3);
System.out.println(q);
}
}
运行结果:
00028、字符串的并置——存放在动态区还是常量池?
public class Main {
public static void main(String[] args) {
String hello = "你好";
String text_1 = "你" + "好";
System.out.println(hello == text_1); //text_1中参与并置的都是常量,所以并置结果也是常量,会被存放在常量池
System.out.println("你好" == text_1);
System.out.println("你好" == hello);
String you = "你";
String hi = "好";
String text_2 = you + hi;
System.out.println(text_2 == hello); //text_2中参与并置的成员存在变量,所以并置结果会存放在动态区(存放结果的引用和实例)
String text_3 = you + hi;
System.out.println(text_3 == text_2); //text_2和text_3是分别产生的两个String对象
}
}
运行结果:
结果分析:
String可以通过“+”进行并置运算,但需要注意的是,参与并置运算的String对象,只要有一个是变量,那么Java就会在动态区存放所得到的String对象的实例和引用,如果是两个常量参与并置运算,那么得到的结果仍然是常量,如果常量池没有这个常量就放进常量池中。
00029、String类中常用方法(1)_public int length()
public class LengthMethod {
public static void main(String[] args) {
String china = "1945年抗战胜利";
int n1, n2;
n1 = china.length();
n2 = "小鸟bird".length();
System.out.println(n1);
System.out.println(n2);
}
}
方法作用:
获取一个String对象的字符序列的长度
运行结果:
00030、String类中常用方法(2)_public boolean equals(String s)
public class equalsMethod {
public static void main(String[] args) {
String tom = new String("天道酬勤");
String bot = new String("知心朋友");
String jerry = new String("天道酬勤");
String jean = "天道酬勤";
System.out.println(tom.equals(bot));
System.out.println(tom.equals(jerry));
System.out.println(tom.equals(jean));
}
}
方法作用:
比较两个string对象的字符序列是否一样
运行结果:
注意:
对字符串进行比较时不能使用"tom == jerry"这种方式,因为这是对字符串的引用在进行比较。
00031、String类中常用方法(3)_public boolean startsWith(String s)、public boolean endsWith(String s)
public class StartAndEndMethod {
public static void main(String[] args) {
String tom = "天气预报,阴有小雨";
String jerry = "比赛结果,中国队赢得胜利";
System.out.println(tom.endsWith("小雨"));
System.out.println(jerry.startsWith("胜利"));
}
}
方法作用:
判断一个目标字符串的前缀或者后缀是否有想要的字符
运行结果:
00032、String类中常用方法(4)_public int compareTo(String s)、public int compareToIgnoreCase(String s)
public class CompareMethod {
public static void main(String[] args) {
String str = "abcde";
System.out.println("boy".compareTo(str)); //b-98, a-97
System.out.println("aba".compareTo(str));
System.out.println("abcde".compareTo(str));
System.out.println("Abcde".compareToIgnoreCase(str));
}
}
方法作用:
public int compareTo(String s)按字典序与指定的对象s进行比较,并返回差值,注意,调用者是被减数,指定的对象是减数,public int compareTo(String s)在忽略大小写的基础上进行比较。
运行结果:
00033、按照字典序列对String数组进行排序
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] a = {"melon", "apple", "pear", "banana"};
String[] b = {"西瓜", "苹果", "梨", "香蕉"};
SortString.sort(a);
for(int i = 0; i < a.length; i++){
System.out.print(" " + a[i]);
}
System.out.println(" ");
Arrays.sort(a);
for(int i = 0; i < a.length; i++){
System.out.print(" " + a[i]);
}
}
}
public class SortString {
public static void sort(String a[]){
int cout = 0;
for(int i = 0; i < a.length - 1; i++){
for (int j = i + 1; j < a.length; j++){
if(a[j].compareTo(a[i]) < 0){
String temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
}
运行结果:
00034、String类中常用方法(5)_public boolean contains(String s)
public class ContainsMethod {
public static void main(String[] args) {
String tom = "student";
System.out.println(tom.contains("tud"));
System.out.println(tom.contains("tdu"));
}
}
运行结果:
00035、String类中常用方法(6)_public int indexOf(String s) 、public int lastIndexOf(String s)、public int indexOf(String str, int startpoint)
public class IndexMeythod {
public static void main(String[] args) {
String tom = "I am a good cat";
System.out.println(tom.indexOf("a")); //2
System.out.println(tom.indexOf("good", 2)); //7
System.out.println(tom.indexOf("a", 7)); //13
System.out.println(tom.indexOf("w",2)); //-1
}
}
方法作用:
查找某个字符串第一次出现的位置,public int indexOf(String str, int startpoint) 能指定懂哪个位置开始
运行结果:
00036、String类中常用方法(7)_public String substring(int Satrtpoint)
public class subString {
public static void main(String[] args) {
String tom = "我喜欢篮球";
System.out.println(tom.substring(1));
System.out.println(tom.substring(1,3));
}
}
方法作用:
将Startpoint位置以及end -1 位置中间的字符摘出,成为一个新的字符串
运行结果:
00037、String类中常用方法(8)_public String trim()
public class TrimMethod {
public static void main(String[] args) {
String tom = " I'm a student";
System.out.println(tom);
System.out.println(tom.trim());
}
}
方法作用:
将字符串前后的空格去掉
运行结果: