import java.io.*;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args){
Persona persona1 = new Persona();
try{
StringTokenizer st;
BufferedReader br = new BufferedReader(new FileReader("entrada.txt"));
String linea = br.readLine();
PrintWriter pw = new PrintWriter(new FileWriter("datos.csv"));
while(linea != null){
st = new StringTokenizer(linea);
persona1.setNombre(st.nextToken());
persona1.setRFC(st.nextToken());
persona1.setSueldoMensual(Double.parseDouble(st.nextToken());
persona1.setPrimaVacacional(Double.parseDouble(st.nextToken()));
persona1.setGastosHospitalarios(Double.parseDouble(st.nextToken()));
persona1.setGastosFunerarios(Double.parseDouble(st.nextToken()));
persona1.setSGMM(Double.parseDouble(st.nextToken()));
persona1.setGastosHipotecarios(Double.parseDouble(st.nextToken()));
persona1.setDonativos(Double.parseDouble(st.nextToken()));
persona1.setAportacionRetiro(Double.parseDouble(st.nextToken()));
persona1.setTransporteEscolar(Double.parseDouble(st.nextToken()));
persona1.setNivelEducativo(st.nextToken());
persona1.setColegiaturaTotal(Double.parseDouble(st.nextToken()));
pw.println(persona1.getNombre() + "," + persona1.getRFC() + "," + persona1.getSueldoMensual()
+ "," + persona1.getPrimaVacacional() + "," + persona1.getGastosHospitalarios() + "," + persona1.getGastosFunerarios()
+ "," + persona1.getSGMM() + "," + persona1.getGastosHipotecarios() + "," + persona1.getDonativos()
+ "," + persona1.getAportacionRetiro() + "," + persona1.getTransporteEscolar()
+ "," + persona1.getNivelEducativo() + "," + persona1.getColegiaturaTotal());
}
br.close();
pw.close();
}
catch(FileNotFoundException ex){
System.out.println("Ocurrio un error " + ex);
}
catch(IOException ex){
System.out.println("Ocurrio un error " + ex);
}
}
}
我的程序收到一个.txt文件,并在.csv文件中返回信息,但是当我运行它时会返回此错误:
Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
at Main.main(Main.java:26)
这没有意义,因为我有另一个程序做类似的事情,但我无法弄清楚问题是什么。
答案 0 :(得分:0)
你的问题是没有令牌,你试图设置它,但是例外说没有这样的元素。
为了避免NoSuchElementException,您应该始终在StringTokenizer.hasMoreTokens()的帮助下检查是否有更多令牌。
答案 1 :(得分:0)
尝试使用:
while (st.hasMoreTokens()) {
//do things
}
我的想法是,当标记生成器完成时,字符串最终为空字符串(“”),而不是空。