Topic: 在学数组和例外时遇到的问题求助!

  Print this page

1.在学数组和例外时遇到的问题求助! Copy to clipboard
Posted by: zxhhero
Posted on: 2004-10-25 21:32

{敬请活用编辑功能使您的文章更易于阅读,谢谢}
请教各位,下面这段代码那些地方有问题,我改来改去还是不行,希望能得到大家的帮助,小弟在这里给大家鞠躬了!

import java.io.*;
import java.util.*;
public class ListOfNumbers1{
public static void main(String[] args){
ListOfNumbers1 Alist=new ListOfNumbers1();
Alist.writeList();}

private ArrayList list1;
private static final int size=10;
public ListOfNumbers1(){
list1 =new ArrayList();
for(int i=0;i<size;i++)
{ list1.add(i);
// Collections.fill(list1,"a");
}
}
public void writeList(){
PrintWriter out=null;
try{
System.out.println("Entering try statement");
out=new PrintWriter(new FileOutputStream("zxh.txt"));
for(int i=0;i<size;i++)
out.println(list1.get(i));
}catch(ArrayIndexOutOfBoundsException e)

{System.err.println("Caught ArrayIndexOutOfBoundsException:"+e.getMessage());
}
catch(IOException e)

{System.err.println("Caught IOException:"+e.getMessage());}
}
}

2.Re:在学数组和例外时遇到的问题求助! [Re: zxhhero] Copy to clipboard
Posted by: why
Posted on: 2004-10-25 21:59

add(int) is not valid!

check
http://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html#add(java.lang.Object)
add(Object)
http://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html#add(int,%20java.lang.Object)
add(int, Object)

try something like
add(new Integer(i));

3.Re:在学数组和例外时遇到的问题求助! [Re: zxhhero] Copy to clipboard
Posted by: zxhhero
Posted on: 2004-10-25 22:35

楼上大哥,按你的方法修改后已经不报错了,能顺利通过,但是它创建的文件里却没有内容(即没有将内容写到zxh.txt文件里),请问是什么缘故?能否再帮小弟一把

4.Re:在学数组和例外时遇到的问题求助! [Re: zxhhero] Copy to clipboard
Posted by: littledeer1974
Posted on: 2004-10-25 23:00

那是因为你一次都没有调用 public void writeList()
当然,不会有文件生成了

#而且还要加上黄色的部分,否则,只有文件,而没有内容


public void writeList() {
PrintWriter out = null;
try {
System.out.println("Entering try statement");
out = new PrintWriter(new FileOutputStream("zxh.txt"));
for (int i = 0; i < size; i++) {
out.println(list1.get(i));
}
out.flush();
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Caught ArrayIndexOutOfBoundsException:"
+ e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException:" + e.getMessage());
}
}


你可以查看flush() 的用法。


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923