1. 结婚
有一个类CAB,有一个canMarry方法,接收两个Person对象,返回boolean值表示两个人能否结婚。
package kfm.bases.string;public class Person {private String name;private Character gender;private Integer age;private Boolean marry;public Person(String name, Character gender, Integer age, Boolean marry) {this.name = name;this.gender = gender;this.age = age;this.marry = marry;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Character getGender() {return gender;}public void setGender(Character gender) {this.gender = gender;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public Boolean getMarry() {return marry;}public void setMarry(Boolean marry) {this.marry = marry;}
}
package kfm.bases.string;import java.util.Scanner;public class CAB {public static boolean canMarry(Person person1, Person person2) {// 判断是否性别相同if (person1.getGender().equals(person2.getGender())) {return false;}// 判断是否未婚if (person1.getMarry().equals(true) || person2.getMarry().equals(true)) {return false;}// 判断年龄是否符合if (person1.getGender().equals('女')) {if (person1.getAge() < 20 || person2.getAge() < 22) {return false;}} else {if (person1.getAge() < 22 || person2.getAge() < 20) {return false;}}return true;}public static Person addPerson() {Scanner input = new Scanner(System.in);System.out.println("姓名");String name = input.next();System.out.println("性别");String inputGender = input.next();char gender = inputGender.charAt(0);System.out.println("年龄");int age = input.nextInt();System.out.println("婚姻状况");boolean marry = input.nextBoolean();Person person = new Person(name, gender, age, marry);return person;}public static void main(String[] args) {boolean isMarry = canMarry(addPerson(), addPerson());if (isMarry) {System.out.println("OMG,你们结婚吧!");} else {System.out.println("你们婚姻不合法。。。。");}}
}
2. 统计个数
请编写程序,由键盘录入一个字符串,统计字符串中英文字母和数字分别有多少个。比如:Hello12345World中字母:10个,数字:5个。
package kfm.bases.string;import java.util.Scanner;public class NumberOfStatistics {public static void main(String[] args) {Scanner input = new Scanner(System.in);String str = input.next();int countNum = 0;int countStatic = 0;for (int i = 0; i < str.length(); i++) {// 判断是否为数字if (Character.isDigit(str.charAt(i))) {countNum ++;}// 通过 ASCLL码 比较if ((str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') || (str.charAt(i) >= 'a' && str.charAt(i) <= 'z')) {countStatic ++;}}System.out.println("数字个数为 " + countNum);System.out.println("字母个数为 " + countStatic);}
}
3. 回文字符串
请定义一个方法用于判断一个字符串是否是对称的字符串,并在主方法中测试方法。例如:“abcba”、"上海自来水来自海上"均为对称字符串
package kfm.bases.string;import java.util.Scanner;public class Palindrome {public static void isPalin(String str) {String str1 = "";for (int i = str.length() - 1; i >= 0; i--) {str1 += str.charAt(i);}if (str.equals(str1)) {System.out.println("是回文字符串");return;}System.out.println("不是回文字符串");}public static void main(String[] args) {Scanner input = new Scanner(System.in);isPalin(input.next());}
}