Android编程:解决异常“java.util.NoSuchElementException”

本文介绍了一个Java程序中集合遍历与文件读写的常见错误,并提供了修复建议。通过一个具体的例子展示了如何从文件中读取数据到集合中,然后将数据写入另一个文件的过程。同时指出了在迭代输出过程中可能遇到的NoSuchElementException异常及其解决办法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class Step01 {

 public static void main(String[] args) {
  Set<String> set = new HashSet<String>();
  File in = new File("Answer0712/aaa.txt");
  File out = new File("Answer0712/bbb.txt");
  InputStream is = null;
  OutputStream os = null;
  try {
   is = new FileInputStream(in);
   os = new FileOutputStream(out);
   BufferedReader br = new BufferedReader(new InputStreamReader(is));
   while (true) {
    String str = br.readLine();
    if (str == null)
     break;
    set.add(str);
   }
   // Iterator i = set.iterator();
   // while(i.hasNext()){
   // System.out.println("Null值判断:"+i.next());
   // }
   PrintWriter pw = new PrintWriter(new BufferedWriter(
     new OutputStreamWriter(os)), true);
   Iterator i = set.iterator();
   while (i.hasNext()) {
    System.out.println(i.next());  //这一句是罪魁祸首
    pw.println(i.next());
   }
   pw.flush();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    is.close();
    os.close();
   } catch (IOException e) {
    e.printStackTrace();
   }

  }

 }
}


文章中标示黄色的那一句,本来是要打印出来,在控制台看看所写的数据是否正确。

结果就出现了java.util.NoSuchElementException的错误提示 ,就是黄色的那一句,多了一个 迭代器的next()。

所以错了。去掉它就好了,或者改为

 

while (i.hasNext()) {
    String ss = (String) i.next();
    System.out.println(ss);
    pw.println(ss);
   }都可以解决问题。


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值