How to print an array in Java - java

I have a Student class which has;
private String name;
private long idNumber;
and getters and setters for them.
I also have a StudentTest class which has three different methods, 1. to ask user for the size of the array and then to create an array of type Student, 2. to ask user to populate the array with names and ID numbers for as long as the array is, 3. to show the contents of the array.
The code I have so far is;
import java.util.Scanner;
public class StudentTest {
// Main method.
public static void main(String [] args) {
}
// 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) {
}
}
How do I print the contents of the array back out to the user?

in class Student u can override toString():
#Override
public void toString(){
return "name: " + this.name;
}
and create a simple for loop
for(int i = 0; i < array.length; i++){
System.out.println(array[i].toString());
}
hope this helps a little

Override the toString method in Student class and then use https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#toString(java.lang.Object[])

use this in you display function if you don't want to override the toString method
for (int i = 0; i < array.length; i++) {
System.out.println("Student id : "+array[i].getIdNumber() + " Student name : " +array[i].getName());
}

Related

how to prompt user to input array values and create a data type in java

I am working on a java code where it should prompt the user to input the grades of N amount of students and it should output the highest grade, My code is working well but I want to give the user ability to enter the content of the array and I want to create a data type called Student for example for the array.
public class Test3 {
static double grades[] = {85, 99.9, 78, 90, 98};
static double largest() {
int i;
double max = grades[0];
for (i = 1; i < grades.length; i++)
if (grades[i] > max)
max = grades[i];
return max;
}
public static void main(String[] args)
{
System.out.println("Highest grade is : " + largest());
}
}
Any help would be really appreciated.
First, you should create the Student class:
public class Student {
private double grade;
// empty constructor
public Student() {}
// all args constructor
public Student(double grade) {
this.grade = grade;
}
public double getGrade() {
return grade;
}
public void setGrade(double grade) {
this.grade = grade;
}
#Override
public String toString() {
return "Student{" +
"grade=" + grade +
'}';
}
}
To avoid repetitive code, you can use the Lombok library. It creates for you the constructors, getters, setters, toString(), and much more.
After, you can create a method to input students grades.
public static Student[] inputStudens() {
Scanner sc = new Scanner(System.in);
System.out.println("How many students?");
int N = sc.nextInt();
Student[] students = new Student[N];
for (int i=0; i<N; i++) {
System.out.println("What's the grade for student " + i + ":");
double grade = sc.nextDouble();
Student student = new Student(grade);
students[i] = student;
}
return students;
}
And... using your already made max finder, but returning the Student instead.
public static Student maxGrade(Student[] students) {
int max = 0;
for (int i = 1; i < students.length; i++) {
if (students[i].getGrade() > students[max].getGrade()) {
max = i;
}
}
return students[max];
}
Now we just need to call these methods in main().
public static void main(String[] args) {
Student[] students = inputStudens();
Student student = maxGrade(students);
System.out.println("Student with highest grade is: " + student);
}
You can create an object and use that object to invoke the array to store value. For example:
test3obj= new Test3(); // creating an object.
Use test3obj to invoke the array to store values like:
test3obj.grades[i]=(object of scanner class).nextDouble();
Object of scanner class:
Scanner obj=new Scanner(System.in);

I am trying to build an array in java that has multiple data types

I'm a beginner in programming java, I have a question which asks of me to input: the student name, id, math score, english score, and science score then calculate his total and average. So I am trying to make it into a 2d array yet I don't know how to turn string array into int. Is there a way to have one array with multiple data types(char, int, string etc)?
heres my code so far
int columns = input.nextInt();
int rows=5;
int StudentName=0;
int StudentID=1;
int math=2;
int English=3;
int Science = 4;
int i = 0;
String[][] newArray = new String[columns][rows];
for (i = 0; i<columns;i++){
System.out.println("Enter Student Name ");
newArray[i][StudentName] = input.nextLine();
System.out.println("Enter Student ID ");
newArray[i][StudentID] = input.nextLine();
System.out.println("Enter Student Math Score ");
newArray[i][math] = input.nextLine();
System.out.println("Enter Student English Score ");
newArray[i][English] = input.nextLine();
System.out.println("Enter Student Science Score ");
newArray[i][Science] = input.nextLine();
}
for(i = 0; i < columns; i++){
for(int j = 0; j < 5; j++){
System.out.println(newArray[i][j]);
}
}
}
1.Create a domain object which will be your data structure and immutable;
For an example:
public class StudentInfo implements Serializable {
private static final long serialVersionUID = 1L;
private final String StudentName;
private final int StudentID;
public StudentInfo (String StudentName, int StudentID) {
this.StudentName= StudentName;
this.StudentID= StudentID;
}
public String getStudentName() {
return StudentName;
}
//More access method.
One builder method to create the object incrementally
public class StudentInfoBuilder {
private String StudentName;
private int StudentID;
private StudentInfo() {
}
public static JobInfoBuilder newBuilder() {
return new JobInfoBuilder();
}
public JobInfoBuilder withJobName(String StudentName) {
this.StudentName = StudentName;
return this;
}
public JobInfo build() {
return new StudentInfo(StudentName, StudentID);
}
}
To be simple and clear, you could do following steps:
Create Student model with all required fileds (with required types):
public class Student {
private String id;
private String name;
private String mathScore;
private String englishScore;
private String scienceScore;
}
Define method for read all students from console:
public static Student[] readStudents(Scanner input) {
Student[] students = new Student[input.nextInt()];
for (int i = 0; i < students.length; i++) {
Student student = new Student();
students[i] = student;
System.out.println("Enter Student Name ");
student.setName(input.nextLine());
System.out.println("Enter Student ID ");
student.setId(input.nextLine());
System.out.println("Enter Student Math Score ");
student.setMathScore(input.nextLine());
System.out.println("Enter Student English Score ");
student.setEnglishScore(input.nextLine());
System.out.println("Enter Student Science Score ");
student.setScienceScore(input.nextLine());
}
return students;
}
Define method to print all students to console:
public static void print(Student[] students) {
for (int i = 0; i < students.length; i++) {
Student student = students[i];
System.out.printf("Student Name: %s", student.getName());
System.out.printf("Student ID: %s", student.getId());
System.out.printf("Student Math Score: %s", student.getMathScore());
System.out.printf("Student English Score: %s", student.getEnglishScore());
System.out.printf("Student Science Score: %s", student.getScienceScore());
System.out.println();
}
}
P.S. You could use either array or list as collection. In general: do use array if you do not plan to modify size of the collection.
You could use an array of Object. Because, in the end, anything in Java is an Object (or has an "Object sibling" - like the Integer class for primitive int values). Therefore an array of Object can be used to store the various different elements that make up a pupil.
But that is the wrong approach. You use classes and objects to model the entities your code has to deal with.
Thus create a class that represents a Student. And that class has fields such as name, id, grades. And then, in the end create a one-dimensional array of Student! That is the essence of OO programming: to create helpful abstractions, instead of coupling your data by stuffing it into arrays and remembering which index "relates" things that belong together. Instead: make that relationship explicit!
Yes you can. Below is the sample code. You can follow the same procedure and try calculating the sum and avg.
class Student{
String name;
int mark1;
int mark2;
Student(String name,int mark1,int mark2){
this.name=name;
this.mark1=mark1;
this.mark2=mark2;
}
}
public class DiffDataType {
public static void main(String[] args) {
//Creating user defined class objects
Student s1=new Student("Mark",90,75);
Student s2=new Student("John",74,65);
Student s3=new Student("Simon",65,86);
ArrayList<Student> al=new ArrayList<Student>();
al.add(s1);
al.add(s2);
al.add(s3);
Iterator itr=al.iterator();
//traverse elements of ArrayList object
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.name+" "+st.mark1+""+st.mark2);
}
}
}
Hope this answers your question.
Get accustomed to just a couple of other data structures and java statements:
class Student {
String name;
String id;
//int mathScore;
//int englishScore;
//int scienceScore;
int[] scores = new int[3];
}
As arrays cannot grow, use a List, implemented as ArrayList.
List<Student> students = new ArrayList<>();
while (input.hasNextLine()) {
System.out.println("Enter Student Name ");
String line = input.nextLine();
if (line.equals("end")) {
break;
}
// Create a new student:
Student student = new Student();
student.name = line;
System.out.println("Enter Student ID ");
student.id = input.nextLine();
System.out.println("Enter Student Math Score ");
String line = input.nextLine();
student.scores[0] = Integer.parseInt(line);
System.out.println("Enter Student English Score ");
line = input.nextLine();
student.scores[1] = Integer.parseInt(line);
System.out.println("Enter Student Science Score ");
line = input.nextLine();
student.scores[2] = Integer.parseInt(line);
// Add the student to the list:
students.add(student);
}
// One way to walk through the list:
for (Student student : students) {}
System.out.printf("Name %s, ID %s, Math: %d.%n",
student.name, student.id, student.scores[0]);
}
I think It's better to create Student class like in previous answers, and then store them into Map:
Map<Integer, Student> students = new HashMap<>();
for (int i = 0; i < students.length; i++) {
Student student = new Student("Mark", 90, 75);
map.put(i, student);
}
So you can iterate over the map, (using students.entrySet()) and get student by key (students.get(3))
The previous answers which stated that you should create your own Student class are correct, however I will show you a way to create an array that supports multiple types:
Make the array of type Object and instead of using primitive values (i.e, int, float, char, etc) use their wrapper classes (i.e, Integer, Float, Character)
Keep in mind that this will use much more memory.

Assigning and returning objects in java

I am trying to assign the current array element in the temp array with the Student object returned after calling the getStudent method.... I called the getStudent method (Step 2) and have temp[i] = to assign the current element in the temp array but cannot figure out what it should = to pair it up with the Student object returned. When using getStudent() and running the program, the output is enter the number of students, the user enters the number, and that is all that happens, it does not ask for the user to enter the name and etc, I'm not sure if step 2 is the problem or if there is another issue entirely.
import java.util.Scanner;
public class Students
{
private static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
Student[] students;
students = getStudents();
printStudents(students);
}
private static Student[] getStudents()
{
Student[] temp;
int how_many;
System.out.print("How many students? ");
how_many = input.nextInt();
purgeInputBuffer();
temp = new Student[input.nextInt()]; // Step 1 ???
for (int i = 0; i < temp.length; i++)
{
getStudent(); // Step 2
temp[i] = ; // <----------
}
return temp; // Step 3
}
private static Student getStudent()
{
String name,
address,
major;
double gpa;
System.out.print("Enter name: ");
name = input.nextLine();
System.out.print("Enter address: ");
address = input.nextLine();
System.out.print("Enter major: ");
major = input.nextLine();
System.out.print("Enter GPA: ");
gpa = input.nextDouble();
purgeInputBuffer();
return new Student (name, address, major, gpa); // Step 4
}
private static void printStudents(Student[] s)
{
System.out.println();
for (int i = 0; i < s.length; i++) // Step 5
{
System.out.println(getStudent()); // Step 6
}
}
private static void purgeInputBuffer()
{
// ----------------------------------------------------
// Purge input buffer by reading and ignoring remaining
// characters in input buffer including the newline
// ----------------------------------------------------
input.nextLine();
}
}
So first problem is first on the line:
temp = new Student[input.nextInt()];
in that line you have already asked the user to enter how many Students and store it in how_many. So i'm assuming you want to instead do:
temp = new Student[how_many];
Also what i said in my comment:
But please do also look at your private static void printStudents(Student[] s) method and acutally on the line //step 6 i don't believe that is how you want to be doing that. Instead you want System.out.println(s[i]); not System.out.println(getStudent()); For my code substitution to work though you will need to Override the toString method so it can actually display the information

Inheritance & Polymorphism Assignment

I need to write an application to display the name and ID number of each student and to calculate whether they have passed or failed. I need to have 4 different classes student, studenttest, undergraduate, postgraduate.
So far this is what I have:
Student
class Student {
//private data members
private long idNumber = 0;
private String name = "Not Given";
private int markForMaths = 0;
private int markForEnglish = 0;
private int markForEconomics = 0;
private int markForPhilosophy = 0;
private int markForIT = 0;
//Default constructor
public Student() {
name = "Not Given";
idNumber = 0;
markForMaths = 0;
markForEnglish = 0;
markForEconomics = 0;
markForPhilosophy = 0;
markForIT = 0;
}
//Constructs a new Student with passed name and age parameters.
public Student(String studentName, long studentIdNumber) {
name = studentName;
idNumber = studentIdNumber;
}
//Returns the name of student.
public String getName( ) {
return name;
}
//Returns the idNumber of student.
public long getIdNumber( ) {
return idNumber;
}
//entermarks()
//enter all subject marks given as args
public void enterMarks(int maths, int english, int economics, int philosophy, int informationTechnology)
{
markForMaths = maths;
markForEnglish = english;
markForEconomics = economics;
markForPhilosophy = philosophy;
markForIT = informationTechnology;
}
//getMathsMark()
//return mark for maths
public int getMathsMark()
{
return markForMaths;
}
//getEnglishMark()
//return mark for English
public int getEnglishMark()
{
return markForEnglish;
}
//getEconomicsMark()
//return mark for Economics
public int getEconomicsMark()
{
return markForEconomics;
}
//getPhilosophyMark()
//return mark for Philosophy
public int getPhilosophyMark()
{
return markForPhilosophy;
}
//getITMark()
//return mark for IT
public int getITMark()
{
return markForIT;
}
//calculateAverageMark()
//return the average of the three marks
public double calculateAverageMark()
{
return ((markForMaths + markForEnglish +
markForEconomics + markForPhilosophy + markForIT) / 3.0);
}
//Sets the name of student.
public void setName(String studentName ) {
name = studentName;
}
//Sets the idNumber of student.
public void setIdNumber(long studentIdNumber ) {
idNumber = studentIdNumber;
}
}//end class
Undergraduate
public class Undergarduate extends Student{
}
Postgraduate
public class Postgraduate extends Student{
}
StudentTest
import java.util.Scanner;
public class StudentTest {
static int array;
//create method createArray
public static Student[] createArray() {
Scanner int_input = new Scanner(System.in);
//user enters size of array
System.out.print("Enter Size of Array: ");
array = int_input.nextInt();
Student[] array = new Student[0];
//read user input as arraySize
return new Student[5];
}//end method
//create method populateArray
public static void populateArray(Student[] array) {
Scanner string_input = new Scanner(System.in);
Scanner long_input = new Scanner(System.in);
Scanner int_input = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
Student student = new Student(); // new student
//set name
System.out.println("Enter Student Name: ");
student.setName(string_input.nextLine());
//set ID number
System.out.println("Enter Student ID Number: ");
student.setIdNumber(long_input.nextLong());
//set Marks
System.out.println("Enter Marks");
student.enterMarks(int_input.nextInt());
//put new student into array passed to the method
array[i] = student;
}//end for loop
}//end method
//create method display Array
public static void displayArray(Student[] array){
System.out.println("Array Contents");
for (Student s : array) {
System.out.println(String.format("%s %d", s.getName(),
s.getIdNumber(), s.getEnglishMark(), s.getMathsMark(),
s.getEconomicsMark(), s.getPhilosophyMark(), s.getITMark(),
s.calculateAverageMark()));
}//end for loop
}//end method
public static void main(String [] args) {
// create array of size specified by user
Student[] students = createArray();
//populate this array with data from user
populateArray(students);
//display array contents
displayArray(students);
}//end main method
}//end class
I keep getting an error in the studenttest on the line
student.enterMarks(int_input.nextInt());
the error reads:
The method enterMarks(int, int, int, int, int, int) in the type Student is not applicable for the arguments (int)
As your class Student expects marks for each subject (english, maths, etc..), change your StudentTest class so that it passes each and every subject as input to enterMarks method.
Change your method call from:
student.enterMarks(int_input.nextInt());
TO
student.enterMarks(int_input.nextInt(), int_input.nextInt(), int_input.nextInt(), int_input.nextInt(), int_input.nextInt(), int_input.nextInt());//to make it more readable and usable, first take input from keyboard by asking user to enter the number, assign to individual marks variable and then pass it to the method.
You are trying to invoke method enterMarks(int) but there is only enterMarks(int, int, int, int, int, int) method defined in Student class.

Asking user for array size and populating array | Java

I have a Student class which has
private String name;
private long idNumber;
and getters and setters for them.
I also have a StudentTest class which has three different methods, 1. to ask user for the size of the array and then to create an array of type Student, 2. to ask user to populate the array with names and ID numbers for as long as the array is, 3. to show the contents of the array.
The code I have so far is;
import java.util.Scanner;
public class StudentTest {
// Main method.
public static void main(String [] args) {
}
// 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) {
}
// Method that displays contents of array.
public static void displayArray(Student[] array) {
}
}
I'm not sure as to how to tackle the second method of asking the user to populate the array, any help will be greatly appreciated :)
This may help you
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;
}
public static void populateArray(Student [] array) {
for(int i=0;i<array.length().i++)
{
array[i]=new Student();
System.out.println("Enter Name");
Scanner userInputEntry = new Scanner(System.in);
array[i].setName(userInputEntry .next());
System.out.println("Enter Id");
array[i].setIdNumber(userInputEntry .nextLong());
}
}
The easiest solution is probably a loop, in which you ask the user for input and then store it in your array.
Something like:
for(int i = 0; i < students.length(); i++){
[Ask for input and store it]
}
i suppose something like this:
// Method that asks user to populate array.
public static void populateArray(Student [] array) {
for(int i = 0; i < array.lenght;i++) {
array[i]=new Student(name, id); //put here student name/id
}
}

Categories