[Java] API Basics

Personal homepage: Hello Code.
This article column: Java Zero Basic Guide
For more related content, please click to go to Java Zero Basic Guide to view
If you have any questions, please correct me and learn together~~


Article directory


Overview

  • API ( Application Programming Interface ) : Application Programming Interface

To write a program to control the football, the program needs to issue various commands to the robot, such as running forward, running backward, shooting, and grabbing the ball. Robot manufacturers must provide some interface classes for controlling robots. These classes define the methods for manipulating various actions of the robot. In fact, these interface classes are the interfaces provided by robot manufacturers for application programming, and these classes are called APIs.

  • keyboard input string
Scanner sc = new Scanner();
System.out.print("请输入内容:");
String s = sc.nextLine(System.in);	//遇到回车、换行结束
//String s = sc.next(System.in);	//遇到空格、tab就停止
System.out.println(s);

When receiving data by keyboard input, if the string and integer are received together, it is recommended to use the next method to receive the string


String class

  • Overview: The String class is under the java.lang package and does not need to be imported when using it.
    The String class represents strings, and all string literals (eg: "abc") in Java programs are implemented as methods of this class

Strings are constants, their value cannot be changed after creation

  • Common construction methods
    public String()Create a blank string object without any content Create a string according
    public String(char[] chs)to the content of the character array Create a string object
    public String(String original)according to the incoming string content Create a string object
    String s = "abc";by direct assignment, the content is abc

String is a special class. When printing its object name, the memory address will not appear, but the real content recorded by the object.

  • The difference between creating a string object and comparing
    the string given in the "" way, as long as the character sequence is the same (order and case), no matter how many times it appears in the program code, the JVM will only create a String object, and in the string Maintained in constant pool

String constant pool: when usingWhen double quotes create a string object, the system willCheck if the string exists in the string constant pool. If it does not exist, it will be created; if it exists, it will not be recreated and used directly.
Note: The string constant pool has been moved from the method area to the heap memory since JDK7.
Extension: ==compare values ​​when comparing basic data types, and when comparing reference data types Compare if addresses are the same

A string object created by new will apply for a memory space each time new, although the content is the same, but the address value is different

  • Features:
    All double-quote characters in Java programs are objects of the String class
    Strings are immutable and their values ​​cannot be changed after creation
    Although String values ​​are immutable, they can be shared

When using + splicing between strings, the bottom layer of the system will automatically create a StringBuilder object
and then call its append method to complete the splicing
. After splicing, call the toString method to convert to String type.

  • String comparison
    String is an object. It compares whether the content is the same or not. It is implemented by a method. This method is called:equals()

public boolean equals(Object anObject) : Compares this string with the specified object. Since we are comparing string > string objects, a string is passed between the parameters

String s1 = "abc";
String s2 = "ABC";
s1.equals(s2);		//false
//equalsIgnoreCase()方法比较字符串不区分大小写
s1.equalsIgnoreCase(s2);		//true	
  • case
// 需求:已知用户名和密码,请用程序实现模拟用户登录,总共给三次机会,登录之后,给出相应的提示
import java.util.Scanner;
public class Test{
    
    
	public static void main(String[] args){
    
    
		String userName = "abcde";
		String passWord = "abc666";
		int count = 0;
		Scanner sc = new Scanner(System.in);
		for(int i = 0; i < 3; i++){
    
    
			System.out.print("请输入用户名:");
			String user = sc.nextLine();
			System.out.print("请输入密码:");
			String pass = sc.nextLine();
			if(userName.equals(user) && passWord.equals(pass)){
    
    
				System.out.println("恭喜您,登录成功!");
				break;
			}else{
    
    
				System.out.println("账号或密码错误,请重试");
				count++;
				}
		}
		if(count >= 3) System.out.println("登录失败次数过多,请稍后重试");
	}
}
// 需求:键盘录入一个字符串,使用程序实现在控制台遍历该字符串,将字符串拆分为字符数组
// public char charAt(int index):返回指定索引处的char值,字符串的索引也是从0开始的
// public int length():返回此字符串的长度
// public char[] toCharArray():将当前字符串拆分为字符数组并返回
import java.util.Scanner;
public class Test{
    
    
	public static void main(String[] args){
    
    
		Scanner sc = new Scanner(System.in);
		System.out.print("请输入字符串:");
		String s = sc.nextLine();
		/*
		for(int i = 0; i < s.length(); i++){
			System.out.print(s.charAt(i) + " ");
		}
		*/
		char[] chars = s.toCharArray();
		for(int i = 0; i < chars.length; i++){
    
    
			System.out.print(chars[i] + " ");
		}
	}
}
//需求: 键盘录入一个字符串,统计该字符串中大写字母字符,小写字母字符,数字字符出现的次数(不考虑其他字符)
import java.util.Scanner;
public class Test{
    
    
	public static void main(String[] args){
    
    
		Scanner sc = new Scanner(System.in);
		System.out.print("请输入字符串:");
		String s = sc.nextLine();
		char[] chars = s.toCharArray();
		int num = 0;
		int english = 0;
		int English = 0;
		for(int i = 0; i < chars.length; i++){
    
    
			if(chars[i] >= '0' && chars[i] <= '9') num++;
			else if(chars[i] >= 'a' && chars[i] <= 'z') english++;
			else if(chars[i] >= 'A' && chars[i] <= 'Z') English++;
		}
		System.out.println("数字:" + num + " 小写字母:" + english + " 大写字母:" + English);
	}
}
// 需求:以字符串的形式从键盘接收一个手机号,将中间四位号码屏蔽
// 最终效果:183****4828
/*
截取字符串:
	String substring(int beginIndex):
		从传入的索引位置处,向后截取,一直截取到末尾,得到新的字符串并返回
	String substring(int beginIndex, int endIndex):
		从beginIndex索引位置开始截取,截取到endIndex索引位置,得到新的字符串并返回(含头不含尾)
  */
import java.util.Scanner;
public class Test{
    
    
	public static void main(String[] args){
    
    
		Scanner sc = new Scanner(System.in);
		System.out.print("请输入手机号:");
		String s = sc.nextLine();
		String begin = s.substring(0, 3);
		String end = s.substring(7, 11);
		System.out.println("最终手机号为:" + begin + "****" + end);
	}
}
// 需求:键盘录入一个字符串,如果字符串中包含(TMD),则使用***替换
/*
String replace(CharSequence target, CharSequence replacement)
	将当前字符串中的target(被替换的旧值)内容,使用replacement(替换的新值)进行替换
	返回新的字符串
*/
import java.util.Scanner;
public class Test{
    
    
	public static void main(String[] args){
    
    
		Scanner sc = new Scanner(System.in);
		System.out.print("请输入内容:");
		String s = sc.nextLine();
		String result = s.replace("TMD", "***");
		System.out.println("您输入的内容为:" + result);
	}
}
// 需求:以字符串的形式从键盘录入学生信息,例如:"张三,23"从该字符串中切割出有效数据,封装为Student学生对象
// String[] split(String regex):根据传入的字符作为规则进行切割,将切割后的内容存入字符串数组中,并将字符串返回(数组)

// 新建一个Student类
public class Student{
    
    
	private String name;
	private String age;
	public Student(){
    
    }
	public Student(String name, String age){
    
    
		this.name = name;
		this.age = age;
	}
	public String getName(){
    
    
		return name;
	}
	public void setName(String name){
    
    
		this.name = name;
	}
	public String getAge(){
    
    
		return age;
	}
	public void setAge(String age){
    
    
		this.age = age;
	}
}
  
  //---------------------------下面为一个新的class文件----------------------------------------------
  
import java.util.Scanner;
public class Test{
    
    
	public static void main(String[] args){
    
    
		Scanner sc = new Scanner(System.in);
		System.out.print("请输入您的信息:");
		String stuInfo = sc.nextLine();
		String[] sArr = stuInfo.split(",");
		Student stu = new Student(sArr[0], sArr[1]);
		System.out.println("姓名:" + stu.getName() + " 年龄:" + stu.get)
	}
}

StringBuilder

  • Overview: StringBuilder is a mutable string class, we can think of it as a container
  • Role: improve the efficiency of string operations
  • Constructor:
    public StringBuilder()Create a blank mutable string object that does not contain any content Create a mutable string object
    public StringBuilder(String str)based on the content of the string
  • Common method:
    method name illustrate
    public StringBuilder append(any type) add data, and return the object itself
    public StringBuilder reverse() Returns the reversed sequence of characters
    public int length() Returns length (number of occurrences of characters)
    public String toString() Convert StringBuilder to String through toString()
StringBuilder sb = new StringBuilder();
//链式编程:如果一个方法返回的是对象类型,对象就可以继续向下调用方法
sb.append("red").append("blue").append("green");
  • StringBuilder improves efficiency principle:

whenStringWhen the type string is spliced ​​with +, the system will create a new one in the heap memory by default.StringBuilderType object, complete the splicing through the append() method, and then passtoString()Convert StringBuilder type to String type.
Using StringBuilder saves unnecessary steps

  • case
// 需求:键盘接收一个字符串,程序判断出该字符串是否是对称字符串,并在控制台打印是或不是
// 对称字符串:123321、111			非对称字符串:123123
import java.util.Scanner;
	public class Test{
    
    
		public static void main(String[] args){
    
    
			Scanner sc = new Scanner(System.in);
			System.out.print("请输入内容:");
			String s = sc.nextLine();
			StringBuilder ss = new StringBuilder(s);
			String sss = ss.reverse().toString();
			if(s.equals(sss)){
    
    
				System.out.println("是");
			}else{
    
    
				System.out.println("不是");
			}
		}
	}
// 需求:定义一个方法,把int数组中的数据按照指定的格式拼接成一个字符串返回,调用该方法,并在控制台输出结果。
// 例如:数组为:int[] arr = {1, 2, 3};	执行方法后的输出结果为:[1,2,3]
public static void main(String[] args){
    
    
	int[] arr = {
    
    1, 2, 3};
	String s = arrayToString(arr);
	System.out.println(s);
}
// 定义一个方法,返回值类型 String ,参数列表int[] arr
public static String arrayToString(int[] arr){
    
    
	StringBuilder sb = new StringBuilder("【");
	for(int i = 0; i < arr.length; i++){
    
    
		if(i == arr.length - 1){
    
    
			sb.append(arr[i]).append("】");
		}else{
    
    
			sb.append(arr[i]).append(",");
		}
	}
	return sb.toString();
}

Recommended reading: Java Collections Fundamentals

Guess you like

Origin blog.csdn.net/qq_24980365/article/details/121662593
Recommended