@ysner
2021-09-13T12:44:50.000000Z
字数 2208
阅读 765
数据结构
JAVA
一些尝试:
1、学习使用JAVA的输入语句,减少程序修改次数。
2、throw new IllegalArgumentException("")可以自定义报错显示+直接终止程序。
import java.util.Scanner;
public class Hw1_12
{
static class Set<E>
{
final int Mxsize=100;
E[] data;
int size;
public Set()
{
data=(E[])new Object[Mxsize];
size=0;
}
public int getsize()
{
return size;
}
public E get(int i)
{
if(i<0||i>=size)
throw new IllegalArgumentException("failing get: I is not in the right range!");
return (E)data[i];
}
public boolean IsIn(E e)
{
for(int i=0;i<size;i++)
if(data[i]==e) return true;
return false;
}
public boolean add(E e)
{
if(IsIn(e)||size==Mxsize) return false;
else
{
data[size]=e;
size++;
return true;
}
}
public boolean delete(E e)
{
int i=0;
while(i<size&&data[i]!=e) i++;
if(i>=size) return false;
for(int j=i+1;j<size;j++) data[j-1]=data[j];
size--;
return true;
}
public void display()
{
for(int i=0;i<size;i++)
if(i==0) System.out.print(data[i]);
else System.out.print(" "+data[i]);
System.out.println();
}
}
static class TwoSet<E>
{
public Set<E> Union(Set<E> s1,Set<E> s2)
{
Set<E> s3=new Set<E>();
for(int i=0;i<s1.getsize();i++) s3.add(s1.get(i));
for(int i=0;i<s2.getsize();i++)
if(!s1.IsIn(s2.get(i))) s3.add(s2.get(i));
return s3;
}
public Set<E> Intersection(Set<E> s1,Set<E> s2)
{
Set<E> s3=new Set<E>();
for(int i=0;i<s1.getsize();i++)
if(s2.IsIn(s1.get(i))) s3.add(s1.get(i));
return s3;
}
public Set<E> Difference(Set<E> s1,Set<E> s2)
{
Set<E> s3=new Set<E>();
for(int i=0;i<s1.getsize();i++)
if(!s2.IsIn(s1.get(i))) s3.add(s1.get(i));
return s3;
}
}
public static void main(String[] args)
{
Set<Integer> s1,s2,s3,s4,s5;
TwoSet<Integer> t=new TwoSet<Integer>();
s1=new Set<Integer>();
Scanner in=new Scanner(System.in);
System.out.println("Please enter the size of Set s1: ");
int n=in.nextInt();
System.out.println("Please enter the elements of Set s1: ");
while(n>0) {s1.add(in.nextInt());n--;}
s2=new Set<Integer>();
System.out.println("Please enter the size of Set s2: ");
n=in.nextInt();
System.out.println("Please enter the elements of Set s2: ");
while(n>0) {s2.add(in.nextInt());n--;}
s3=t.Union(s1,s2);
System.out.println("s3 is the union of s1 and s2!");
System.out.print("Set s3: ");s3.display();
s4=t.Difference(s1,s2);
System.out.println("s4 is the difference set of s1 and s2!");
System.out.print("Set s4: ");s4.display();
System.out.println("s5 is the intersection of s1 and s2!");
s5=t.Intersection(s1,s2);
System.out.print("Set s5: ");s5.display();
s1.get(5);//看看自己写的边界检查语句效果怎么样
}
}