复数集合

被subString和split卡了一下   细节还是要注意。

注意subString两个参数的方法索引最后一位不包括,split的正则表达式,“+”前面要加“\\”,  还有hasnext()方法里面不能有nextLine()。(补充:nextLine方法如果在while里第一次用,且只有一次时他是不会报错的,这个视情况而定)

 

进入正题:

题目描述

    一个复数(x+iy)集合,两种操作作用在该集合上:     1、Pop 表示读出集合中复数模值最大的那个复数,如集合为空 输出  empty  ,不为空就输出最大的那个复数并且从集合中删除那个复数,再输出集合的大小SIZE;     2 Insert a+ib  指令(a,b表示实部和虚部),将a+ib加入到集合中 ,输出集合的大小SIZE;     最开始要读入一个int n,表示接下来的n行每一行都是一条命令。 
输入描述:
输入有多组数据。
每组输入一个n(1<=n<=1000),然后再输入n条指令。


输出描述:
根据指令输出结果。

模相等的输出b较小的复数。
a和b都是非负数。

输入例子:
3
Pop
Insert 1+i2
Pop

输出例子:
empty
SIZE = 1
1+i2
SIZE = 0

代码如下:
import java.util.Scanner;

public class 复数集合 {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int count = in.nextInt();
            int num[][] = new int[count + 1][2];
            int n = 0;
            for (int i = 0; i < count; i++) {
                String str = in.next();
                if (str.indexOf("Pop")>=0) {
                    if (n == 0) {
                        System.out.println("empty");
                    } else {
                        int flag = 0, tag = 0;
                        for (int a = 1; a <= n; a++) {
                            int mo = num[a][0] * num[a][0] + num[a][1] * num[a][1];
                            if (mo > tag) {
                                tag = mo;
                                flag = a;
                            } else if (mo == tag) {
                                if (num[flag][1] > num[a][1])
                                    flag = a;
                            }
                        }
                        System.out.println(num[flag][0] + "+i" + num[flag][1]);
                        for (int b = flag; b < n; b++) {
                            num[b][0] = num[b + 1][0];
                            num[b][1] = num[b + 1][1];
                        }
                        n--;
                        System.out.println("SIZE = " + n);

                    }

                } else if (str.indexOf("Insert")>=0) {
                    
                    n++;
                    String[] fushu = in.next().trim().split("\\+i");
//                    System.out.println(fushu);
                    num[n][0] = Integer.parseInt(fushu[0]);
                    num[n][1] = Integer.parseInt(fushu[1]);
                    System.out.println("SIZE = " + n);
                }
            }

        }
        in.close();

    }

}

 


posted @ 2016-07-25 21:09  华不摇曳  阅读(628)  评论(0编辑  收藏  举报