I am working on a Java app for a school project where we have to enter user information: Name, Student ID and their points. How can I store all the data for each user on an ArrayList (or an Array or really whatever type) so I can keep track of all the data.
Example:
John Doe - 401712 - 20 points
Jack Young - 664611 - 30 points
The I want to be able to call methods like setPoints to change the point values for whatever the student selected is.
Here's the problem: How can I link the ArrayList together. If I have three ArrayLists, how does Java know what name, student id and points are associated together?
All the ArrayLists are stored in a class called Data.
Data data = new Data();
Also, all the ArrayLists in the Data class should be outputted to a file which will be loaded next time the app is opened.
I will try to answer any questions.
You need to define a class which contain 3 data fields as follows
Name
Student ID
their points
But not to forget, the class has to have other necessary elements of a class like:
Constructor
Overloaded Constructors if they are necessary
Accessors
Mutators
Note: For accessing each part of an object in your arrayList, you can use accessors. For manipulating each part of an object in your arrayList, you can use mustators.
After having such a class, you can define a arrayList that contain elements with type of class you have already define
Like:
List<Your Type of class > students = new ArrayList<Your Type of class>;
After Java 7, you can do
List<Your Type of class > students = new ArrayList<>;
which is diamond inference.
If you are looking for a specific id number in your arrayList, you can do something like:
public boolean findIdNumber(int idNumber){
for(int i=0; i< students.size; i++)
if(students.get(i).getID() == idNumber)
return true;
else
return false;
}
Warning:
what I have done are suggestions for you to be able to look for what you want smoother. You need to do necessary changes in order to comply what you were
asked to do
You need to create a class named Student, and then declare an array/ArrayList of the Student type. Your Student class must have a constructor that sets the fields of an instance of the Student class (the created instance is now called an object).
So first create a Student class in the same package in which your other class is (the class in which your main method is):
public class Student {
private String firstName;
private String lastName;
private String studentId;
private int points;
public Student(String firstName, String lastName, String studentId, int points) {
this.firstName = firstName;
this.lastName = lastName;
this.studentId = studentId;
this.points = points;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
}
Then in your main method or wherever you like, create a Hashmap to hold your Student objects. A map/hashmap is a collection just like an ArrayList to hold a set of objects. In your use case, it is better to use a hashmap because finding/retrieving a specific student object is much faster and easier when you use a hashmap.
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
// a map is a "key-value" store which helps you search items quickly
// (by only one lookup)
// here you consider a unique value of each object as its 'key' in the map,
// and you store the whole object as the value for that key.
// that is why we defined Student as the second type in the following
// HashMap, it is the type of the "value" we are going to store
// in each entry of this map.
Map<String, Student> students = new HashMap<String, Student>();
Student john = new Student("John", "Doe", "401712", 20);
Student jack = new Student("Jack", "Young", "664611", 30);
students.put("401712", john);
students.put("664611", jack);
Student johnRetrieved = students.get("401712");
// each hashmap has a get() method that retrieves the object with this
// specific "key".
// The following line retrieves the student object with the key "664611".
Student jackRetrieved = students.get("664611");
// set/overwrite the points "field" of this specific student "object" to 40
johnRetrieved.setPoints(40);
int johnsPoints = johnRetrieved.getPoints();
// the value of johnsPoints "local variable" should now be 40
}
}
The classical object-oriented approach would be to create a Student class including name, ID and points and storing list of Student objects in a single ArrayList.
class Student{
private String id;
private String name;
private int points;
public Student(String id, String, name, int points){
this.id = id;
this.name = name;
this.points = points;
}
}
..
ArrayList<Student> students = new ArrayList<Student>();
students.add(new Student(1, 'John Doe', 1000));
String id = students.get(0).id;
Related
Problem:
I'm trying to figure out how to access the Student Array class in order to create four entries for each Student object, but I'm not sure how to do so, while also allowing the program to create more than just one Student.
public class ClassRoster<T> {
public static void main(String[]args) {
ClassRoster<Student> classroster = new ClassRoster<Student>();
Scanner keyboard = new Scanner(System.in);
System.out.println("Add/Drop/Search?");
String action = keyboard.nextLine();
boolean done = false;
Object temp, c, d, e;
int fresh, soph, jun, sen;
Student test = new Student();
while(!done) {
if(action.equalsIgnoreCase("Add"))
{
int counter = 0;
System.out.print("Enter Student ID");
temp = test.setID(keyboard.nextInt());
System.out.println("First name?");
c = test.setFirstName(keyboard.nextLine());
System.out.println("Last name?");
d = test.setLastName(keyboard.nextLine());
System.out.println("Academic Level?");
e = test.setLevel(keyboard.nextLine());
...
}
And I have another class called Student, where there are four different data entries (ID, FirstName, LastName, Academic Level).
I'm not sure how to access the object which I have created in the correct way. It just gives me an error in this Driver class, and I don't know how to correctly access the array bag.
but I'm not sure how to do so while also allowing the program to create more than just one Student
Currently you are only creating one specific instance of student with Student test = new Student(); To actually create more than one student, you will have to iterate the whole process of reading all four data entries (ID, FirstName, LastName, Academic Level). Instead of having to initialize the fields (your four data entries) with specific set methods, I would recommend you letting the Student class initialize them with the class constructor. Meaning the Student class should look something like this:
public class Student{
private final int ID;
private final String firstname;
private final String lastname;
private String level;
public Student(int ID, String firstname, String lastname, String level){
this.ID = ID;
this.firstname = firstname;
this.lastname = lastname;
this.level = level;
}
ID, firstname and lastname are set to final as you foresee them not to change. However the academic level is ought to change and therefore is not set to final. Now that you have set up a constructor for your Student class, we can get to how to allow the program to insert multiple students at once.
public static void main(String[]args) {
ClassRoster<Student> classroster = new ClassRoster<Student>();
Scanner keyboard = new Scanner(System.in);
System.out.println("Add/Drop/Search?");
String action = keyboard.nextLine();
boolean done = false;
while(!done) {
if(action.equalsIgnoreCase("Add")) {
System.out.print("Enter Student ID");
int ID = keyboard.nextInt();
System.out.println("First name?");
String firstname = keyboard.nextLine();
System.out.println("Last name?");
String lastname = keyboard.nextLine();
System.out.println("Academic Level?");
String level = keyboard.nextLine();
Student student = new Student(ID, firstname, lastname, level);
//we have now created a new instance of Student, now we have to save it in your classroster
classroster.add(student);
}
System.out.println("Next action?");
action = keyboard.nextLine();
if(action.equals("done") done = true; //if you write 'done', your loop will finish executing
}
I don't know about your implementation of classroster, but I assume you have implemented it with some kind of list or map, which is why I call the add(Student s) method after creating an instance of Student. To actually then access all students, you will have to implement a method in classroster that returns the saved list of classroster and then iterate through the returned list in the main loop. To actually see what the students look like, you will also have to implement methods for the student instances to for example print out their full names.
I see that you are having a little trouble with arrays, maps and lists as you don't know how to access your students yet. I recommend you reading up on the difference between these three data structure types and simply try to implement them in a small example to see how they work.
I'm not too sure how to word this so it makes sense, but I'll try my best.
Say I have 2 classes. My main class, and a Person class.
My main class will create some Objects from the Person class like this
public class Example {
static Person bob = new Person(23);//Age
static Person fred = new Person(34);
static Person John = new Person(28);
//..and so on
public static void main(String args[]){
..
}
}
and in my Person class..
public class Person{
private int age;
public Person(int age){
this.age = age;
}
public int getAge(){
return this.age;
}
}
Now, if I wanted the age of fred, I'd just call Fred.getAge();.
But, in my program, I don't know what person I'm getting the age of. It randomly selects one, and I need to get the name without directly calling the object. For example, I would have something like this in my Person class:
public static Object getPerson(){
//Some code to get a random integer value and store it it Var
switch(Var){
case 1:
return bob;
case 2:
return fred;
case 3:
return john;
}
}
What I would expect this to do is return an Object that I could then use like this:
public static void main(String args[]){
System.out.println(Person.getPerson().getAge());
}
What I thought that would have done was first call getPerson() which randomly returns either bob, fred, or john, and then it would call getAge(). So if getPerson() returned fred then it would be the same as doing fred.getAge();
Now, this doesnt work, and this was the only way I thought of that made sense to me.
How do I do this so it actually does what I want?
I'm very new to Java, and OOP, and this is my first time really working with different Objects. So I'm sorry if I'm using the wrong terms and explaining things weirdly.
Change
public static Object getPerson(){
to
public static Person getPerson(){
You can't call getAge on an Object, because the Object type does not have getAge() defined.
Why not put the name as a property of the Person class?
class Person {
// ... your existing code for age...
private String name;
String getName() { return name; }
// add name to constructor...
public Person(String name, int age) {
// set them up here...
}
}
The way I see it, is that name is for you as a human, but variables john are irrelivant to the program and computer.... you can even use p1 = Person("Joe", 42);
To get a person by age, you can use a Map with age as key, and person as value.
It could be the case that this is a misunderstanding, but how I'm interpreting the issue is as follows:
You need a (better) place to store all of your Person objects instead of having them as static variables.
You need a way to randomly select from wherever you're storing those objects.
Let's address the main issue first. You're creating these as static variables when they probably shouldn't be; they should just be created as entries into an array.
The way to do this is through this declaration:
Person[] people = new Person[] {new Person(23), new Person(34), new Person(28)};
The main issue now is that you have no way to refer to which person's age belongs to whom since you haven't attached a name field to any of these instances. You could do that easily:
public class Person {
private String name;
private String age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// getters for name and age
}
...then you can instantiate your Person with two values.
new Person("Bob", 23);
Now that we've addressed one concern (which was where to store the people in the first place), now we need a way to randomly access them.
For that, we can use Random#nextInt().
Random rand = new Random();
System.out.println("Person's age - " + people[rand.nextInt(people.length)]);
This will randomly pull a Person out of the array and print their age.
If you want to get a random person within the person class you could store a reference to each person created, and then select randomly from that list
public class Person {
// A List of every Person Created.
private static final List<Person> allPeople = new ArrayList<People>();
// A source of random numbers
private static final Random rand = new Random();
...
public Person(int age) {
...
// Every time we create a new Person, store a reference to that person.
addPerson(this);
}
// synchronized as ArrayLists are not thread safe.
private static synchronized addPerson(Person person) {
allPeople.add(person);
}
...
public static Person getRandomPerson() {
// Get a random number between zero and the size of the list.
int random = rand.nextInt(allPeople.size() -1);
return allPeople.get(random);
}
Now this code is not what I would do in a production environment but it the question sounds like an exercise. A better way would be to store the people created in a List in your Example class. But trying to answer the question as you asked it.
I'm new to programming and I was wondering how I would store values into variables in a class using arrays if I'm getting the values from a .txt file. The values would be either strings or ints, how would you adjust to make this work? Here is the text from the txt. file.
Kobe Bryant
USA
4250000
25
21.03
NBA
Lebron James
USA
6450000
27
21.03
NBA
So I need to store each set of 6 values into 6 separate variables in a class using an array. The second index of the array will call the next 6 values.
Create a Class which contains name, country, Salary, age etc.
Create a List of yourClass instances.
Read from file and store them in the list.
class Person {
private String name;
private String country;
private int salary;
private int age;
private double someValue;
private String league;
public Person() { }
public Person(String name, String country, int salary, int age, double someValue, String league) { //set them }
//add setX and getX methods
}
In you main class:
List<Person> persons = new ArrayList<>();
Create a class which contains all the necessary details you want to store in the array list. Then write the details on the text file and using the file concept read the data from the file and create an Array list object to store the data into an array list.
First it starts off with the class College tester, it askes the user for a command.
The first command will be to add. what adding does is it askes the user to enter a name ( with at least 2 words by identifying a space) and an address.
Then it creates a student object with it. and I add the student object to a arraylist.
Issue #1: How would i add the collegetester input and create a student object out of it
Issue #2: after how would i add it to the array College
Collegetester (where i get user input)
import java.util.Scanner;
public class CollegeTester {
Scanner input = new Scanner(System. in );
private String command;
public String name;
public static void main(String[] args) {
CollegeTester collegeTester = new CollegeTester(); //creates object
collegeTester.getCommand(); //goes to command
}
//Ask user for a command
public void getCommand() {
System.out.println("Enter a command: ");
command = input.nextLine();
if (command.equals("add"))
addCommand(); //If command is add go to addcommand
}
//Add name and address to student object
public void addCommand() {
String name = "";
do {
System.out.println("Enter a Name: ");
name = input.nextLine();
} while (!(name.contains(Character.toString(' ')))); //To check if the name has at least 2 words
System.out.println("Enter an Address: ");
String address = input.nextLine();
Student student = new Student(name, address);
getCommand(); //repeat to see if user wishes to add another
}
}
Student object (The student object)
public Student(String name, String address) {
if (name == null)
name = "";
if (address == null)
address = "";
this.name = name;
this.address = address;
lastAssignedNumber++;
studentNum = lastAssignedNumber;
}
and the arraylist (In a different file)
import java.util.ArrayList;
public class College {
private ArrayList <College> entries = new ArrayList<College>();
}
Let's do a quick analysis of your code:
Your Student object looks like a constructor for the Student class object type which is most likely in this case an inner class of the CollegeTester class.
So here's the deal, your addCommand() already connects your CollegeTester class with your Student class, by executing this command after you provide the input for name and address it creates a new instance of the Student object.
This means that at this point, you need to add this newly created Student object to your College list.
However if you take a good look at your College list you will see that:
It's marked private (meaning it can be accessed only from within itself)
It is a list of College type objects (but you need a list of Student type objects)
So your options at this point are:
Make the list public
Create a public setter method that will do the adding
You will also need to change the list object type to Student if you wish to store Student objects in the list.
Also unless you want to have multiple colleges you might consider declaring your list as static otherwise you will have to declare an instance of it to add the Student objects to it.
Hopefully this is enough information to get you started in the right direction.
Also an advice is to not look at classes as actual objects, instead look at them as blueprints that can be used to construct those real objects.
The main method should call a constructor in the Object array class that create's the Object CollegeTester ct.
ct = new CollegeTester();
Then a method to insert new students, that calls the Student constructor in the student class to create a new student Object.
ct.insert("input1", "input2");
write an insert method that calls to create a new student and adds that object to College.
Constructor to add values to the new student object:
String studentName;
String studentAddress;
public Student(String name, String address) {
studentName = name;
studentAddress = address;
}
note: with ArrayList you could simply use the method add of ArrayList.
I want to pull data from a database. Name, Age, Sex, Location.(maybe more fields)
I want to hold the data in an object similar to how I would expect it to look in a JSON object.
Like:
myData{
row1[name:beavis, age:48, sex:male, location:Joburg]
row2[name:quintus, age:43, sex:, location:Helsinki]
...up to say 500 rows
}
So i'd like to be able to do tempName = row(i).name and so on in java.
Any suggestions.
// Defines a Person datatype
public class Person {
// fields
private String name;
private int age;
private String location;
// gets the value of a field
public String getName() {
return name;
}
// sets the value of a field
public void setName(aName) {
this.name = aName;
}
}
What I did here was define a Person type with a number of fields. Also I give here an example of a setter and getter for the name field. You can put them in an array or collection. For example:
Person people[] = new Person[2];
people[0] = new Person();
people[0].setName("Alice");
You can also dispense with the setters and getters by making the fields public, but I wouldn't recommend it.
A straight translation of that data structure would be along the lines of
List<Map<String, Object>> myData
so you'd be able to call
tempName = (String) myData.get(i).get("name");
Like the JSON array, this doesn't enforce typing (which you'll have to deal with explicitly in Java) and doesn't limit the fields to only those from the database.
If all the database values are strings, things get cleaner as no casts are necessary.
List<Map<String, String>> myData
tempName = myData.get(i).get("name");