Java learning records (3)

Preface

I started to learn JAVA in my sophomore year, and I want to record the programs I wrote to witness my progress


task

Program a class Compare, define a static method to compare the size of two String objects, if string 1 and string 2 are equal, return 0; if string 1 and string 2 are not equal, return the first difference The difference between the characters; if the string 1 and string 2 are only different in length, the difference between the lengths of the two is returned. Define the test class to call this method.

Code

The code is as follows: the
test class is not attached.

public class Compare {
    
    
	public static void compare(String a, String b) {
    
    
		if (a.equals(b)) {
    
    
			System.out.println(0);//如果两个字符串相等就直接输出0
		}

		for (int m = 0; m < 123123; m++) {
    
    
			if (a.charAt(m) == (b.charAt(m))) {
    
    //提取第m个字符进行比较
				if (a.length() == (m + 1) || b.length() == (m + 1)) {
    
    
					if (a.length() > b.length()) {
    
    
						System.out.println(a.length() - b.length());
						break;
					}
					System.out.println(b.length() - a.length());
					break;
				}
			} else {
    
    
				System.out.println(a.charAt(m) - b.charAt(m));//直接相减可以直接比较ASCII码
				break;
			}
		}

	}

}

Guess you like

Origin blog.csdn.net/beiyingC/article/details/108895918