Olá pessoal, estou com um trabalho de faculdade pra entregar.
O problema é o seguinte: eu consigo inserir no arquivo .txt até o segundo objeto da classe Pizza, quando eu vou inserir ele dá a seguinte exceção: NoSuchElementException
estou enviando-lhes o código para vocês darem uma olhada
CLASSE ArquivoPizza
package Modelo;
import java.io.FileNotFoundException;
import java.lang.SecurityException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.io.File;
public class ArquivoPizza {
private Formatter saida;
private Scanner entrada;
private ArrayList<Pizza> listaPizza;
private static final String NOMEARQUIVO = "pizzas.txt";
public void abreArquivo() {
try {
entrada = new Scanner(new File(NOMEARQUIVO)); //
lerDados(entrada);
}
catch (FileNotFoundException filesNotFoundException) {
System.err.println("Arquivo vazio...");
criarArquivo();
}
}
public void criarArquivo() {
try {
saida = new Formatter(NOMEARQUIVO);
}
catch (SecurityException securityException) {
System.err.println("Voc� n�o tem acesso a escrita nesse arquivo!");
System.exit(1);
}
catch (FileNotFoundException fileNotFoundException) {
System.err.println("Erro na cria��o do arquivo!");
System.exit(1);
}
}
public void fecharArquivo() {
if(entrada != null)
entrada.close();
if(saida != null)
saida.close();
}
public void lerDados(Scanner entrada) {
listaPizza = new ArrayList<Pizza>();
try {
while(entrada.hasNext()){
Pizza p = new Pizza();
p.setSabor(entrada.nextLine());
p.setPreco(entrada.nextDouble());
listaPizza.add(p);
}
}
catch (NoSuchElementException noSuchElementException) {
System.err.println("Arquivo Formatado de maneira inapropriada!");
entrada.close();
System.exit(1);
}
catch (IllegalStateException illegalStateException) {
System.err.println("Erro de leitura do arquivo!");
System.exit(1);
}
}
public void cadastrarPizza(Pizza p) {
listaPizza.add(p);
salvarPizzas();
fecharArquivo();
}
public void salvarPizzas() {
criarArquivo();
for(Pizza p : listaPizza) {
saida.format("%s\n%.2f\n", p.getSabor(), p.getPreco());
}
}
}
CLASSE Principal (classe com o main)
package Controle;
import Modelo.*;
import GUI.AbaPainel;
import javax.swing.JFrame;
public class Principal {
public static void main(String[] args) {
Pizza x = new Pizza(30.0, "Carne");
ArquivoPizza arqPizza = new ArquivoPizza();
arqPizza.abreArquivo();
arqPizza.abreArquivo();
arqPizza.cadastrarPizza(x);
Pizza y = new Pizza(20.0, "Escarola");
arqPizza.abreArquivo();
arqPizza.cadastrarPizza(y);
Pizza k = new Pizza(10.0, "Atum");
arqPizza.abreArquivo();
arqPizza.cadastrarPizza(k);
Pizza j = new Pizza(10.0, "Mussarela");
arqPizza.abreArquivo();
arqPizza.cadastrarPizza(j);
}
}