Outputting information without explicitly calling toString() in java - java

For step 6 in the println i know how to call the toString explicitly but how do i output student information from the current student in the array WITHOUT calling toString() explicitly or using any accessor methods?
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();
temp[i] = getStudent(); // Step 2
}
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(______); // Step 6
}
}
private static void purgeInputBuffer()
{
// ----------------------------------------------------
// Purge input buffer by reading and ignoring remaining
// characters in input buffer including the newline
// ----------------------------------------------------
input.nextLine();
}
}

Declare your variables name, address, major, gpa as member variables.
Override the toString() method for this class.
public String toString() {
return "Name: " + name + "\n" + "Address: " + .... //whatever you want to print.
}
Whenever you need to print details of a student, pass it to the println method:
System.out.println(obj); //where obj is a Student object.

In your Stundent class override the toString() method as, for example,:
#Override
public String toString() {
return "Stundent [ Name: " + name + ", Address: " + address + ", Major: " + major + ", GPA: " + gpa + " ]";
}
And modify your printStudents() method as follows (your Step 6):
private static void printStudents(final Student[] s) {
System.out.println();
for (final Student student : s) {
System.out.println(student);
}
}
Then your output should look like:
Stundent [ Name: Name1, Address: Addr1, Major: Major1, GPA: 3.0 ]
Stundent [ Name: Name2, Address: Addr2, Major: Major2, GPA: 3.5 ]
Now you see the toString() method will be invoked implicitly.

Related

why is my java program printing "null" in output for a string when I took it as an input through a method?

package com.company;
import java.util.Scanner;
class fields{
Scanner sc = new Scanner(System.in);
String fn;
String ln;
String em;
String phn;
String country;
String city;
public fields() {
System.out.println("\n ~~~ FORM ~~~\n");
System.out.print("First Name: ");
input(fn);
System.out.print("Last Name: ");
input(ln);
System.out.print("Email: ");
input(em);
System.out.print("Phone number: ");
input(phn);
System.out.print("Country: ");
input(country);
System.out.print("City: ");
input(city);
}
public void input(String x){
x = sc.nextLine();
}
public void output(){
System.out.println("The user's name is: " + fn + " " + ln + "\nEmail: " + em + "\nPhone Number: " + phn + ",\nand lives in: " + city + ", " + country);
}
}
public class Form {
public static void main(String[] args) {
fields obj = new fields();
System.out.println("\n ~~~ OUTPUT ~~~\n");
obj.output();
}
}
I am new to java. and I am still learning its concepts. I think it might be a problem of scopes of variable initialization. I am looking forward to being guided by anyone who can solve my problem. Thankyou
The problem is on the input() method. This method receives a String parameter. But remember that parameters in java are passed by value and in particular Strings are immutable objects so when you invoke input() and pass a String variable as a parameter, this variable is copied. So the value you are modifying inside the input() method is the copy of the parameter sent. That's why the fn, ln, em, phn, country, city variables are never initialized.
An alternative implementation of input method is the following:
public String input(){
return sc.nextLine();
}
And invoke it as the following example:
:
System.out.print("Last Name: ");
ln = input();
:
This is just a playful example to understand how parameters are passed in java because using a method just to execute the read from de standard input seems to be unnecessary.
A final comment: As a convention, Class names in java start with a capital letter.
The null values are coming from input method which dosen't initialize values, one of the correct form will be like below
public class Fields {
Scanner sc = new Scanner(System.in);
private String fn;
private String ln;
private String em;
private String phn;
private String country;
private String city;
public Fields() {
System.out.println("\n ~~~ FORM ~~~\n");
System.out.print("First Name: ");
this.fn = sc.nextLine();
System.out.print("Last Name: ");
this.ln = sc.nextLine();
System.out.print("Email: ");
this.em = sc.nextLine();
System.out.print("Phone number: ");
this.phn = sc.nextLine();
System.out.print("Country: ");
this.country = sc.nextLine();
System.out.print("City: ");
this.city = sc.nextLine();
}
public void output() {
System.out.println("The user's name is: " + fn + " " +
ln + "\nEmail: " + em + "\nPhone Number: " + phn + ",\nand lives in: " + city + ", " + country);
}}
More over please respect language [conventions][1] for class naming .
[1]: https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html#:~:text=Class%20names%20should%20be%20nouns,such%20as%20URL%20or%20HTML).

adding elements to LinkedList using for loop and user input

I am trying to use a for loop to add elements to a LinkedList, and whenever I print the list it only contains one of my inputs, and has put it at every index.
I have a feeling the problem lies with my toString method, or with my Student constructor but can't seem to figure it out.
Any and all help is appreciated. Thanks!
import java.util.*;
public class Student {
private static String name;
private static String address;
private static double GPA;
static LinkedList<Student> stu = new LinkedList<Student>();
static Scanner scanner = new Scanner(System.in);
public Student(String name, String address, double GPA) {
Student.name = name;
Student.address = address;
Student.GPA = GPA;
}
public String getName() {
return Student.name;
}
public String getAddr() {
return Student.address;
}
public double getGPA() {
return Student.GPA;
}
public static void main(String [] args) {
for (int i = 0; i <= 2; i++) {
System.out.println("Enter the student's name: ");
name = scanner.next();
System.out.println("Enter the student's address: ");
address = scanner.next();
System.out.println("Enter the student's GPA: ");
GPA = scanner.nextDouble();
stu.addLast(new Student(name, address, GPA));
}
System.out.println(stu);
}
#Override
public String toString() {
String str = "Name: " + getName() + "\nAddress: " + getAddr() + "\nGPA: " + getGPA()+ "\n\n";
return str;
}
}
Console
Enter the student's name:
Jim
Enter the student's address:
111Ave
Enter the student's GPA:
2.3
Enter the student's name:
Joe
Enter the student's address:
222Ave
Enter the student's GPA:
3.0
Enter the student's name:
Jack
Enter the student's address:
333Ave
Enter the student's GPA:
3.4
[Name: Jack
Address: 333Ave
GPA: 3.4
, Name: Jack
Address: 333Ave
GPA: 3.4
, Name: Jack
Address: 333Ave
GPA: 3.4
]
The attributes name, address, and GPA are static, which means they're accessed from all the student objects you create. Thus when you create a new student object and call it's constructor you change the values of name, address, and GPA for all the other student objects you've created before.
To solve your problem you need to remove the static keyword from the declaration of name, address, and GPA.
Now all that's left is to change the way you access your variables. Notice how you used to use Student.name whenever you wanted to use the attribute name? this only works when name is static "aka name is the same for all Students". We now want to use the name of the current student not All students, so we should use this.name instead of Student.name. Similarly change Student.GPA to this.GPA and Student.address to this.address.
Also you can't just use the attributes name, address, and GPA inside your main without an object "since they're not static anymore", so you'll need to declare name, address, and GPA inside your main, notice that these variables are not related to the variable attributes inside the Student class.
Please refer to this code for better understanding, sorry for my terrible explanation.
import java.util.*;
public class Student {
private String name;
private String address;
private double GPA;
static LinkedList<Student> stu = new LinkedList<Student>();
static Scanner scanner = new Scanner(System.in);
public Student(String name, String address, double GPA) {
this.name = name; //this.name instead of Student.name
this.address = address; //this.address instead of Student.address
this.GPA = GPA; //this.GPA instead of Student.GPA
}
public String getName() {
return this.name; //similarly
}
public String getAddr() {
return this.address; //similarly
}
public double getGPA() {
return this.GPA; //similarly
}
public static void main(String [] args) {
for (int i = 0; i <= 2; i++) {
System.out.println("Enter the student's name: ");
//notice here. "name" can be changed to anything, "sname" for example
//this variable is just to store the input, it's not related to the name
//attribute in the class
String name = scanner.next();
System.out.println("Enter the student's address: ");
//same goes for address and GPA
String address = scanner.next();
System.out.println("Enter the student's GPA: ");
double GPA = scanner.nextDouble();
//use the input taken above to create a new student by calling the constructor
stu.addLast(new Student(name, address, GPA));
}
System.out.println(stu);
}
#Override
public String toString() {
String str = "Name: " + getName() + "\nAddress: " + getAddr() + "\nGPA: " + getGPA()+ "\n\n";
return str;
}
}

Error when removing student from Java arraylist

I am struggling to get this program to do exactly what the assignment asks. It throws a null pointer exception when trying to remove an added student. Also when I list the students, it shows null on everything.
-Code is fixed-
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Student> newStudents = new ArrayList<Student>();
System.out.println("Welcome to the Student Interface!.");
System.out.println("Please select a number from the options below \n");
while (true) {
// Give the user a list of their options
System.out.println("1: Add a student to the list.");
System.out.println("2: Remove a student from the list.");
System.out.println("3: Display all students in the list.");
System.out.println("0: Exit the student interface.");
// Get the user input
int userChoice = input.nextInt();
switch (userChoice) {
case 1:
addStudents(newStudents);
break;
case 2:
removeStudent(newStudents);
break;
case 3:
displayStudent(newStudents);
break;
case 0:
System.out.println("Thank you for using the student interface. See you again soon!");
System.exit(0);
}
}
}
public static void addStudents(ArrayList<Student> newStudents) {
Scanner input = new Scanner(System.in);
Student newStudent = new Student();
System.out.println("Please enter first name: ");
String First_Name = input.next();
newStudent.setFirst_Name(First_Name);
System.out.println("Please enter last name: ");
String Last_Name = input.next();
newStudent.setLast_Name(Last_Name);
System.out.println("Please enter major: ");
String Major = input.next();
newStudent.setMajor(Major);
System.out.println("Please enter GPA: ");
String GPA = input.next();
newStudent.setGPA(GPA);
System.out.println("Please enter UIN: ");
String UIN = input.next();
newStudent.setUIN(UIN);
System.out.println("Please enter NetID: ");
String NetID = input.next();
newStudent.setNetID(NetID);
System.out.println("Please enter Age: ");
String Age = input.next();
newStudent.setAge(Age);
System.out.println("Please enter Gender: ");
String Gender = input.next();
newStudent.setGender(Gender);
if (newStudents.size() <= 10) {
newStudents.add(newStudent);
System.out.println("Student added\n");
} else {
System.out.println("\n Student interface is full!");
}
}
private static void displayStudent(ArrayList<Student> newStudents) {
for (Student e : newStudents) {
System.out.println(e);
}
}
private static void removeStudent(ArrayList<Student> newStudents) {
Scanner input = new Scanner(System.in);
System.out.println("Please, enter the UIN to remove the Student: ");
String uin = input.nextLine();
for (Student e : newStudents) {
if (e.getUIN().equals(uin)) {
newStudents.remove(e);
System.out.println("Student removed");
break;
}
else {
System.out.println("Sorry, no such student with this " + uin + " " + "number exist");
}
}
}
Student Class:
package assignments;
public class Student{
private String First_Name;
private String Last_Name;
private String Major;
private String GPA;
private String UIN;
private String NetID;
private String Age;
private String Gender;
public String getFirstName()
{
return First_Name;
}
public void setFirst_Name(String value)
{
this.First_Name = value;
}
public String getLastName()
{
return Last_Name;
}
public void setLast_Name(String value)
{
Last_Name = value;
}
public String getMajor()
{
return Major;
}
public void setMajor(String value)
{
Major = value;
}
public String getGPA()
{
return GPA;
}
public void setGPA(String value)
{
GPA = value;
}
public String getUIN()
{
return UIN;
}
public void setUIN(String value)
{
UIN = value;
}
public String getNetID()
{
return NetID;
}
public void setNetID(String value)
{
NetID = value;
}
public String getAge()
{
return Age;
}
public void setAge(String value)
{
Age = value;
}
public String getGender()
{
return Gender;
}
public void setGender(String value)
{
Gender = value;
}
public String toString()
{
return "First Name: " + First_Name +
"\n Last Name: " + Last_Name +
"\n Major: " + Major +
"\n GPA: " +GPA+
"\n UIN: " + UIN +
"\n NetID: " + NetID+
"\n Age: " + Age+
"\n Gender: " + Gender;
}
public void createStudent(String first_Name2, String last_Name2, String major2, String gPA2, String uIN2, String netID2,
String age2, String gender2) {
first_Name2 = First_Name;
last_Name2 = Last_Name;
major2 = Major;
gPA2 = GPA;
uIN2 = UIN;
age2 = Age;
gender2 = Gender;
}
}
Your program runs about perfectly on my computer. Here’s an example run:
Welcome to the Student Interface!.
Please select a number from the options below
1: Add a student to the list.
2: Remove a student from the list.
3: Display all students in the list.
0: Exit the student interface.
2
Please, enter the UIN to remove the Student:
13
1: Add a student to the list.
2: Remove a student from the list.
3: Display all students in the list.
0: Exit the student interface.
1
Please enter first name:
o
Please enter last name:
v
Please enter major:
cs
Please enter GPA:
g
Please enter UIN:
79
Please enter NetID:
o
Please enter Age:
57
Please enter Gender:
m
Student added
1: Add a student to the list.
2: Remove a student from the list.
3: Display all students in the list.
0: Exit the student interface.
3
Student [firstName=o, lastName=v, major=cs, gPA=g, uIN=79, netID=o, age=57, gender=m]
1: Add a student to the list.
2: Remove a student from the list.
3: Display all students in the list.
0: Exit the student interface.
2
Please, enter the UIN to remove the Student:
79
Student removed
1: Add a student to the list.
2: Remove a student from the list.
3: Display all students in the list.
0: Exit the student interface.
3
1: Add a student to the list.
2: Remove a student from the list.
3: Display all students in the list.
0: Exit the student interface.
0
Thank you for using the student interface. See you again soon!
Potential issues in your program include: You have two Scanner objects on System.in, you may want to share just one. You don’t use the variable student_added. In my two cases the program didn’t report back to the user whether a student was removed or not. Your two TODO comments are obsolete and should be removed.
One of two reasons you'd get a NullPointerException on the remove operation. Either the ArrayList is null, or the object you are attempting to remove is null. Check for those.

I have some issue with my output

The Cullerton Part District holds a mini-Olympics each summer. Create a class named Participant with fields for a name, age, and street address. Include a constructor that assigns parameter values to each field and a toString() method that returns a String containing all the values. Also include an equals() method that determines two Participants are equal if they have the same values in all three fields. Create an application with two arrays of at least 5 Participants each--one holds the Participants in the mini-marathon and the other holds Participants in the diving competition. Prompt the user for Participants who are in both events save the files as BC.java and ABC.java.
import javax.swing.JOptionPane;
import java.util.*;
public class ABC {
private static Participant mini[] = new Participant[2];
public static void main(String[] args) {
setParticipant();
displayDetail();
}
// BC p=new BC(name,age,add);
//displayDetails();
// System.out.println( p.toString());
public static void displayDetail() {
String name=null;
String add = null;
int age=0;
System.out.println("Name\tAdress\tAge");
BC p=new BC(name,age,add);
for (int x = 0; x < mini.length; x++) {
//Participant p1=mini[x];
System.out.println(p.toString());
}
}
public static String getName() {
Scanner sc = new Scanner(System.in);
String name;
System.out.print(" Participant name: ");
return name = sc.next();
}
// System.out.print(" Participant name: ");
// name = sc.next();
public static int getAge() {
int age;
System.out.print(" Enter age ");
Scanner sc=new Scanner(System.in);;
return age= sc.nextInt();
}
public static String getAdd() {
String add;
Scanner sc=new Scanner(System.in);;
System.out.print("Enter Address: ");
return add=sc.next();
}
public static void setParticipant(){
for (int x = 0; x < mini.length; x++) {
System.out.println("Enter loan details for customer " + (x + 1) + "...");
//Character loanType=getLoanType();
//String loanType=getLoanType();
String name=getName();
String add=getAdd();
int age=getAge();
System.out.println();
}
}
}
//another class
public class BC {
private String name;
private int age;
private String address;
public BC(String strName, int intAge, String strAddress) {
name = strName;
age = intAge;
address = strAddress;
}
#Override
public String toString() {
return "Participant [name=" + name + ", age=" + age + ", address=" + address + "]";
}
public boolean equals(Participant value){
boolean result;
if (name.equals(name) && age==value.age && address.equals(address))
result=true;
else
result=false;
return result;
}
}
outPut:
Enter loan details for customer 1...
Participant name: hddgg
Enter Address: 122
Enter age 12
Enter loan details for customer 2...
Participant name: ddjkjde
Enter Address: hdhhd23
Enter age 12
//Why I'm not getting right output
Name Adress Age
Participant [name=null, age=0, address=null]
Participant [name=null, age=0, address=null]
You are getting that output because of this method:
public static void displayDetail() {
String name=null;
String add = null;
int age=0;
System.out.println("Name\tAdress\tAge");
BC p=new BC(name,age,add);
for (int x = 0; x < mini.length; x++) {
//Participant p1=mini[x];
System.out.println(p.toString());
}
}
You are creating a BC with null for name and add and 0 for age. You are then printing it twice.

Create multiple students and check if any are repeated java

In my code I am to input multiple students and have a method check to see if any of the students are repeated (by checking ID number) but I cant seem to be able to set multiple students with my current code and save them. From my current code is there any way to be able to set multiple students or will I have to change my code completely
import java.util.Scanner;
public class Registrar
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String string1 = " ";
while(string1 != "1")
{
System.out.println("Please input full name name of student: ");
string1 = input.next(); // user input of name
if (string1 != "0"){
break;
}
System.out.println("Please input Student ID (if done enter 0): ");
String string2 = input.next(); // user input of ID
System.out.println("Please input Students Credits: ");
int inputCredits = input.nextInt(); // User input of Credits
System.out.println("Please input Student's Total Grade Points Earned: ");
double getPoints = input.nextDouble();
double GPA = getPoints/inputCredits; //User input of Grade Points Earned and Divide by Credits to get GPA
Student first = new Student(string1, string2, inputCredits, GPA);
System.out.println( "Name: " + first.getName() + "\nUser ID: " + first.getId() + "\nCredits: " + first.getCredits() + "\nGrade Point Average: " + first.getGradePoints() );
}
}
}
This is my Student Class
public class Student {
private String name;
private String idnum;
private int credits;
private double gradePoints;
public Student(String n, String id, int c, double gp){
name = n;
idnum = id;
credits = c;
gradePoints = gp;
}
public String getName(){
return name;
}
public String getId(){
return idnum;
}
public int getCredits(){
return credits;
}
public double getGradePoints(){
return gradePoints;
}
}
Try this code. better implementation with collection.
Scanner input = new Scanner(System.in);
String string1 = " ";
System.out.println("Number of students to be entered");
int s = input.nextInt();
List<Student> studentList = new ArrayList<Student>();
for(int i = 0; i<s; i++) {
System.out.println("Please input full name of student: ");
string1 = input.next(); // user input of name
System.out.println("Please input Student ID (if done enter 0): ");
String string2 = input.next(); // user input of ID
System.out.println("Please input Students Credits: ");
int inputCredits = input.nextInt(); // User input of Credits
System.out.println("Please input Student's Total Grade Points Earned: ");
double getPoints = input.nextDouble();
double GPA = getPoints/inputCredits; //User input of Grade Points Earned and Divide by Credits to get GPA
Student student = new Student(string1, string2, inputCredits, GPA);
System.out.println( "Name: " + first.getName() + "\nUser ID: " + first.getId() + "\nCredits: " + first.getCredits() + "\nGrade Point Average: " + first.getGradePoints() );
studentList.add(student);
}
You can take a user input(How many student you want to save and run a loope to take details of input. The rough code will be like this:
System.out.println("Enter how many student you want to enter");
int s = input.nextInt();
for(int i = 0; i<s; i++) {
//Code for take details of user
}
//Then you can print the details of student in similar way.

Categories

Resources