Hi
i m new in java
i want to create one to many objects it depends of the user how many objects he wants to create
for a test the user can put a name and age then these entries will be saved to a hasmap then to a file in a disk
please see my code
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// Classes can contain
// 1. Data
// 2. Subroutines (methods)
}
public class App {
public static void main(String[] args) {
File file = new File("texte.txt");//creating a file named texte.txt
Scanner input=new Scanner(System.in);
//HashMap<String, Integer> map = new HashMap<String,Integer>();
HashMap<Integer,String> map1 = new HashMap<Integer,String>();
int i=0;
System.out.println("Enter a Value: ");// asking how many objects wants to create
int valeur=input.nextInt();
while(i<valeur){
System.out.println("Enter a name: ");// creating name
String nom=input.next();
System.out.println("Enter age: ");// creating age
int sine=input.nextInt();
Person personi=new Person();// creating object personi where i is the value..not sure if it //is correct
personi.setName(nom);
personi.setAge(sine);
//map.put(nom, sine);
map1.put(sine,nom);
i++;
try (BufferedWriter br = new BufferedWriter(new FileWriter(file))) {
br.write(map1);// write the map1 to a file
br.newLine();
} catch (IOException e) {
System.out.println("Unable to read file " + file.toString());
}
}
for(Map.Entry<Integer,String> entry: map1.entrySet()) {
int key = entry.getKey();
String value = entry.getValue();
System.out.println("Name is "+value + " and has " + key+" old age");
}
// Create a Person object using the Person class
// Person person1 = new Person();
// person1.setName(name);
// person1.setAge(age);
// System.out.println("Name :"+person1.getName());
// System.out.println("Age :"+person1.getAge());
// Create a second Person object
}
}