已知接口 Comparator,内部定义了 max 函数,用于返回两个整数中的最大值。请定义该接口的实现类,使得 main 方法中的比较逻辑可以正确执行,要求实现类的名称为 ComparatorImpl。
输入描述
两个整数
输出描述
两个整数中的最大值
示例1
输入:
1 3
输出:
3
解答
创建一个类来实现 Comparator 接口,然后重写 max() 方法即可。
import java.util.Scanner;
publicclassMain{
publicstaticvoidmain(String[] args){ Comparator comparator = new ComparatorImpl();
Scanner scanner = new Scanner(System.in); while (scanner.hasNextInt()) { int x = scanner.nextInt(); int y = scanner.nextInt(); System.out.println(comparator.max(x, y)); } }
}
interfaceComparator{ /** * 返回两个整数中的最大值 */ intmax(int x, int y); }
classComparatorImplimplementsComparator{
publicintmax(int x, int y){ if (x > y) { return x; } return y; } }
JAVA27 重写父类方法
描述
父类 Base 中定义了若干 get 方法,以及一个 sum 方法,sum 方法是对一组数字的求和。请在子类 Sub 中重写 getX() 方法,使得 sum 方法返回结果为 x*10+y
输入描述
整数
输出描述
整数的和
示例1
输入:
1 2
输出:
12
解答
注意观察,在父类中 getY() 和 sum() 方法都是加了 final 关键字的,所以代表我们在继承自父类的子类中都是无法修改这两个方法的。而要实现将 x 增大 10 倍,那么就只能操作 getX() 方法了,在这个方法中将 x 放大 10 倍即可。
import java.util.Scanner;
publicclassMain{
publicstaticvoidmain(String[] args){ Scanner scanner = new Scanner(System.in); while (scanner.hasNextInt()) { int x = scanner.nextInt(); int y = scanner.nextInt(); Sub sub = new Sub(x, y); System.out.println(sub.sum()); } }
StringBuilder newstr = new StringBuilder(str); for (int i = str.length() - 3; i >= 0; i -= 3) { newstr.insert(i, ','); } System.out.println(newstr.toString()); } }
JAVA30 统计字符串中字母出现次数
描述
给定一个字符串,随机输入一个字母,判断该字母在这个字符串中出现的次数
输入描述
任意一个字母
输出描述
字母在字符串中出现次数
示例1
输入:
o
输出:
3
示例2
输入:
a
输出:
0
解答
要统计字符串中某字母出现的次数,那么遍历该字符串,然后利用字母和字符串的每一个字符相比较,如果相同则计数加 1,直到字符串末尾。注意,要获取字符串第 index 位的字符,需要使用 charAt(index) 方法。
import java.util.Scanner;
publicclassMain{ publicstaticvoidmain(String[] args){ String string = "H e l l o ! n o w c o d e r"; Scanner scanner = new Scanner(System.in); String word = scanner.next(); scanner.close(); System.out.println(check(string, word)); }
publicstaticintcheck(String str, String word){ char ch = word.charAt(0); int count = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ch) { count++; } } return count; } }