学习JAVA遇到问题请大家帮帮忙,是个小问题!谢谢

nesle 2005-03-21 01:37:58
import java.io.*;
import java.util.*;

public class Test
{
private static String line = null;
BufferedReader in = null;

public Test()
{
super();
}
public static void main (String args[])
{
try
{
String fileName = "C:\\javatest\\border.CSV";
BufferedReader in = new BufferedReader(new FileReader(fileName));
while((line = in.readLine()) != null)
{
StringTokenizer st=new StringTokenizer(line,",");
int tokenCount=0;
while(st.hasMoreTokens())
{
tokenCount++;
String token=st.nextToken();

System.out.println(token);

}
}
}catch (IOException e){

}
}
}
输出如下:
5
25
7
35
2
9
100
74
81
20
这是输出的结果,我想对它排序,因为token是String类型的,我想把它写成这样的int[] arr = {5, 25, 7,35,2,9,100,74,81,20};不知道应该怎么做,请指点一下,谢谢!





...全文
141 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
coaa 2005-03-21
  • 打赏
  • 举报
回复
List<Integer> li = new ArrayList<Integer>();
while((line = in.readLine()) != null){
String[] sNum = line.split("\\s*,\\s*");
for (String str: sNum){
li.add(Integer.parseInt(str));
}
}
Collections.sort(li);
Integer[] arr = new Integer[0];
arr = li.toArray(arr);
fog628 2005-03-21
  • 打赏
  • 举报
回复
你的文件:t.txt 如下
12 56 3 15 8 20 9 17
16 19 2 78 95 61 32

======================================
Sort.java如下:

import java.io.*;
import java.util.*;

public class Sort{
public Sort() throws IOException,
FileNotFoundException{

ArrayList list = new ArrayList();
BufferedReader bf = new BufferedReader(
new FileReader("t.txt"));
String line;
while((line = bf.readLine()) != null){
StringTokenizer st = new StringTokenizer(line," ");
while(st.hasMoreTokens()){
//添加到ArrayList
list.add(st.nextToken());
}
}
//对ArrayList排序
Collections.sort(list, new Comparator(){
public int compare(Object o1, Object o2){
return Integer.parseInt((String)o1)
- Integer.parseInt((String)o2);
}
});
System.out.println(list);
}
public static void main(String[] args){
try{
new Sort();
}catch(Exception e){
e.printStackTrace();
}
}
}
pateric 2005-03-21
  • 打赏
  • 举报
回复
int[] arr = new int[st.countTokens()];
int index=0;
while (st.hasMoreTokens()){
arr[index++] = Integer.parseInt(st.nextToken());
}
nesle 2005-03-21
  • 打赏
  • 举报
回复
那怎么把数据加入到Collection中呢?谢谢
wulinbazhu 2005-03-21
  • 打赏
  • 举报
回复
老兄多看书
nesle 2005-03-21
  • 打赏
  • 举报
回复
那怎么把字符一个个取出来写入数组啊?类型的转换我会了
fog628 2005-03-21
  • 打赏
  • 举报
回复
你的这些数据来自文件,是按文件里的顺序读出来的,

你想排序的话,那得把这些数据加入到一个Collection

再用Collections.sort();来排序
simbas00 2005-03-21
  • 打赏
  • 举报
回复
public static int parseInt(String s)
throws NumberFormatException
lemurzjb 2005-03-21
  • 打赏
  • 举报
回复
Integer.parseInt(token);

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧