1. Define and arbitrarily input an array a, containing 10 elements. Use the tool class (java.util.Arrays) in the collection framework to complete: 1) Sort the array and output; 2) Input an x, the query is in the array No such value;
package cn.whb.test03;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class work01 {
public static void main(String[] args) throws IOException {
int[] a = {
1,3,4,87,41,123,32,54,1124,23};
Scanner scanner = new Scanner(System.in);
// 排序
Arrays.sort(a);
System.out.println(Arrays.toString(a));
// 查找
int c = scanner.nextInt(); // 输入
int index = Arrays.binarySearch(a, c);
String s = index>=0? ("存在索引为: " + index) :("不存在");
System.out.println(s);
}
}
2. Fill in the names of five people in the collections of HashSet and TreeSet respectively, and output the elements.
package cn.whb.test03;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class work02 {
public static void main(String[] args) {
// 创建集合
Set<Students> stus = new HashSet<>();
// 添加元素
stus.add(new Students("xiao ming"));
stus.add(new Students("xiao li"));
stus.add(new Students("xiao wang"));
stus.add(new Students("xiao zhang"));
stus.add(new Students("xiao mei"));
System.out.println(stus);
Set<Students> stus2 = new TreeSet<>();
stus2.add(new Students("da ming"));
stus2.add(new Students("da li"));
stus2.add(new Students("da wang"));
stus2.add(new Students("da zhang"));
stus2.add(new Students("da mei"));
System.out.println(stus2);
}
}
class Students implements Comparable<Students>{
private String name;
public Students(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return this.name;
}
// 实现compareTo接口,使自定义类型之间可以比较
public int compareTo(Students o) {
int c = this.name.compareTo(o.getName());
if(c>0) {
return 1;
}else if(c<0) {
return -1;
}else {
return 0;
}
}
}
3. Complete the paint method and main method of the following program to make the execution similar to the following result:
package cn.whb.test03;
import java.awt.Graphics;
import javax.swing.*;
public class Example6_1 extends JFrame{
Example6_1(){
super("简单图形");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500,500);
setVisible(true);
}
public void paint(Graphics g){
g.drawRect(100, 100, 200, 200);
g.fillOval(150, 150, 200, 200);
}
public static void main(String args[]){
new Example6_1();
}
}