adding multiple objects to ArrayList is not printing very well - java

import java.util.ArrayList;
import java.util.Scanner;
public class Student {
static String studentNum;
static int age;
static String Name;
Student(int Age, String Name){
this.Name = Name;
this.age = Age;
}
public static String input_read() {
Scanner sc = new Scanner(System.in);
if (sc.hasNext()) {
studentNum = sc.next();
} else {
sc.close();
}
return studentNum;
}
public static int setAge() {
System.out.println("Enter the age of the Student");
return Integer.valueOf(input_read());
}
public static String setName() {
System.out.println("Enter the name of the Student");
return input_read();
}
public static int getAge() {
return age;
}
public static String getName() {
return Name;
}
public static void main(String[] args) {
ArrayList<Student> ar = new ArrayList();
for (int i=0; i<2; i++) {
Student s1= new Student(setAge(), setName());
ar.add(s1);
}
for (Student each :ar){
System.out.println(each.getName());
System.out.println(each.getAge());
}
}
}
I am new guy in Java. I created a program to add student age and name. This program output is printing only last object 2 times. It is not printing all the objects in the list. Anybody know why?

You should remove the keyword static from your member variables.
That is causing them to be shared across all instances.
See here: What does the 'static' keyword do in a class?

Related

How to read a file containing strings and integers into an ArrayList and sort by integer?

I'm trying to read from a text file containing a list of names and grades, organized by line, i.e.:
David Smith 84
Susan L Potter 100
...
Then store them (by line) in an ArrayList, and sort that ArrayList by the students' grade using a selection sort algorithm, however I've tried multiple different ways to code this and every edit seems to prompt another error (I'm extremely new to programming). This is what I currently have:
import java.io.*;
import java.util.*;
public class Grades {
private static void sort(ArrayList<String> list) {
int pFill;
int pTest;
int pSmallest;
String temp;
for (pFill = 0; pFill < list.size(); pFill++) {
pSmallest = pFill;
for (pTest = pFill + 1; pTest < list.size(); pTest++) {
if (pTest < pSmallest) {
pSmallest = pTest;
}
}
temp = list.get(pSmallest);
list.set(pSmallest, list.get(pFill));
list.set(pFill, temp);
}
}
public static void main(String[] args){
ArrayList<String> list = new ArrayList<>();
String fileName = "students.txt";
try (BufferedReader input = new BufferedReader(new FileReader(fileName))) {
while(input.ready()){
list.add(input.readLine());
}
input.close();
sort(list);
System.out.println(list);
} catch (IOException e){
System.out.println(e.getMessage());
}
}
}
You can create a student object to hold name and grade separately. Once you have added all the data into list you can directly use list.sort() method by using Comparator but in your case you want to write selection sort that's why you have to write another method to do selection sort.
package com.stackovflow.problems;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class Grades {
public static void main(String[] args){
ArrayList<Student> list = new ArrayList<>();
String fileName = "students.txt";
try (BufferedReader input = new BufferedReader(new FileReader(fileName))) {
while(input.ready()){
String line = input.readLine().trim();
String name = line.substring(0,line.lastIndexOf(' '));
int grade = Integer.parseInt(line.substring(line.lastIndexOf(' ')+1));
list.add(new Student(name, grade));
}
input.close();
selectionSort(list);
System.out.println(list);
} catch (IOException e){
System.out.println(e.getMessage());
}
}
private static void selectionSort(ArrayList<Student> list) {
int pFill;
int pTest;
int pSmallest;
Student temp;
for (pFill = 0; pFill < list.size(); pFill++) {
pSmallest = pFill;
for (pTest = pFill + 1; pTest < list.size(); pTest++) {
Student pTestStudent = list.get(pTest);
Student pSmallestStudent = list.get(pSmallest);
if (pTestStudent.getGrade() < pSmallestStudent.getGrade()) {
pSmallest = pTest;
}
}
if(pSmallest!=pFill) {
temp = list.get(pSmallest);
list.set(pSmallest, list.get(pFill));
list.set(pFill, temp);
}
}
}
}
//This class is to hold line data in your students.txt file
class Student{
private String name;
private int grade;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public Student(String name, int grade) {
super();
this.name = name;
this.grade = grade;
}
#Override
public String toString() {
return "Student [name=" + name + ", grade=" + grade + "]";
}
}
It will be easy if you declare a Student class with 2 fields name and age. And you can make the Student class implement Comparable and compare on the basis of grade. It will look something like this:
public class Student implements Comparable<Student> {
private final String name;
private final int grade;
public Student(String name, int grade) {
this.name = name;
this.grade = grade;
}
#Override
public int compareTo(Student s) {
return Integer.compare(this.grade, grade);
}
}
To populate the Student object you will need to split the String and extract the name and grade, and then call new Student(name, grade).
In your sort method you can pass a List<Student> where you can compare 2 students (as Student implements Comparable<Student>) by calling something like s1.compareTo(s2).
Once you got the list of student. You can use Comparator to do this.
List<Student> sorted=list.sort(Comparator.comparing(p-> p.getGrade()));
Or use stream api
List<Person> result =list.stream().sorted((p1, p2)>p1.getGrade().compareTo(p2.getGrade())).collect(Collectors.toList());
Create a separate Student.java file in the same folder to hold the Student class:
public class Student {
private final String name;
private final int grade;
public Student(String name, int grade) {
this.name = name;
this.grade = grade;
}
public String getName(){
return name;
}
public int getGrade(){
return grade;
}
}
Then split each line by space and set the first tokens as the name and the last as the grade, then use Comparator to sort the ArrayList of Student Objects:
import java.io.*;
import java.util.*;
public class Grades {
private static ArrayList<Student> sort(ArrayList<String> list) {
ArrayList<Student> students = new ArrayList<Student>();
String name = "";
int grade;
for (String line : list) {
String[] splitted = line.split("\\s+");
for(int i = 0;i< splitted.length-1;i++){
name += splitted[i] + " ";
}
grade = Integer.parseInt(splitted[splitted.length-1]);
students.add(new Student(name,grade));
name = "";
}
students.sort(Comparator.comparing(student-> student.getGrade()));
return students;
}
public static void main(String[] args){
ArrayList<String> list = new ArrayList<>();
String fileName = "students.txt";
try (BufferedReader input = new BufferedReader(new FileReader(fileName))) {
while(input.ready()){
list.add(input.readLine());
}
input.close();
ArrayList<Student> sortedStudents = sort(list);
for (Student currentStudent : sortedStudents)
System.out.println(currentStudent.getName() + currentStudent.getGrade());
} catch (IOException e){
System.out.println(e.getMessage());
}
}
}

Error while printing out arraylist elements

Here is a small program which adds and print out workers. When calling a method to print I receive an output with identical elements as many times as the number of elements I have added. I cant understand where is my mistake.
public class Radnik {
static List<Radnik> workers = new ArrayList<>();
private String name;
public static void main (String []args) {
Radnik.add();
for(Radnik r : workers) {
System.out.println(r);
}
}
public static void add () {
String name;
String answer;
do {
Scanner s = new Scanner(System.in);
System.out.println("name");
name = s.next();
Radnik f = new Radnik();
workers.add(f);
System.out.println("More");
answer = s.next();
} while (answer.equals("yes"));
}
}
You never set the name to a Radnik.
I would add the constructor Radnik(String name) to initialize name and also add an getter and setter.
System.out.println(r) will only print nonsense because it calls Object.toString(). You have to override toString() or call another method to output something meaningful.
public class Radnik {
static List<Radnik> workers = new ArrayList<>();
private String name;
public Radnik(String name) {
this.name = name;
}
public String getName() {
return name;
}
#Override
public String toString() {
return "Radnik=[name=\""+name+"\"]";
}
public static void main (String []args) {
Radnik.add();
for(Radnik r : workers) {
System.out.println(r);
}
}
public static void add () {
String name;
String answer;
do{
Scanner s = new Scanner(System.in);
System.out.println("name");
name = s.next();
Radnik f = new Radnik(name);
workers.add(f);
System.out.println("More");
answer = s.next();
} while (answer.equals("yes"));
}
}
public class MainClass{
private static List<Radnik> workers = new ArrayList<>();
public static void main (String []args) {
new MainClass().add();
for(Radnik r : workers) {
System.out.println(r.getName());
}
}
public void add () {
String name;
String answer;
do{
Scanner s = new Scanner(System.in);
System.out.println("name");
name = s.next();
Radnik f = new Radnik();
f.setName(name);
workers.add(f);
System.out.println("More");
answer = s.next();
} while (answer.equals("yes"));
}
public class Radnik {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}

cannot set the value of string from the main class into setter

public class StudentTest{
public static void main(String args[]){
UnderGrad uG1 = new UnderGrad();
uG1.setName("John");
uG1.setMatric("0192345");
System.out.println("Undergarduate Student Info");
uG1.setCourse(new Course("CS1103",3));
uG1.setCourse(new Course("IT4504",3));
uG1.displayStudentInfo();
System.out.println(" ");
PostGrad pG1 = new PostGrad();
pG1.setName("Sam");
pG1.setMatric("G015466");
pG1.setResearch("Empirical Software Engineering");
pG1.setResearch("Data Mining");
System.out.println("Postgrad Student Info");
pG1.displayStudentInfo();
}
}
public class Course{
private String courseName;
private int crhour;
public Course(String n, int c){
courseName = n;
crhour = c;
}
public void setCourseName(String course){
courseName = course;
}
public String getCourseName(){
return courseName;
}
public void setCreditH(int c){
crhour = c;
}
}
public class Student{
private String matric ="-matric required-";
private String name="-name required-";
public Student(){
}
public void setName(String n){
if (n.matches("[a-zA-Z]+") == false)
System.out.println("Invalid Name");
else
name = n;
}
public String getName(){
return name;}
public void setMatric(String m){
matric = m;}
public String getMatric(){
return matric;}
}
public class UnderGrad extends Student{
private Course courseList[];
private int index = 0;
public UnderGrad(){
Course courseList[] =new Course[7];}
public void setCourse(Course courseName){
//Course courseList[]= new Course[2];
}
public Course[] getCourse(){
return courseList;}
public void displayStudentInfo(){
System.out.println("Name: "+getName());
System.out.println("Matric: "+getMatric());
System.out.println("Course List: "+getCourse());
}}
public class PostGrad extends Student{
private String researchArea[];
private int index = 0;
public PostGrad()
{
researchArea = new String[5];
}
public void setResearch(String research){
for(index=0;index<2;index++){
researchArea[index]=research;}
}
public String[] getResearch(){
return researchArea;}
public void displayStudentInfo(){
System.out.println("Name: "+getName());
System.out.println("Matric: "+getMatric());
System.out.println("Research List: "+getResearch());
}}
Output:
Undergarduate Student Info
Name: John
Matric: 0192345
Course List: null
Postgrad Student Info
Name: Sam
Matric: G015466
Course List: [Ljava.lang.String;#2ac9fefa
The problem I cant get the value of String of the course an the research. What should I do?Should I use super reference?
Here:
System.out.println("Course List: "+getCourse());
You're printing out the default toString() returned by an array of String. Don't do that. Iterate through the array and print each item or else use java.util.Arrays.toString(...).
System.out.println("Course List: "+ java.util.Arrays.toString(getCourse()));
You will also need to give your Course class a valid toString() method, one that returns the courseName and perhaps the credit hours. Also I would change the course field to courses or courseList to reflect that it does not represent one single course but rather a collection of courses. Likewise the getter method should reflect the field name change.

How to add an integer to my arraylist?

I currently have my code set up so a student's name and subject is added to my arraylist, and then printed when user is done. How ever as I'm not wanting to add a string now, I want to add a student number, i'm unfamiliar with how to go about this. I have tried replacing set with add, and string with int, but to no prevail.
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();
System.out.println("Enter student's subject: ");
String subject = in.next();
System.out.println("Enter student's number: ");
int number = in.nextInt();
Student s = new Student(name,subject,number);
s.setName(name);
s.setSubject(subject);
s.Number.add(number);
studentList.add(s);
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());
System.out.println(studentList.get(i).getSubject());
}
}
}
and
class Student
{
private String studentName;
private String studentSubject;
public Student(String name, String subject, int number )
{
setName(name);
setSubject(subject);
Number.add(number);
}
public String getName()
{
return studentName;
}
public void setName(String name)
{
studentName = name;
}
public String getSubject()
{
return studentSubject;
}
public void setSubject(String subject)
{
studentSubject = subject;
}
public int getNumber()
{
return studentNumber;
}
public void Number.add(int number)
{
studentNumber = number;
}
}
As you are storing Student objects in your list you are also storing the member variables of each object as you entered them. So no different approach needs to be taken to store an integer.
You can declare your private int studentNumber; in your student class, add a getter and a setter for it and then modify your constructor so that setStudentNumber(number); would work in the same way as setting your two Strings up.
Then to iterate through your list you could make use of the 'enhanced-for' syntax instead of a plain old for loop, meaning:
for (Student s : studentList) {
System.out.println(s.getName());
System.out.println(s.getSubject());
System.out.println(s.getStudentNumber());
}
Hope that this helps, if you need anything more just give me a shout below.

Using multiple classes java

I would like to know how to use multiples clas in Java. I know how use method from other class and also constructors but i would like know how create a new "object" for example. If i am making a PersonDirectory, then i can have class called Person which has the attributes Name and Age. Then i want to make a Person[] in my PersonDirectory Class and add names and ages to it. How can i do that? I have some code that i did, but it doesn't seem to work out.
import java.io.*;
public class PersonDirectory {
static BufferedReader br = new BufferedReader
(new InputStreamReader(System.in));
static Person[] personArray = new Person[2];
public static void main(String[] args) throws IOException{
for (int i = 0; i < personArray.length; i++) {
System.out.print("Please enter the name of the person: ");
String name = br.readLine();
System.out.print("Please enter the age of the person: ");
int age = Integer.parseInt(br.readLine());
personArray[i] = new Person(name,age);
}
for(Person p : personArray) {
System.out.println("The name is "+p.getName()+" and the age is "+p.getAge());
}
}
}
second class
public class Person {
private static String name = "";
private static int age = 0;
public Person(String name,int age) {
this.name = name;
this.age = age;
}
public static String getName() {
return name;
}
public static int getAge() {
return age;
}
}
This is because the properties in the Person class are static. Static means that they are shared between all object(instances). Remove the static keyword from the Person class and you will be fine.

Categories

Resources