Separate data and store in ArrayList? - java

I am trying to separate a set of data. I need to store each data into a variable then create an object and put them in an ArrayList.
The dataset is in this format
lastName, firstName
ID num_courses
course1_name
grade units
course2_name
grade units
....
I have done this so far but I'm having trouble creating multiple objects, storing the data, and adding it to an ArrayList[]. Thanks for your time and help (:
public static void main (String[] args) throws FileNotFoundException {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter file name: ");
String fileName = scnr.nextLine();
Scanner inFile = new Scanner(new FileInputStream(fileName)); //importing filename
ArrayList<String> list = new ArrayList<String>(); //for list of courses
String name = "";
String id = "";
int coursesTaken = 0;
String courseName = "";
char grade;
int courseUnit = 0;
while(inFile.hasNextLine()){
name = inFile.nextLine(); //first line is name
StringTokenizer st = new StringTokenizer(inFile.nextLine()); //separting whitespace
id = st.nextToken(); //storing ID
coursesTaken = Integer.parseInt(st.nextToken()); //storing num_courses_taken
Student s1 = new Student(name, id); //FIXME (need more than 1 student object)
for(int i = 0; i < coursesTaken*2; ++i){
courseName = inFile.nextLine();
s1.addCourses(courseName); //adding to arrayList
StringTokenizer st2 = new StringTokenizer(inFile.nextLine());
grade = st2.nextToken().charAt(0);
courseUnit = Integer.parseInt(st2.nextToken());
Course ci = new Course(courseName, grade, courseUnit); //FIXME (need more than 1 course)
}
}
}
Course.java
public class Course {
private String name;
private char grade;
private int units;
//constructors
public Course(){
name = "";
grade = 0;
units = 0;
}
public Course(String name, char grade, int units){
this.name = name;
this.grade = grade;
this.units = units;
}
//getters
public String getName(){
return name;
}
public char getGrade(){
return grade;
}
public int getUnits(){
return units;
}
//setters
public void setName(String name){
this.name = name;
}
public void setGrade(char grade){
this.grade = grade;
}
public void setUnits(int units){
this.units = units;
}
}
Student.java
public class Student {
private String name;
private String id;
private ArrayList<String> listCourses = new ArrayList<String>();
//constructor
//default
public Student(){
name = "none";
id = "none";
//courses = "none";
}
public Student(String name, String id){
this.name = name;
this.id = id;
//this.courses = courses;
}
//getters
public String getName(){
return name;
}
public String getId(){
return id;
}
public ArrayList<String> getCourses(){
return listCourses;
}
//setters
public void setName(String name){
this.name = name;
}
public void setId (String id){
this.id = id;
}
public void addCourses(String courses){
listCourses.add(courses);
}
}

First, you need a List to store your students:
ArrayList<Student> students = new ArrayList<>();
You should add each created student to this list when all fields are parsed:
students.add(s1);
Second, I think, it's better to change the listCourses field from ArrayList<String> to ArrayList<Course> - to store information about all students courses inside the Student object.
Third, you don't need to multiply coursesTaken by 2 because you call inFile.nextLine() twice for each course taken.
for (int i = 0; i < coursesTaken; i++)
Finally your main method would look like this:
private ArrayList<Course> listCourses = new ArrayList<>();
ArrayList<Student> students = new ArrayList<>();
while(inFile.hasNextLine()){
name = inFile.nextLine(); //first line is name
StringTokenizer st = new StringTokenizer(inFile.nextLine()); //separting whitespace
id = st.nextToken(); //storing ID
coursesTaken = Integer.parseInt(st.nextToken()); //storing num_courses_taken
Student s1 = new Student(name, id);
ArrayList<Course> courses = new ArrayList<>();
for(int i = 0; i < coursesTaken; i++){
courseName = inFile.nextLine();
StringTokenizer st2 = new StringTokenizer(inFile.nextLine());
grade = st2.nextToken().charAt(0);
courseUnit = Integer.parseInt(st2.nextToken());
courses.add(new Course(courseName, grade, courseUnit)); //FIXED
}
s1.setListCourses(courses);
students.add(s1); //FIXED
}
UPDATE: Changes in Student class:
public class Student {
private String name;
private String id;
private ArrayList<Course> listCourses = new ArrayList<>();
...
// this is just a setter for listCourses field
public void setListCourses(ArrayList<Course> listCourses) {
this.listCourses = listCourses;
}
}

//for list of courses
That's a list of strings.
This is for a list of courses
List<Course> list = new ArrayList<>();
Then, just list.add(ci) in the loop
Sidenote: Student.addCourses should be singular, and probably accept a Course object

Related

How can I store values from a text file into an array in java

I´m working with text file reads in Java, and I need to store the content of this text files inside of arrays, and the pass it as references for instance a new Class.
This is the structure of my txt file:
OXFORD
Software Engineer, Administracion, Laws
PRINCETON
Maths, Economy, Sociology
This is the class who have the structure of the file:
public class University {
private String name;
private String[] careers;
public University() {
}
public University(String name, String[] careers) {
this.name = name;
this.careers = careers;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String[] getCareers() {
return careers;
}
public void setCareers(String[] careers) {
this.careers = careers;
}
This is the student class, who have a university and career as attribute from the University class:
public class Student {
private String name;
private University university;
private String career;
public Student() {
}
public Student(String name, University university, String career) {
this.name = name;
this.university = university;
this.career = career
}
public String getName(){
return name;
}
public string setName(String name){
this.name = name;
}
public University getUniversity(){
return university;
}
public University setUniversity(University university){
this.university = university;
}
}
As you can see, my careers attribute is an array. I want store the careers and university from the text file in my student careers array. And to do something like this:
Sample input:
System.out.println("Greetings student, to what career you wanna set up to");
//here I wanna type the name of the career from the careers list from the text file
And then have something like this:
Sample expected output:
System.out.println("Congrats new student, your new career is" + career);
This is my main method where I am reading the text file and printing it:
public static void readFiles() throws FileNotFoundException, IOException {
BufferedReader readBuffer = new BufferedReader(new FileReader("C:\\Users\\Roberto\\Documents\\NetBeansProjects\\sistemaBecas\\src\\ficheros\\Universidad.txt"));
String docLine;
ArrayList<String> registerList = new ArrayList<String>();
while ((docLine = readBuffer.readLine()) != null) {
registerList.add(docLine);
}
String[] arrayDocument = registerList.toArray(new String[0]);
for (int i = 0; i < arrayDocument.length; i++) {
System.out.println(Array.get(arrayDocument,i));
}
}
How could I do this?
Try this.
String file = "C:\\Users\\Roberto\\Documents\\NetBeansProjects\\sistemaBecas\\src\\ficheros\\Universidad.txt";
List<String> lines = Files.readAllLines(Paths.get(file));
List<University> universities = new ArrayList<>();
for (int i = 0; i < lines.size(); i += 2)
universities.add(new University(lines.get(i), lines.get(i + 1).split("\\s*,\\s*")));

how to get input for an array of class in java?

I am new in java and I trying to get information
for five students and save them into an array of classes. how can I do this?
I want to use class person for five students whit different informations
import java.io.IOException;
import java.util.*;
public class exam
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
// I want to get and save information in this array
person[] f = new student[5];
}
}
class person defined for get name and family name.
import java.util.*;
public abstract class person {
Scanner scr = new Scanner(System.in);
private String name , fname;
public void SetName() {
System.out.println("enter name and familyNAme :");
name = scr.next();
}
public String getname() {
return name;
}
public void setfname () {
System.out.println("enter familyname:");
fname = scr.next();
}
public String getfname() {
return fname;
}
}
class student that inherits from the class person for get studentID and student Scores .
import java.util.*;
class student extends person {
float[] p = new float[5];
int id , sum ;
float min;
public void inputs() {
System.out.println("enter the id :");
id = scr.nextInt();
}
public void sumation() {
System.out.println("enter points of student:");
sum= 0;
for(int i = 0 ; i<5 ; i++){
p[i]=scr.nextFloat();
sum+=p[i];
}
}
public void miangin() {
min = (float)sum/4;
}
}
So first things first, when creating Java objects, refrain from getting input inside the object so that if you decide to change the way you get input (e.g. transition from command line to GUI) you don't need to modify the Java object.
Second, getters and setters should only get or set. This would save some confusion when debugging since we don't have to check these methods/functions.
So here's the person object:
public abstract class Person {
protected String name, fname;
public Person (String name, String fname) {
this.name = name;
this.fname = fname;
}
public void setName (String name) {
this.name = name;
}
public String getName () {
return name;
}
public void setFname (String fname) {
this.fname = fname;
}
public String getFname () {
return fname;
}
}
And here's the student object (tip: you can make as much constructors as you want to make object creation easier for you):
public class Student extends Person {
private float[] p;
private int id;
public Student (String name, String fname) {
this (name, fname, -1, null);
}
public Student (String name, String fname, int id, float[] p) {
super (name, fname);
this.id = id;
this.p = p;
}
public void setP (float[] p) {
this.p = p;
}
public float[] getP () {
return p;
}
public void setId (int id) {
this.id = id;
}
public int getId () {
return id;
}
public float summation () {
float sum = 0;
for (int i = 0; i < p.length; i++)
sum += p[i];
return sum;
}
public float miangin () {
return summation () / 4.0f;
}
#Override
public String toString () {
return new StringBuilder ()
.append ("Name: ").append (name)
.append (" Family name: ").append (fname)
.append (" Id: ").append (id)
.append (" min: ").append (miangin ())
.toString ();
}
}
And lastly, wherever your main method is, that is where you should get input from. Take note that when you make an array, each index is initialized to null so you still need to instantiate each array index before using. I made a sample below but you can modify it depending on what you need.
import java.util.*;
public class Exam {
Scanner sc;
Person[] people;
Exam () {
sc = new Scanner (System.in);
people = new Person[5];
}
public void getInput () {
for (int i = 0; i < people.length; i++) {
System.out.print ("Enter name: ");
String name = sc.nextLine ();
System.out.print ("Enter family name: ");
String fname = sc.nextLine ();
System.out.print ("Enter id: ");
int id = sc.nextInt (); sc.nextLine ();
System.out.println ("Enter points: ");
float[] points = new float[5];
for (int j = 0; j < points.length; j++) {
System.out.printf ("[%d] ", j + 1);
points[j] = sc.nextFloat (); sc.nextLine ();
}
people[i] = new Student (name, fname, id, points);
}
}
public void printInput () {
for (Person p: people)
System.out.println (p);
}
public void run () {
getInput ();
printInput ();
}
public static void main (String[] args) {
new Exam ().run ();
}
}
Just one last tip, if you ever need dynamic arrays in Java, check out ArrayList.
You can add a class attribute, and then add class information for each student, or you can add a class class, define an array of students in the class class, and add an add student attribute, and you can add students to that class.
First of all, please write class names with capital letter (Student, Exam <...>).
Exam class:
import java.util.Scanner;
public class Exam {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Student[] students = new Student[]{
new Student(),
new Student(),
new Student(),
new Student(),
new Student()
};
for (int i = 0; i < 5; i++) {
students[i].setFirstName();
students[i].setLastName();
students[i].setId();
}
}
}
Person class:
import java.util.Scanner;
public class Person {
String firstName, lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName() {
System.out.println("Type firstName: ");
this.firstName = new Scanner(System.in).next();
}
public String getLastName() {
return lastName;
}
public void setLastName() {
System.out.println("Type lastName: ");
this.lastName = new Scanner(System.in).next();
}
}
Student class:
import java.util.Scanner;
public class Student extends Person{
int id;
public int getId() {
return id;
}
public void setId() {
//Converting String line into Integer by Integer.parseInt(String s)
System.out.println("Type id: ");
this.id = Integer.parseInt(new Scanner(System.in).next());
}
}

How to create a search method for an array

My code is as follows:
import java.io.*;
import java.util.*;
public class readStudents extends Object
{
private String SName = "";
private String DoB = "";
private String Gender = "";
private String Address = "";
Student [] students = new Student[20];
public void fillStudentArray()
{
// properties
int size; // total number of Students in collection
File file = new File("StudentDetails.txt");
try
{
Scanner in = new Scanner(file);
while(in.hasNextLine())
{
String SName = in.next();
String DoB = in.next();
String Gender = in.next();
String Address = in.next();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public String getName()
{
return this.SName;
}
public void printname()
{
System.out.println("hello");
}
public Student search(String name)
{
System.out.print("Enter the name you wish to search: ");
for (int i = 0; i < this.students.length; i++)
{
Student s = this.students[i];
if (s.getName().equalsIgnoreCase(name))
{
return s;
}
}
return null;
}
} //end class students
However I am trying to create a well refined program that I can call on these methods from another main file with as minimal code as possible in that file.
The search method at the bottom is tripping me up as I am assuming I need to put something to do with the array in my getName() method but I can't figure it out.
Since I am doing this as a class for another main method, with the placement of my array initialization and declaration it allows the other methods to access it but it leaves me with no way to create this array from the main method unless I am missing something?
This is the error jCreator is throwing:
F:\University\Ass2\readStudents.java:62: error: cannot find symbol
if (s.getName().equalsIgnoreCase(name))
^
symbol: method getName()
location: variable s of type Student
You never populated the Student students[] array... You retrieved the values you would populate them with here:
while(in.hasNextLine())
{
String SName = in.next();
String DoB = in.next();
String Gender = in.next();
String Address = in.next();
}
But you never actually set those values into a Student object in the students[] array
Do something like this:
int i = 0;
while(in.hasNextLine())
{
String name = in.next();
String dateOfBirth = in.next();
String gender = in.next();
String address = in.next();
students[i] = new Student(name, dateOfBirth, gender, address);
i++
}
Also, you might consider ditching the array and using some sort of List or Hash object... If your file contains more than 20 lines, the array will be out of index when you try to define the 21st value.. With an arraylist or a List you wouldn't have that problem
I took a liberty to tweak your code as previous answer mentioned, it's better to use array list in your case. You could make a small student container class within your reader. The get name method is also kinda redundant ;s
package test;
import java.io.*;
import java.util.*;
public class readStudents{
ArrayList<Student> students = new ArrayList<Student>();
class Student {
private String name;
private String dob;
private String gender;
private String address;
public Student(String name, String dob, String gender, String address) {
this.name = name;
this.dob = dob;
this.gender = gender;
this.address = address;
}
public void fillStudentArray() {
// properties
int size; // total number of Students in collection
File file = new File("StudentDetails.txt");
try {
Scanner in = new Scanner(file);
while (in.hasNextLine()) {
String SName = in.next();
String DoB = in.next();
String Gender = in.next();
String Address = in.next();
students.add(new Student(SName, DoB, Gender, Address));
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public String getName(Student student) {
return student.name;
}
public void printname() {
System.out.println("hello");
}
public Student search(String name) {
System.out.print("Enter the name you wish to search: ");
for (Student student : students) {
if (student.name.equalsIgnoreCase(name))
;
return student;
}
return null;
}
}
}
If you're not forced by your teacher to use for or for-each cycle in the search function - this is how to do a full scan the Java 8 way
public Optional<Student> findFirstByName(final String name) {
return Arrays.stream(students)
.filter(s -> s.getName().equalsIgnoreCase(name))
.findFirst();
}

String ArrayList returning null values

I am new to java and doing some arraylist work, and when compiling my lists just return null values instead of names I have typed in.
I don't understand why this is so, so if anyone could advise/help me that would be great.
Here is my main code
import java.util.*;
public class StudentData
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
ArrayList<Student> studentList = new ArrayList<Student>();
String yesNo = "true";
do
{
System.out.println("Enter student's name: ");
String name = in.next();
Student s = new Student();
studentList.add(s);
String input;
do
{
System.out.println("Would you like to enter data for another student? Yes/No ");
yesNo = in.next();
}
while (!yesNo.equalsIgnoreCase("YES") && !yesNo.equalsIgnoreCase("NO"));
}
while (yesNo.equalsIgnoreCase("YES"));
for(int i = 0; i < studentList.size(); i++)
{
System.out.println(studentList.get(i).getName());
}
}
}
And
class Student
{
private String studentName;
public StudentData(String name)
{
setName(name);
}
public String getName()
{
return studentName;
}
public void setName(String name)
{
studentName = name;
}
}
You're creating a student but didn't set the name :
String name = in.next();
Student s = new Student();
studentList.add(s);
Try with :
String name = in.next();
Student s = new Student();
s.setName(name);
studentList.add(s);
Also replace your constructor. I.e :
public StudentData(String name){
setName(name);
}
should be
public Student(String name) {
setName(name);
}
Then you will be able to do Student s = new Student(name);

conflict b/w string and string[]

Basically I have a class that has methods which use String arrays and i'm writing a method in the application class to read a file and update an array of object of class Customer. I get errors like:
Line 83: set_address(java.lang.String[]) in Customer cannot be applied to (java.lang.String)
at the line review[i].set_address(st[1]). I understand that it is looking for a string[] and it is receiving a string but is there any way to fix this? Here's the code I'm working with.
import java.io.*;
import java.util.*;
class Customer {
int account_id;
char[] ch1 = new char[20];
String name = new String (ch1);
char[] ch2 = new char[80];
String address = new String (ch2);
char[] ch3 = new char[10];
String phone_number = new String (ch3);
char[] ch4 = new char[8];
String date_of_birth = new String (ch4);
double account_balance;
public int get_accountid(){
return account_id;
}
public String get_address(){
return address;
}
public String get_phone_number(){
return phone_number;
}
public String get_date_of_birth(){
return date_of_birth;
}
public double get_balance(){
return account_balance;
}
public void set_account_id(int num){
account_id = num;
}
public void set_address(String add){
address = add;
}
public void set_phone_number(String phone){
phone_number = phone;
}
public void set_date_of_birth(String dob){
date_of_birth = dob;
}
public void set_balance(double bal){
account_balance = bal;
}
Customer(){ // default constructor
}
// parametrized constructor
Customer(int id, String name, String add, String dob, String num, double bal){
this.account_id = id;
this.name = name;
this.address = add;
this.date_of_birth = dob;
this.phone_number = num;
this.account_balance = bal;
}
}
public class lab2{
public static void main(String args[]){
System.out.println("testing this shit");
}
public static void readFile(String filename){
Customer[] review = new Customer[30];
int i=0;
Scanner scan = new Scanner (new File (filename));
while (scan.hasNext()){
while(i<30){
review[i].set_account_id(scan.nextInt());
String[] st = scan.nextLine().split("=");
review[i].set_address(st[1]);
st = scan.nextLine().spilt("=");
review[i].set_phone_number(st[1]);
st = scan.nextLine().split("=");
review[i].set_date_of_birth(st[1]);
//st = scan.nextLine().split("=");
review[i].set_balance(scan.nextDouble());
scan.nextLine();
i=i+1;
}
}
}
}
Your class Customer looks like a Java bean. I find these declaration suspicious:
String[] name = new String [20];
String[] address = new String [80];
String[] phone_number = new String [10];
String[] date_of_birth = new String [8];
Why do you want a Customer to have 20 names, 80 addresses, 10 phone numbers, and 8 date of birth? I suspect that your intention is saying that a Customer name is at most 20 characters long, his/her address is at most 80 characters long, etc. If this is the case, than you don't want a String[], you may want a char[]!
However, think about making those fields simply String: it seems more natural. I don't see reason why you may want to limit their size.
Just change your method signature:
public void set_address(String add){
address = add;
}
Or other choice: You create a new String[] object based on your String object an pass this:

Categories