提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
目录
前言
一、题目1-集合排序
1.题目描述
2.思路与代码
2.1 思路
2.2 代码
二、题目2- 判断各类型字符个数
1.题目描述
2.思路与代码
2.1 思路
2.2 代码
总结
提示:这里可以添加本文要记录的大概内容:
1月14日练习内容
提示:以下是本篇文章正文内容,下面案例可供参考
有三个客户对象,将三个客户对象存入集合中,并将其按照消费总额从高到低排序
三个整数,分别代表三个客户的消费值
根据消费额从高到低排序后的集合(输出部分预设代码已经给出,为保证输出格式请不要随意更改)
1.Collections中有一个sort方法可以对数据进行排序处理,但要想满足题目要求的按照消费总额从低到高输出,需要在类Customer类内重写compareTo函数
2.重写compareTo函数
代码如下(示例):
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);Customer customer1 = new Customer("小明", scanner.nextInt());Customer customer2 = new Customer("小军", scanner.nextInt());Customer customer3 = new Customer("小红", scanner.nextInt());List customers = new ArrayList<>();customers.add(customer1);customers.add(customer2);customers.add(customer3);//write your code here......Collections.sort(customers);System.out.println(customers);}
}class Customer implements Comparable {private String name;private int consumption;public Customer(String name, int consumption) {this.name = name;this.consumption = consumption;}@Overridepublic String toString() {return "Customer{" +"name='" + name + '\'' +", consumption=" + consumption +'}';}//write your code here......public int compareTo(Customer c) {return c.consumption - this.consumption;}}
输入一行字符串,分别统计出其中英文字母、空格、数字和其它字符的个数
控制台随机输入一串字符串
输出字符串中包含的英文字母个数,数字个数,空格个数,其它字符个数(格式为:英文字母x数字x空格x其他x),预设代码中已给出输出
1.使用for循环遍历字符串,使用charAt函数获得单个字符,
2使用Character类内api进行判断字符分类,
3.输出
代码如下(示例):
import java.util.Scanner;public class Main {public static void main(String[] args) {int numbers = 0;int words = 0;int space = 0;int other = 0;Scanner scanner = new Scanner(System.in);String str = scanner.nextLine();//write your code here......for (int i = 0; i < str.length(); i++) {char c = str.charAt(i);if (Character.isLetter(c)) {words++;} else if (Character.isDigit(c)) {numbers++;} else if (Character.isWhitespace(c)) {space++;} else {other++;}}System.out.println("英文字母" + words + "数字" + numbers + "空格" +space + "其他" + other);}
}
提示:这里对文章进行总结: