Java Print Array With External Method - java

I'm making a program to display the names, ages and gpa's of a class which has been stored in an array. I made the Student class with a constructor, accessors and a method to print out the details.
In the main method, I populate the array and want to display all of the items in the array (this is what I'm having trouble with).
This is what I have so far:
public class Student {
private String name;
private int age;
private double gpa;
public Student(String studentName, int studentAge, double studentGpa) {
this.name = studentName;
this.age = studentAge;
this.gpa = studentGpa;
}
//Normal accessors, not going to bother putting them on here.
public void printStudents() {
System.out.println("Name: " + name + ", Age: " + age + ", GPA: " + gpa);
}
//New class, imagine it's on a different file
public class MyClass {
private static Student [] students = new Student[3];
System.out.println("Students in my class");
students[0] = new Student("Mark",16,77.6);
students[1] = new Student("Sam",17,56.9);
students[2] = new Student("Polly",16,97.4);
for (int g = 0; g < students.length; g++) {
//This is where I'm stuck, I'm not sure how to call printStudents here. students.printStudents didn't work for some reason.

class Student {
private String name;
private int age;
private double gpa;
public Student(String studentName, int studentAge, double studentGpa) {
this.name = studentName;
this.age = studentAge;
this.gpa = studentGpa;
}
public void printStudent() {
System.out.println("Name : "+this.name);
System.out.println("Age : "+this.age);
System.out.println("GPA : "+this.gpa);
}
}
public class MyClass {
public static void main(String s[])
{
Student [] students = new Student[3];
System.out.println("Students in my class");
students[0] = new Student("Mark",16,77.6);
students[1] = new Student("Sam",17,56.9);
students[2] = new Student("Polly",16,97.4);
for (int i = 0; i <=(students.length-1); i++) {
students[i].printStudent();
}
}
}

As #Hello_World mentioned in the comments - change printStudents method name to printStudent to make more sense. It is a public method of the Student object, which means you access it directly from the instance of the object (for example students[0].printStudent()). Also you can iterate through an Array with a foreach cycle, which is a bit easier to read.
students[0] = new Student("Mark", 16, 77.6);
students[1] = new Student("Sam", 17, 56.9);
students[2] = new Student("Polly", 16, 97.4);
for (Student student : students) {
student.printStudent();
}

Related

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());
}
}

Why is there multiple output when I call from an arraylist?

import java.util.ArrayList;
class BryanList{
public static void main (String [] args)
{
ArrayList<String> alist=new ArrayList<String>();
alist.add("Bryan");
alist.add("18");
alist.add("Chicken Rice");
for (int i = 0; i <= alist.size(); i++) {
System.out.println ("My Name: "+alist.get(i));
System.out.println ("Age: "+alist.get(i));
System.out.println ("Favourite food: "+alist.get(i));
}
}
}
How come its not just displaying just one output instead there's 3 of the same output? Does anyone have any solution for this? Thanks.
If you want one time output then use generics class structure.
Create one class which you want to save records.
class Menu {
public int age;
public String name;
public String favFood;
}
You can create getter/setter method if you need. Otherwise just declare variables with public keyword.
Create one ArrayList which will store object of Menu class.
ArrayList<Menu> alist = new ArrayList<Menu>();
Menu menu = new Menu();
menu.name = "Bryan";
menu.age = 18;
menu.favFood = "Chicken Rice";
alist.add(menu);
Print output
for (int i = 0; i <= alist.size(); i++) {
Menu menu = alist.get(i);
System.out.println("My Name: " + menu.name);
System.out.println("Age: " + menu.age);
System.out.println("Favourite food: " + menu.favFood);
}
I updated your class with your requirement, please check.
class BryanList {
public static void main(String[] args) {
ArrayList<Menu> alist = new ArrayList<Menu>();
Menu menu = new Menu();
menu.name = "Bryan";
menu.age = 18;
menu.favFood = "Chicken Rice";
alist.add(menu);
for (int i = 0; i <= alist.size(); i++) {
Menu menu = alist.get(i);
System.out.println("My Name: " + menu.name);
System.out.println("Age: " + menu.age);
System.out.println("Favourite food: " + menu.favFood);
}
}
}
class Menu {
public int age;
public String name;
public String favFood;
}
Happy coding :)
Your loop check is happening on alist.size() which is in your case 3.
Now, in each iteration, it's printing alist.get(i) 3 times.
Suggestion:
Use POJO and add it to your list.
public class Person{
String name;
int age;
String favFood;
public getName(){
return name;
}
public getAge(){
return age;
}
public getFavFood(){
return favFood;
}
public setName(String name){
this.name = name;
}
public setName(int age){
this.age = age;
}
public setName(String favFood){
this.favFood = favFood;
}
}
And now, your code will work with simple modification.
public static void main (String [] args){
ArrayList<String> alist=new ArrayList<String>();
Person person = new Person();
person.setName("Bryan");
person.setAge(18);
person.setFavFood("Chicken Rice");
// If you want multiple person to add, you need to use loops, and that way you can keep creating person objects and add them to list.
// Suggesting, use separate method for that logic.
alist.add(person);
for (int i = 0; i <= alist.size(); i++) {
Person p = alist.get(i);
System.out.println ("My Name: "+ p.getName());
System.out.println ("Age: "+ p.getAge());
System.out.println ("Favourite food: "+ p.getFavFood());
}
}
Because your printing codes in a For loop. And loop is running 3 three times
alist.size()
means 3, you have 3 item in that list.
This can be your object class:
public class Table {
int age;
String name;
String food;
public Table(int age, String name, String food) {
this.age = age;
this.name = name;
this.food = food;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFood() {
return food;
}
public void setFood(String food) {
this.food = food;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And fill arraylist with your object:
public static void main(String[] args) {
ArrayList<Table> alist = new ArrayList<>();
// this is how you fill
alist.add(new Table(18, "Bryan", "Rice");
for (int i = 0; i <= alist.size(); i++) {
System.out.println("AGE: " + alist.get(i).age);
//other stuff
}
}
import java.util.ArrayList;
public class HelloWorld {
public static void main(String []args) {
ArrayList<String> alist_name=new ArrayList<String>();
ArrayList<String> alist_value=new ArrayList<String>();
alist_name.add("My Name: ");
alist_name.add("Age: ");
alist_name.add("Favourite food: ");
alist_value.add("Bryan");
alist_value.add("18");
alist_value.add("Chicken Rice");
for (int i = 0; i < alist_name.size(); i++) {
System.out.println (alist_name.get(i)+alist_value.get(i));
}
}
}

Adding values to the objects without looping

I want to add values to the objects with out looping because if there are 1000 of objects then I don't want to loop all of them.I want to add age randomly to the students based on the Name of the student.Is there are any way to add values
Here is the code
import java.util.*;
import java.io.*;
class Student{
Student(String Name){
this.Name=Name;
}
String Name;
int age;
}
public class HelloWorld{
public static void main(String []args){
String a []={"Ram","Krishna","Sam","Tom"};
ArrayList<Student> al = new ArrayList<Student>();
for(int i=0;i<a.length;i++){
Student c;
c=new Student(a[i]);
al.add(c);
}
for(Student obj:al){
if(obj.Name.equals("Krishna")){
obj.age=24;
}
System.out.println("Name = "+ obj.Name + " Age = " + obj.age);
}
}
}
First some minor points:
You should never use the fields directly but create getter and setters instead. The fields should be private. Variable names should start with a lower case letter by convention. So this would be the adjusted Student class:
public class Student {
private String name;
private int age;
public Student(String name) {
this.name = name;
}
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;
}
}
To store the Student objects you can use a map with names as keys and Student instances as values.
It is good practice to declare the variable only with the interface type Map and not with the concrete implementation HashMap. A hash map has O(1) complexity for searching by key. So you don't need a loop to iterate through all Student instances. (The HashMap.get() implementation doesn't use a loop internally.)
public static void main(String[] args) {
String a [] = {"Ram", "Krishna", "Sam", "Tom"};
// Keys: student names
Map<String, Student> al = new HashMap<String, Student>();
// Fill the Student's map
for(int i = 0; i < a.length; i++){
String name = a[i];
al.put(name, new Student(name));
}
// Manipulate one student by name. If there is no entry for that name we get null.
// So we better check for null before using it.
Student student = al.get("Krishna");
if(student != null) {
student.setAge(24);
}
// Output the all students
for(Student obj: al.values()){
System.out.println("Name = "+ obj.getName() + " Age = " + obj.getAge());
}
}

Printing arrays - overriding toString() method

I have two different class, Student and StudentTest - the Student class has;
public class Student {
// Data Members
private String name; // The name of this student
private long idNumber; // The ID number of this student
// Constructs a new Student with passed name and ID number parameters.
public Student(String studentName, long studentIDNumber) {
name = studentName;
idNumber = studentIDNumber;
}
// Returns the name of this student.
public String getName() {
return name;
}
// Returns the ID number of this student.
public long getIDNumber() {
return idNumber;
}
// Sets the name of this student.
public void setName(String studentName) {
name = studentName;
}
// Sets the ID number of this student.
public void setIDNumber(long studentIDNumber) {
idNumber = studentIDNumber;
}
#Override
public String toString(){
return "Name: " + this.name;
}
} // end class
And the StudentTest class has 3 different methods, 1. to ask the user to enter the size of an array and then create an array of type Student, 2. to ask the user to populate the array with names and ID numbers, 3. to display the contents of the array.
import java.util.Scanner;
public class StudentTest {
// Main method.
public static void main(String [] args) {
Student[] students = createArray();
populateArray(students);
displayArray(students);
}
// Method that asks user for size of array.
public static Student[] createArray() {
System.out.println("Enter size of array: ");
Scanner userInputEntry = new Scanner(System.in);
int inputLength = userInputEntry.nextInt();
Student students[] = new Student[inputLength];
return students;
}
// Method that asks user to populate array.
public static void populateArray(Student [] array) {
for(int i = 0; i < array.length; i++) {
array[i] = new Student();
System.out.println("Enter student name: ");
Scanner userInputEntry = new Scanner(System.in);
array[i].setName(userInputEntry.next());
System.out.println("Enter student ID number: ");
array[i].setIDNumber(userInputEntry.nextLong());
}
}
// Method that displays contents of array.
public static void displayArray(Student[] array) {
for(int i = 0; i < array.length; i++){
System.out.println(array[i].toString());
}
}
}
When I try to run it, I get an error about the
array[i] = new Student();
in the for loop in the second method.
How would you expect this to work ?
#Override
public void toString(){
return "Name: " + this.name;
}
It should give you an compile error. You are trying to send a string back and the return type is void.
Change it to
#Override
public String toString(){
return "Name: " + this.name;
}
Change you main method to
// Main method.
public static void main(String [] args) {
Student[] students = createArray();
populateArray(students);
displayArray(students)
}

Class Constructor Problems While Doing A Linear Search Across Two Classes

Im creating a program that is supposed have the user enter a student name and see if it exist in the student array using a linear search method. The student array is in a different class and im having trouble creating a constructor i have tried many things and its not working can someone point me in the right direction.
My linear search class is
import java.util.*;
import java.util.Scanner;
public class LinearSearch {
public int find(Student [] a, String nm) {
for (int i = 0; i < a.length; i++) {
if (a[i].equals(nm)){
return i;
break;
}
else{
return -1;
}
}
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
LinearSearch search = new LinearSearch();
Student stu = new Student();
Student [] arr = stu.getArray();
System.out.print("Enter the name to search: ");
String name = reader.nextLine();
int n = search.find(arr, name);
if ((n >= 0) && (n < arr.length)) {
System.out.println(name + " was found at index: " + n);
} else {
System.out.println(name + " was not found");
}
}
}
My Student class is
import java.util.*;
public class Student {
public Student(){
}
public Student [] getArray(){
Student [] studentArray = new Student[3];
studentArray[0] = new Student ("Mel");
studentArray[1] = new Student ("Jared");
studentArray[2] = new Student ("Mikey");
return studentArray;
}
}
You defined a constructor with no argument:
public Student() {
}
But you're invoking a constructor which needs a String as argument:
studentArray[0] = new Student("Mel");
So, your constructor should have a String as argument:
public Student(String name)
And you should probably store this name as a field in the Student class:
private String name;
public Student(String name) {
this.name = name;
}
Note that there is no way that a Student instance could be equal to a String instance. You should provide a getter method for the name, and compare the entered String with the name of the student, instead of comparing it with the student itself.
import java.util.*;
public class Student {
private String name;
public Student(String name){
this.name = name;
}
public Student [] getArray(){
Student [] studentArray = new Student[3];
studentArray[0] = new Student ("Mel");
studentArray[1] = new Student ("Jared");
studentArray[2] = new Student ("Mikey");
return studentArray;
}
public String getName(){
return name;
}
}
and of course in the compersion you'll need to do:
f (a[i].getName().equals(nm)){
public class Student {
private String studentName;
private Student[] studentArray;
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public Student[] getStudentArray() {
return studentArray;
}
public void setStudentArray(Student[] studentArray) {
this.studentArray = studentArray;
}
public Student(){
studentArray = new Student[3];
}
public Student[] getArray() {
Student st1 = new Student();
st1.setStudentName("mel");
Student st2 = new Student();
st2.setStudentName("Jared");
Student st3 = new Student();
st3.setStudentName("Mikey");
studentArray[0]=st1;
studentArray[1]=st2;
studentArray[2]=st3;
return studentArray;
}
}
the above code is your Student class. there is no need to create a constructor though. but because you would like it i put it in the code.
the LinearSearch class is as follow:
public class LinearSearch {
private int i;
public int find(Student[] a, String nm) {
for ( i = 0; i < a.length; i++) {
if (a[i].getStudentName().equals(nm)) {
break;
} else {
i = -1;
}
}
return i;
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
LinearSearch search = new LinearSearch();
Student stu = new Student();
Student[] arr = stu.getArray();
System.out.print("Enter the name to search: ");
String name = reader.nextLine();
int n = search.find(arr, name);
if ((n >= 0) && (n < arr.length)) {
System.out.println(name + " was found at index: " + n);
} else {
System.out.println(name + " was not found");
}
}
}

Categories