File Handling and Arraylists error - java

I'm trying to add a list of phrases from the text file "ListOfElectronics.txt", to the ArrayList "electronics".
I'm getting an error here: electronics.add(fileIn.nextLine());
It's saying "no suitable method found for add(java.lang.String)"
import java.util.Scanner;
import java.util.ArrayList;
import java.io.*;
/***
*
*
*
*/
public class Driver
{
public static void main(String[] args)
{
System.out.println("\f");
ArrayList<Electronics> electronics = new ArrayList<Electronics>();
Scanner stdIn = new Scanner(System.in);
Scanner fileIn;
try
{
fileIn = new Scanner(new FileReader("ListOfElectronics.txt"));
while (fileIn.hasNextLine())
{
electronics.add(fileIn.nextLine());
}
fileIn.close();
}
catch (FileNotFoundException e)
{
System.out.println("Error: " + e.getMessage());
}
}
}

Replace
ArrayList<Electronics> electronics = new ArrayList<Electronics>();
with
ArrayList<String> electronics = new ArrayList<>();
Otherwise, it's expecting you to add objects of a class of a type called Electronics.
If you do have a class called Electronics, that you're looking to add to the Arraylist, and if it has a constructor that calls for a String, you can replace the add string with:
electronics.add(new Electronics(fileIn.nextLine()));

If your Electronics class looks like this
public class Electronics {
private string name;
public Electronics(String name) {
this.name = name;
}
}
then you could just replace:
while (fileIn.hasNextLine())
{
electronics.add(fileIn.nextLine());
}
with
while (fileIn.hasNextLine())
{
Electronics electronics = new Electronics(fileIn.nextLine();
electronics.add(electronics);
}

Related

Visitors Details question IO file handling in java

VIP group of companies introduce a new shopping mall “Le Le” . To promote the mall they had approached “6th Event” a famous commercial event organizer to organize an event of lucky draw. The organizer has to collect name, phone and email id of all the visitors during promotion time and give it to the company.
The organizer needs an automated application and wants to store records in a text file called “visitors.txt”.
Records should to be stored in the following structure
Name1,phonenumber1,emailId1;Name2,phonenumber2,emailId2;
In a record, each attributes should be separated using comma (,) and records should be separated using semi colon (;).
Create a Java Application which has two classes called Main.java and FileManager.java
In FileManager class implement the following methods [method skeletons are given]
static public File createFile() – This method should create the file and return it.
static public void writeFile(File f, String record) – In the method, first parameter is the file reference in which records to be added and second parameter is a record, This record should append in the file. [Record should be as per the given format]
static public String[] readFile(File f) – This method accept file to be read, returns all records in the file.
[Note : Don’t modify the signature of the given methods]
In Main class use the following Input and Output statements and call the needed methods from FileManager class to manipulate files.
Enter Name
John
Enter Phone Number
1234567
Enter Email
johnpeter#abc.com
Do you want to enter another record(yes/no)
yes
Enter Name
Grace
Enter Phone Number
98765412
Enter Email
gracepaul#xyz.com
Do you want to enter another record(yes/no)
no
Do you want to display all records(yes/no)
yes
John,1234567,johnpeter#abc.com
Grace,98765412,gracepaul#xyz.com
FileManager class
//import necessary packages
import java.io.*;
import java.util.*;
#SuppressWarnings("unchecked")//Do not delete this line
public class FileManager
{
static public File createFile()
{
File file =new File("visitors.txt");
try{ file.createNewFile();}
catch (IOException e)
{
e.printStackTrace(); //prints exception if any
}
return file;
}
//change the return type as per the requirement
static public void writeFile(File f, String record)
{ try {
BufferedWriter out = new BufferedWriter(
new FileWriter(f.getName(), true));
out.write(record+";");
out.close();
}
catch (IOException e) {
System.out.println("exception occoured" + e);
}
}
static public String[] readFile(File f)
{
List<String> tokens = new ArrayList<String>();
try{
File myObj = new File(f.getName());
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
// String [] arr= myReader.nextLine().split(";");
// tokens = Arrays.asList(arr);
tokens.add(myReader.nextLine());
}
myReader.close();
}
catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
String[] tokenArray = tokens.toArray(new String[0]);
//=tokenArray.split(";");
return tokenArray;
}
}
Main class
import java.util.*;
import java.io.FileNotFoundException;
//import necessary packages
import java.io.File;
#SuppressWarnings("unchecked")//Do not delete this line
public class Main
{
public void abcd(){
Scanner in = new Scanner(System.in);
System.out.println("Enter Name");
String name=in.next();
System.out.println("Enter Phone Number");
long phone=in.nextLong();
System.out.println("Enter Email");
String id= in.next();
FileManager f= new FileManager();
File x =f.createFile();
f.writeFile(x,name+","+phone+","+id);
System.out.println("Do you want to enter another record(yes/no)");
String choice=in.next();
if(choice.equals("yes")){
abcd();
}
if(choice.equals("no"))
{String []q=f.readFile(x);
String pl[]=q[0].split(";");
for(int i=0;i<pl.length;i++)
{
System.out.println(pl[i]);
}
System.exit(0);
}
}
public static void main(String[] args)
{
Main asd=new Main();
asd.abcd();
}
}
This program gives me desired output but not able to run all test cases.
Getting error could not append multiple files. Dont know is this.But it works perfectly on compiler. And you should at least try to code rather then simply asking someone to code.
//all test case passed
import java.io.*;
import java.util.*;
#SuppressWarnings("unchecked")//Do not delete this line
public class FileManager
{
static public File createFile()
{
File myObj = new File("visitors.txt");
try{
if(new File("visitors.txt").isFile()==false)
myObj.createNewFile();
}
catch (IOException e)
{
e.printStackTrace(); //prints exception if any
}
return myObj;//change the return type as per the requirement
}
static public void writeFile (File f, String record)
{
try
{
FileWriter fw = new FileWriter(f.getName(),true); //the true will append the new data
fw.write(record+"\n");//appends the string to the file
fw.close();
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
}
static public String[] readFile(File f)
{
List<String> list=new ArrayList<String>();
try{
File myObj = new File(f.getName());
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String str=myReader.nextLine();
String[] parts = str.split(";");
for (String part : parts) {
list.add(part);
}
}
myReader.close();
}
catch(FileNotFoundException ex){}
String[] strings = list.stream().toArray(String[]::new);
return strings;
//change the return type as per the requirement
}
}

How do I fix Illegal Start of Expressions with all of my methods?

I have my code. I think it's all right, but it is not. It keeps telling me at the beginning of each method that there is a ';' expected and it's also an 'illegal start of expression' with the void. I do not know how to fix it. Can someone please help me fix these errors?
Here's an example of the Errors:
F:\COMP SCI\Topic 29 - Data Structures -- Robin Hood\Problem Set\RobinHoodApp.java:203: error: ';' expected
void arrayList **()** throws FileNotFoundException();
F:\COMP SCI\Topic 29 - Data Structures -- Robin Hood\Problem Set\RobinHoodApp.java:212: error: illegal start of expression
**void** output()
F:\COMP SCI\Topic 29 - Data Structures -- Robin Hood\Problem Set\RobinHoodApp.java:212: error: ';' expected
void output **()**
My code:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import static java.lang.System.out;
import java.util.ArrayList;
import javax.swing.JFrame;
public class RobinHoodApp{
public static void main(String[] args) throws FileNotFoundException, IOException {
RobinHood app = new RobinHood();
app.readFile();
app.arrayList();
app.wordCount();
app.countMenAtArms();
app.writeToFile();
}
}
class RobinHood extends JFrame
{
private static final ArrayList<String>words = new ArrayList<>();
private static Scanner book;
private static int count;
private static int wordCount;
public RobinHood()
{
try {
// scrubber();
//Prints All Words 1 by 1: Works!
book = new Scanner(new File("RobinHood.txt") );
book.useDelimiter("\r\n");
} catch (FileNotFoundException ex)
{
out.println("Where's your text fam?");
}
}
void readFile()
{
while(book.hasNext())
{
String text = book.next();
out.println(text);
}
void arrayList() throws FileNotFoundException();
{
Scanner add = new Scanner(new File("RobinHood.txt"));
while(add.hasNext())
{
words.add(add.next());
}
}
void output()
{
out.println(words);
}
void countMenAtArms()
{
//Shows 23 times
String find = "men-at-arms";
count = 0;
int x;
String text;
for(x=0; x< wordCount; x++ )
{
text = words.get(x);
text = text.replaceAll("\n", "");
text = text.replaceAll("\n", "");
if (text.equals(find))
{
count++;
}
}
out.println("The amount of time 'men-at-arms' appears in the book is: " + count);
}
// void scrubber()
// {
//
// }
//
//
void wordCount()
{
{
wordCount=words.size();
out.println("There are "+wordCount+" words in Robin Hood.");
}
}
public void writeToFile()
{
File file;
file = new File("Dominique.dat");
try (FileOutputStream data = new FileOutputStream(file)) {
if ( !file.exists() )
{
file.createNewFile();
}
String wordCountSentence = "There are "+ wordCount +" words in Robin Hood. \n";
String countTheMen = "The amount of time 'men-at-arms' appears in the book is: " + count;
byte[] strToBytes = wordCountSentence.getBytes();
byte[] menToBytes = countTheMen.getBytes();
data.write(strToBytes);
data.write(menToBytes);
data.flush();
data.close();
}
catch (IOException ioe)
{
System.out.println("Error");
}
}
}
}
You should use a Java IDE like Eclipse when programming Java, it would point out to you the most obvious mistakes in your code.
You missed a } after the while loop for your readFile() method (thanks to Sweeper for this one).
The syntax in your arrayList() method is wrong.
void arrayList() throws FileNotFoundException(); {
No semicolon at the end of this defintion, no parenthesis at the end too, you are describing the class, not a method. Here is the correct way:
void arrayList() throws FileNotFoundException {
1 useless } at the end of your class file.
Find below your code, with a proper layout and without syntax errors. Please use an IDE next time, that would avoid you an awful lot of trouble.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import static java.lang.System.out;
import java.util.ArrayList;
import javax.swing.JFrame;
public class RobinHoodApp {
public static void main(String[] args) throws FileNotFoundException, IOException {
RobinHood app = new RobinHood();
app.readFile();
app.arrayList();
app.wordCount();
app.countMenAtArms();
app.writeToFile();
}
}
class RobinHood extends JFrame
{
private static final ArrayList<String>words = new ArrayList<>();
private static Scanner book;
private static int count;
private static int wordCount;
public RobinHood()
{
try {
// Prints All Words 1 by 1: Works!
book = new Scanner(new File("RobinHood.txt") );
book.useDelimiter("\r\n");
} catch (FileNotFoundException ex)
{
out.println("Where's your text fam ?");
}
}
void readFile()
{
while(book.hasNext())
{
String text = book.next();
out.println(text);
}
}
void arrayList() throws FileNotFoundException
{
Scanner add = new Scanner(new File("RobinHood.txt"));
while(add.hasNext())
{
words.add(add.next());
}
}
void output()
{
out.println(words);
}
void countMenAtArms()
{
// Shows 23 times
String find = "men-at-arms";
count = 0;
int x;
String text;
for(x=0; x< wordCount; x++ )
{
text = words.get(x);
text = text.replaceAll("\n", "");
text = text.replaceAll("\n", "");
if (text.equals(find))
{
count++;
}
}
out.println("The amount of time 'men-at-arms' appears in the book is: " + count);
}
void wordCount()
{
{
wordCount=words.size();
out.println("There are "+wordCount+" words in Robin Hood.");
}
}
public void writeToFile()
{
File file;
file = new File("Dominique.dat");
try (FileOutputStream data = new FileOutputStream(file)) {
if ( !file.exists() )
{
file.createNewFile();
}
String wordCountSentence = "There are "+ wordCount +" words in Robin Hood. \n";
String countTheMen = "The amount of time 'men-at-arms' appears in the book is: " + count;
byte[] strToBytes = wordCountSentence.getBytes();
byte[] menToBytes = countTheMen.getBytes();
data.write(strToBytes);
data.write(menToBytes);
data.flush();
data.close();
}
catch (IOException ioe)
{
System.out.println("Error");
}
}
}
throws FileNotFoundException();
This should be
throws FileNotFoundException
and similarly in all cases.
Rather trivial. Don't just make up the syntax. Look it up.

Create and populate HashMap<Integer, ArrayList<object>>

I have an assignment for school that's all about using files, HashMap and ArrayList. This assignment requires 4 classes.
The first class is called FileReader and reads a txt file which is written line by line and each field that we need is separated by ";", for example ("Columbia University";"USA";78.86;2012). Each line contains 2 strings (university name and country) and 2 numbers (score and year). The FileReader class after reading the txt file returns its content in an arraylist.
The second class of the assignment is called UniversityScores and it has 4 fields (uniname, country, score, year), a constructor, accessor methods for all fields and a toString method.
The third class is the heart of our program. This class is called FileEditor and creates a Hashmap<Integer,ArrayList<UniversityScores>> where the key is the year field of each object and value I guess is the rest of the line. My problem is filling the right way the HashMap.
Also, my final 4th class is called FileWriter which creates a new txt and writes inside of it. All my classes work as supposed to except my FileEditor class. Any help needed. Thank you in advance!
Edit
I am supposed to write some other methods as well. For now my problem is the FileEditor class. I also posted the TestFiles class which contains the main function.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
class FileReader{
private String fileName;
private Scanner scanner;
private File file;
private ArrayList<String> arrayList;
private String line;
public FileReader(String otherFileName){
this.fileName = otherFileName;
this.file = new File(fileName);
}
public boolean initReader(){
try {
scanner = new Scanner(file);
}
catch (FileNotFoundException e) {
System.out.println("Just caught a FileNotFoundException.");
}
if(file.exists()){
return true;
}
else{
return false;
}
}
public ArrayList<String> readFile(){
this.arrayList = new ArrayList<String>();
while (scanner.hasNextLine()) {
this.line = scanner.nextLine();
arrayList.add(line);
}
arrayList.remove(0);
//System.out.println(arrayList);
return arrayList;
}
public void closeReader(){
scanner.close();
System.out.println("Scanner closed");
}
}
‌
import java.util.ArrayList;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
class FileWriter{
private String path;
private PrintWriter writer;
private File outputFile;
public FileWriter(String otherPath){
this.path = otherPath;
this.outputFile = new File(path);
}
public boolean initWriter(){
try{
writer = new PrintWriter(path);
}
catch (FileNotFoundException e){
System.out.println("just caught an exception");
}
if(outputFile.exists()){
return true;
}
else{
return false;
}
}
public void writeFile(){
writer.println("The first line");
writer.println("The second line");
writer.println("Christos");
}
public void closeWriter(){
writer.close();
System.out.println("Writer closed");
}
}
‌
class UniversityScore{
private String name;
private String country;
private double score;
private int year;
public UniversityScore(String otherName, String otherCountry, double otherScore, int otherYear){
this.name = otherName;
this.country = otherCountry;
this.score = otherScore;
this.year = otherYear;
}
public String getName(){
return name;
}
public String getCountry(){
return country;
}
public double getScore(){
return score;
}
public int getYear(){
return year;
}
public String toString(){
String outputString = name + "\t" + country + "\t" + score + "\t" + year;
return outputString;
}
}
‌
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
class FileEditor{
private HashMap<Integer, ArrayList<UniversityScore>> scores = new HashMap<Integer, ArrayList<UniversityScore>>();
private ArrayList<String> lines;
public FileEditor(ArrayList<String> otherLines){
this.lines = otherLines;
}
public void fillHashMap(){
// that's where I need help
}
}
public class TestFiles {
public static void main(String[] args){
FileReader reader = new FileReader("universities.txt");
if(reader.initReader()){
FileEditor editor = new FileEditor(reader.readFile());
reader.closeReader();
editor.fillHashMap();
FileWriter writer = new FileWriter("universities_2015_output.txt");
if(writer.initWriter()){
writer.writeFile(editor.getScoresOfYear(2015));
writer.closeWriter();
}
else{
System.out.println("Error creating file");
}
System.out.println("Average university score of year 2015: "+editor.getAverageOfYear(2015));
System.out.println("Min university score of year 2015: "+editor.getMinOfYear(2015));
System.out.println("Max university score of year 2015: "+editor.getMaxOfYear(2015));
}
else{
System.out.println("Error opening file");
}
}
}
You will need a way to parse your lines into UniversityScore objects.
Now that you have all the scores, you can add it to your map, according to their year values (may be score but the type doesn't match nor makes practical sense), for example:
for(String line : lines){
String[] vals = line.split(";");
UniversityScore score = new UniversityScore(vals[0],vals[1],Double.parseDouble(vals[2]),Integer.parseInt(vals[3]))
if(scores.containsKey(score.getYear()){ // If the key exists
scores.get(score.getYear()).add(score);
}else{ // If the key doesn't exist, it must be created and added to the map
ArrayList<UniversityScore> newList = new ArrayList<>();
newList.add(score);
scores.put(score.getYear(), newList)
}
}
I noticed your map has an Integer key which corresponds to the year property of a score, so I assumed the map's keys are the years and not the scores as you suggested.
I didn't check if the code works, but it should at least give you an idea on how to fill your map.
It looks like you're being tasked with reading data from a file, and then generating some stats about the data in the file.
Currently, you're simply plopping each line in the ArrayList.
Looks like your next step is to go through each item in that list, and create a UniversityScore object. This is where you will have to parse each string into values that can be assigned to the various fields in the UniversityScore object. When you have done that, put the current line number (as an Integer key) and UniversityScore (as the value) in your HashMap.
Once you have done that, you will have to write the missing methods getScoresOfYear(Integer year), getAverageOfYear(int year), getMinOfYear(int year), and getMaxOfYear(int year) in the editor class.
try this:
public void fillHashMap() {
for(String line : lines) {
String [] fields = line.split(";");
UniversityScores us = new UniversityScores(fields[0], fields[1], fields[2], fields[3]);
if (scores.keySet().contains(us.getScore())) {
scores.get(us.getScore()).add(us);
}
else {
ArrayList<UniversityScores> t = new ArrayList<UniversityScores>();
t.add(us);
scores.put(us.getScore(), t);
}
}
}

How to Store Variable Data back from file in Java

Problem Defined: I store bookname and bookauthor variable data in file using tostring to buffer writer, When i run program next time program read the file but not to store data back to the variable
Please write read code and and variable data storing from file in JAVA
...........................................................................................................................................................
Three Classes One is Main Class,Second is filewriting class and One Class having book add function.Source Code is given here
import java.util.Scanner;
import java.io.*;
public class AddBook extends Filewriting{
public int add;
public AddBook(int add){this.add=add;}
public String bookname[] = new String[15];
public String bookauthor[] = new String[15];
public int price[] = new int[15];
public void addbook(){
for(int i=0;i<add;i++){
System.out.println("Enter the Book Title:");
Scanner input=new Scanner(System.in);
bookname[i]=input.nextLine();
System.out.println("Enter the Book Author:");
Scanner scan=new Scanner(System.in);
bookauthor[i]=input.nextLine();
System.out.println("Enter the Book Price:");
Scanner input1=new Scanner(System.in);
price[i]=input1.nextInt();
}
}
public String toString(int j)
{
return String.format("BookName:%s%nBookAuthor:%s%nBookPrice:%d%n%n................................................................................................................................%n",bookname[j],bookauthor[j],price[j]);
}
}
import java.util.*;
import java.io.*;
public class Filewriting {
public int add;
public void filewriting(){
System.out.println("How many Books you want to added:");
Scanner in=new Scanner(System.in);
add=in.nextInt();
try{
File file = new File("Hello1.txt");
// creates New file
file.createNewFile();
Writer writer = new FileWriter("Hello1.txt",true);
BufferedWriter bufferWriter = new BufferedWriter(writer);
AddBook obj=new AddBook(add);
obj.addbook();
for ( int i = 0; i < add; i++){
// bufferWriter.write(obj.bookname[i] + obj.bookauthor[i] +obj.price[i]);
bufferWriter.write(obj.toString(i));
}
bufferWriter.close();
}
catch(Exception e)
{
}
}
/* // Creates a FileReader Object
FileReader fr = new FileReader(file);
char [] a = new char[50];
fr.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); // prints the characters one by one
fr.close(); */
}
import java.util.Scanner;
import java.io.*;
public class Test{
public static void main(String args[]){
System.out.println("Enter 1 to Add Books:");
System.out.println("Enter 2 to Check Store Books again in Variable:");
Scanner input=new Scanner(System.in);
int i=input.nextInt();
if(i==1){
System.out.println("You Press B");
Filewriting fw=new Filewriting();
fw.filewriting();
}
if(i==2)
{
Filewriting fw=new Filewriting();
AddBook obj=new AddBook(fw.add);
for ( int j = 0; j < 2; j++) // for storing 2 variables data
{
System.out.println(obj.bookname[j]); // just check bookname,shows null
}
}
// Please write code that we read the file as well as data is stored again in Variables
}
}
I see You can write Data in File as not well.From your Code it is impossible to Store data in your variables.You must set and get Methods in your program in order to store variables.Following Program Code is help you to storing file data to variable perfectly.
................................................................................
public class Book {
public String name;
public String author;
public int price;
public Book(){
this("","",0);
}
public Book(String name,String author,int price){
setName(name);
setAuthor(author);
setPrice(price);
}
public void setName(String name){
this.name= name ;
}
public void setAuthor(String author){
this.author = author ;
}
public void setPrice(int price){
this.price = price ;
}
public String getName(){
return name;
}
public String getAuthor(){
return author;
}
public int getPrice(){
return price;
}
}
import java.io.*;
import java.util.*;
public class ReadText {
Scanner input,a;
public void OpenBook(){
File f = new File("Hello1.txt");
if ( f.exists()){
System.out.println("Welcome Ur File IS Open....."+f);
}
else
{
System.out.println("Error... File DOes not exits");
System.exit(1);
}
try {
input = new Scanner(new File("Hello1.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void ReadBook(){
Book b = new Book();
while((input.hasNext())){
b.setName(input.nextLine());
b.setAuthor(input.nextLine());
b.setPrice(Integer.parseInt(input.nextLine()));
System.out.printf("Book Name:%s\nBook Author:%s\nBook Price:%d\n",b.getName(),b.getAuthor(),b.getPrice());
}
}
}

Java Problems With Deserialization

I know that this question has been addressed before,but i simply cannot find the answer no matter how hard i try.
I am trying to serialize and deserialize objects in Java. I am having problems in the deserialization. I do not get the values that were entered, but something along the lines of prueba.Estudiantes#1bd7848. Why do i get this instead of the actual values typed in?
Here is my code
package prueba;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Prueba {
public static void main(String[] args) throws FileNotFoundException,IOException, ClassNotFoundException {
File file = new File("f.txt");
List <Estudiantes> lista = new ArrayList<>();
boolean continuar = true;
while (continuar == true){
Estudiantes es = new Estudiantes();
System.out.println("Ingrese nombre");
Scanner kb = new Scanner(System.in);
es.nombre = kb.nextLine();
System.out.println("Ingrese Apellido");
Scanner kb1 = new Scanner(System.in);
es.apellido = kb1.nextLine();
System.out.println("Ingrese Número");
Scanner kb2 = new Scanner(System.in);
es.numero = kb2.nextInt();
lista.add(es);
FileOutputStream fo = new FileOutputStream(file);
ObjectOutputStream output = new ObjectOutputStream(fo);
for (Estudiantes est: lista){
output.writeObject(est);
}
output.close();
fo.close();
FileInputStream fi = new FileInputStream(file);
ObjectInputStream input = new ObjectInputStream(fi);
ArrayList<Estudiantes> est2 = new ArrayList<Estudiantes>();
try {
while (true){
Estudiantes s = (Estudiantes)input.readObject();
est2.add(s);
}
}
catch (EOFException ex){}
for (Estudiantes s :est2){
System.out.println(s);
fi.close();
input.close();
}
System.out.println("0 para salir; 1 para continuar");
Scanner kb3 = new Scanner(System.in);
int rev = kb3.nextInt();
if (rev == 0){
continuar = false;
System.out.println("Hasta Luego");
}
}
}
}
And here is my Estudiantes class
package prueba;
import java.io.Serializable;
public class Estudiantes implements Serializable{
String nombre, apellido;
int numero;
}
Thanks
I do not get the values that were entered, but something along the lines of prueba.Estudiantes#1bd7848
That's what you get when you explicitly or implicitly call toString() on an object whose class hasn't overridden it.
It isn't evidence that you have a problem.
I think if you are getting the values like prueba.Estudiantes#1bd7848 you are its already been deserialized. You just have to override the toString() properly to get the output. Not sure if this helps
When you try to print your class when reading back the objects you previously wrote you have to implement the toString() method from the Object class here is what I mean.
Change your class to this:
public class Estudiantes implements Serializable {
private static final long serialVersionUID = 123L; // has to be unique
String nombre, apellido;
int numero;
#Override
public String toString() {
System.out.println("first name: " + nombre);
System.out.println("last name: " + apellido);
System.out.println(numero);
return // a string you want to print
}
}

Categories