T001-UT001-0016

来源:互联网 发布:淘宝联盟推广位爱分享 编辑:程序博客网 时间:2024/05/17 02:41

集合练习


编写一个程序,从标准输入设备上输入若干实数,要求每行代表一个实数,直到当输入的一行内容为"sort"时,对已输入的所有实数进行生序排序,并将结果打印在标准输出设备上,注意每行输出一个实数。当输入存在不合法时,比如输入除非sort以外的字符时,则输出Error Input并退出程序。 注意,输出的实数必须和输入的实数保留相同的位数。例如,输入的事1.00则输出时也必须是1.00;若输入的是10则输出的也必须是10,而不能是10.00。

举例:1

程序运行后,直接等待输入,如下

1
2
3
4
5
6
7
8
1.00
5.00
3.00
488
321
10
3.01
sort

输出如下:

1
2
3
4
5
6
7
1.00
3.00
3.01
5.00
10
321
488

 

举例二:

输入:

1
2
3
4
5
6
7
8
1.00
5.00
abc
488
321
10
3.01
sort

输出:

1
Error Input

 

注意:输出的最后没有换行

代码如下:

import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.Collections;import java.util.List;public class D0016 {public static void main(String[] args)throws IOException{String reD_I="^[+-]?([0-9]*\\.?[0-9]+|[0-9]+\\.?[0-9]*)$";//"^[+-]?([0-9]*\\.?[0-9]+|[0-9]+\\.?[0-9]*)$";String reInt="^([0-9]+)$";//"^([eE][+-]?[0-9]+)$";int flag=0;//Scanner input=new Scanner(System.in);BufferedReader br = new BufferedReader(new InputStreamReader(System.in));String num=null;List<Double> numsort = new ArrayList<Double>();List<Integer> numInteger = new ArrayList<Integer>();List<String> numDouble = new ArrayList<String>();while(true){//num=input.nextLine();num=br.readLine();if(num.equals("sort")){if(flag==1){System.out.print("Error Input");return;}break;}else{if(num.matches(reD_I)){if(num.matches(reInt)){int numInt= Integer.parseInt(num);numInteger.add(numInt);}else{numDouble.add(num);}double numD=Double.parseDouble(num);numsort.add(numD);}else{flag=1;//System.out.print("Error Input");//return;}}}Collections.sort(numsort);for(int i=0;i<numsort.size();i++){int j=0,z=0;while(numDouble.size()!=0){double numDouble1=Double.parseDouble(numDouble.get(j));if((double)numsort.get(i)==numDouble1){System.out.print(numDouble.get(j));if((double)numsort.get(numsort.size()-1)!=numDouble1)System.out.println();break;}else{j++;if(j==numDouble.size()){break;}}}while(numInteger.size()!=0){if(numsort.get(i)==(double)numInteger.get(z)){//(double)System.out.print(numInteger.get(z));if(numsort.get(numsort.size()-1)!=(double)numInteger.get(z))System.out.println();break;}else{z++;if(z==numInteger.size()){break;}}}}}}


0 0