日期:2014-05-20 浏览次数:20806 次
出现1次的号码5注: 533 574 575 735 773 出现2次的号码6注: 333 373 554 573 733 755 出现3次的号码3注: 473 484 775
------解决方案--------------------
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class NumberSort { static String s; // 模拟文件读取 static { s = "出现1次的号码5注:\r\n"; s += "533 574 575 735 773\r\n"; s += "\r\n"; s += "出现2次的号码6注:\r\n"; s += "333 373 554 573 733 755\r\n"; s += "\r\n"; s += "出现3次的号码3注:\r\n"; s += "473 484 775\r\n"; } public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); // 通过正则找出三位数的数组放进list中 Matcher m = Pattern.compile("\\d{3}").matcher(s); while (m.find()) { list.add(new Integer(m.group())); } // 给list排序 Collections.sort(list); StringBuilder sb = new StringBuilder(); System.out.println("出现1次的号码" + list.size() + "注:"); for (int i = 0; i < list.size(); i++) { sb.append(list.get(i)).append(" "); if ((i + 1) % 10 == 0) { sb.append("\r\n"); } } // 结果 String result = sb.toString().trim(); System.out.println(result); } }
------解决方案--------------------
public static void main(String[] args) throws IOException { File file = new File("file.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); List<Integer> numbers = new ArrayList(); StringBuffer str = new StringBuffer(); String temp ; while((temp = br.readLine()) != null){ str.append(temp); } br.close(); Pattern pattern = Pattern.compile("\\d{3}"); Matcher matcher = pattern.matcher(str.toString()); while(matcher.find()){ numbers.add(Integer.parseInt(matcher.group())); } Collections.sort(numbers); for (int i = 0; i < numbers.size(); i++) { System.out.print(numbers.get(i) + "\t"); if( i != 0 && i % 10 == 0)System.out.println(); } }
------解决方案--------------------
public static void main(String[] args) throws IOException { File file = new File("file.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); List<Integer> numbers = new ArrayList(); StringBuffer str = new StringBuffer(); String temp ; while((temp = br.readLine()) != null){ str.append(temp); } br.close(); Pattern pattern = Pattern.compile("\\d{3}"); Matcher matcher = pattern.matcher(str.toString()); while(matcher.find()){ numbers.add(Integer.parseInt(matcher.group())); } Collections.sort(numbers); System.out.println("出现一次的号码为:" + numbers.size() + "注"); for (int i = 0; i < numbers.size(); i++) { System.out.print(numbers.get(i) + "\t"); if((i + 1) % 10 == 0)System.out.println(); } }