package com.itheima;
import java.io.BufferedReader;
import java.io.FileReader;
/*第8题: 把以下IP存入一个txt文件,
* 编写程序把这些IP按数值大小,
* 从小到达排序并打印出来。
61.54.231.245
61.54.231.9
61.54.231.246
61.54.231.48
61.53.231.249
*/
public class Test8 {
//1,首先读入文件
//
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//创建读取文件的流对象
FileReader fr=new FileReader("txt.txt");
//创建缓冲区
BufferedReader bufr=new BufferedReader(fr);
//字符串数组
String[]str=new String[5];
//定义字符串的个数
int num=0;
//读入的一行字符
String line=null;
while((line=bufr.readLine())!=null){
str[num]=line;
num++;
}
bufr.close();
//从小到大冒泡排序
for (int i = 0; i < str.length; i++){
for (int j = 0; j < str.length - 1 - i; j++)
{
if (ToNumber(str[j]) > ToNumber(str[j + 1]))
{
String strBu = str[j];
str[j] = str[j + 1];
str[j + 1] = strBu;
}
}
}
//输出IP地址排序后的结果
for (int i = 0; i < str.length; i++)
{
System.out.println(str[i]);
}
}
//将IP地址转换成数字
public static double ToNumber(String str)throws Exception {
String s="";
for(int i=0;i<str.length();i++)
{
//取出除'.'以外的字符拼接成字符串
if(str.charAt(i)!='.'){
char c=str.charAt(i);
s+=c;
}
}
//将字符串转换成double型返回
double db=Double.parseDouble(s);
return db;
}
}