I've coded a program named TestStudent class that creates four element array of Student object. User is prompt to enter the student id, name, department and classification level. Here's the code :
import java.util.Scanner;
public class TestStudent {
public static void main(String[] args) {
//Create a Scanner object
Scanner input = new Scanner(System.in);
//Create a four element array of Student object
Student[] studentList = new Student[4];
for (int i = 0; i < studentList.length; i++) {
int j = i + 1;
//Prompt user to enter student matrix number
System.out.println("Enter student " + j + " id : ");
studentList[i].setIdStudent(input.nextInt());
//Prompt user to enter student name
System.out.println("Enter student " + j + " name : ");
studentList[i].setName(input.nextLine());
//Prompt user to enter student department
System.out.println("Enter student " + j + " department : ");
studentList[i].setDepartment(input.nextLine());
//Prompt user to enter student classification level
System.out.println("Enter student " + j + " classification : ");
studentList[i].setClassification(input.next());
System.out.println("\n");
}
//Print result
System.out.println("Id Student Name Department Classification");
System.out.println("******************************************************************************");
for (int i = 0; i < studentList.length; i++) {
System.out.println(studentList[i].getIdStudent() + " " + studentList[i].getName() + " " + studentList[i].getDepartment() + " " + studentList[i].getClassification());
}
}
public class Student {
//Student matrix number
private int idStudent;
//Student name
private String name;
//Student department
private String department;
//Student classification level
private String classification;
//Construct a default Student object
public Student() {
idStudent = 0;
name = " ";
department = " ";
classification = " ";
}
//Construct a Student object
public Student(int idStudent, String name, String department, String classification) {
this.idStudent = idStudent;
this.name = name;
this.department = department;
this.classification = classification;
}
//Return student matrix number
public int getIdStudent() {
return idStudent;
}
//Return student name
public String getName() {
return name;
}
//Return student department
public String getDepartment() {
return department;
}
//Return student classification level
public String getClassification() {
return classification;
}
//Set student matrix number
public void setIdStudent(int newIdStudent) {
newIdStudent = idStudent;
}
//Set student name
public void setName(String newName) {
newName = name;
}
//Set student department
public void setDepartment(String newDepartment) {
newDepartment = department;
}
//Set student classification level
public void setClassification(String newClassification) {
newClassification = classification;
}
}
}
The expected output is:
Id Student Name Department Classification
********************************************************************************
1140 Will Gerard Music Junior
1152 Julia Ross Architecture Freshman
1130 Fred Huan Medic Senior
1137 Clara Whist Aviation Sophomore
But the error occured:
Enter student 1 id :
1140
Exception in thread "main" java.lang.NullPointerException
at Asg2.TestStudent.main(TestStudent.java:28)
I suppose that the problem seem to be the studentList[i].setIdStudent(input.nextInt()); line. Any suggestion on how to solve this problem?
1) Go to line 28.
2) There you have some reference which has a null value
at the moment when you try to call a method on it or to access
one of its fields (class variables).
3) Make sure you initialize that reference before trying
to use it, so that it's not null when you need it to have
a non-null value.
Related
Make a program that gets user input and stores it in arrays. You will store information about, at least 3, people. There will be three pieces of information you will need to store about each person: name, age and gender (age must be an integer). After the user inputs information about every person you will print all of the information like shown below
List of people
Melissa, 28, F
Adam, 11, M
Landon, 6, M
Sadie, 1, F
How do I order the people by their age when I have String and int at the same time? Here is my code:
public static void main(String[] args) {
Scanner inputString = new Scanner(System.in);
Scanner input = new Scanner(System.in);
System.out.println("Enter your age:");
int age1 = input.nextInt();
System.out.println("Enter your name:");
String name1 = inputString.nextLine();
System.out.println("Enter your gender:");
String gender1 = inputString.nextLine();
System.out.println("Enter your age:");
int age2 = input.nextInt();
System.out.println("Enter your name:");
String name2 = inputString.nextLine();
System.out.println("Enter your gender:");
String gender2 = inputString.nextLine();
System.out.println("Enter your age:");
int age3 = input.nextInt();
System.out.println("Enter your name:");
String name3 = inputString.nextLine();
System.out.println("Enter your gender:");
String gender3 = inputString.nextLine();
int[] age = new int[3];
age[0] = age1;
age[1] = age2;
age[2] = age3;
String[] name = new String[3];
name[0] = name1;
name[1] = name2;
name[2] = name3;
String[] gender = new String[3];
gender[0] = gender1;
gender[1] = gender2;
gender[2] = gender3;
System.out.print("List of People");
System.out.print("\n" + (age[0]) + ", " + (name[0]) + ", " + (gender[0]));
System.out.print("\n" + (age[1]) +", " + (name[1]) +", "+ (gender[1]));
System.out.print("\n" + (age[2]) + ", " + (name[2]) +" , "+ (gender[2]));
}
If you want to learn Java, please try to first learn object oriented concepts.
In your specific case, you should be using a Person class, a single List<Person> and a Comparator of Person instances to sort your list, instead of trying to sort three different arrays. Have a look at the following example.
First, your runner class that contains the main() method:
package test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import test.Person.Gender;
public class Runner {
public static void main(final String[] args) {
Scanner input = new Scanner(System.in);
Boolean createNewPerson = true;
// a single list of person instances
List<Person> people = new ArrayList<Person>();
while (createNewPerson) {
Person person = new Person();
System.out.println("Enter age:");
person.setAge(Integer.valueOf(input.nextLine()));
System.out.println("Enter name:");
person.setName(input.nextLine());
System.out.println("Enter gender:");
person.setGender(Gender.valueOf(input.nextLine().toUpperCase()));
// add the person to the list
people.add(person);
System.out.println("Add another person ? (true/false)");
createNewPerson = Boolean.valueOf(input.nextLine());
}
input.close();
// here is the sorting trick
Collections.sort(people, new AgeComparator());
// print it out
System.out.println(Arrays.toString(people.toArray()));
}
}
Your Person class:
package test;
public class Person {
private String name;
private Gender gender;
private Integer age;
public Integer getAge() {
return this.age;
}
public void setAge(final Integer age) {
this.age = age;
}
public String getName() {
return this.name;
}
public void setName(final String name) {
this.name = name;
}
public Gender getGender() {
return this.gender;
}
public void setGender(final Gender gender) {
this.gender = gender;
}
#Override
public String toString() {
return this.name + " is a " + this.gender + " and is " + this.age + " year(s) old." + System.lineSeparator();
}
enum Gender {
MALE,
FEMALE;
}
}
And your Comparator (here I wrote one that compares by age, but it is only an example):
package test;
import java.util.Comparator;
public class AgeComparator implements Comparator<Person> {
#Override
public int compare(final Person person1, final Person person2) {
return person1.getAge().compareTo(person2.getAge());
}
}
In other words, programming is not about writing lines, it's about conception, design, using concepts and only then writing lines of code.
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.
Q. 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 Participant.java and TwoEventParticipants.java.*/
Here is my code so far. How do I display the value of Participants who are in both events ?
import javax.swing.JOptionPane;
import java.util.*;
public class TwoEventParticipants {
private static Participant mini[] = new Participant[2];
private static Participant diving[] = new Participant[2];
public static void main(String[] args) {
String name="";;
String add="";
int age=0;
Participant p=new Participant(name, age, add);
Participant p1=new Participant(name, age, add);
setParticipant();
setParticipant1();
displayDetail();
displayDetail1();
//Arrays.sort(p1);
if (p.equals(p1)){
System.out.println(p);
}else{
System.out.println(p1);
}
}
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();
mini[x] = new Participant(name, age, add); //<--- Create the object with the data you collected and put it into your array.
}
}
public static void setParticipant1(){
for (int y = 0; y < diving.length; y++) {
System.out.println("Enter loan details for customer " + (y + 1) + "...");
String name=getName();
String add=getAdd();
int age=getAge();
System.out.println();
diving[y] = new Participant(name, age, add);
}
}
// Participant p=new Participant(name,age,add);
//displayDetails();
// System.out.println( p.toString());
public static void displayDetail() {
// for (int y = 0; y < diving.length; y++) {
System.out.println("Name \tAge \tAddress");
//Participant p=new Participant(name,age,add);
for (int x = 0; x < mini.length; x++) {
System.out.println(mini[x].toString());
// System.out.println(diving[y].toString());
}
}
public static void displayDetail1() {
System.out.println("Name \tAge \tAddress");
for (int y = 0; y < diving.length; y++) {
System.out.println(diving[y].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();
}
}
Participant with fields for a name, age, and street address
//
public class Participant {
private String name;
private int age;
private String address;
public Participant(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
#Override
public String toString() {
return name + " " + age + " " + address ;
}
// include an equals() method that determines two Participants are equal
public boolean equals(Participant[] name,Participant[] age,Participant[] add) {
if (this.name.equals(name) && this.address.equals(address)&& age == age){
return true;
}
else{
return false;
}
}
}
This will work for you:
for(Participant p : mini){
if(diving.contain(p)){
System.out.pringtln(p.toString()) ;
}
}
i have a Student class and my arraylist is of type student .now,how do i take input from user and insert it in my arraylist?
I think this is what you are looking for
----------------------- Main Class File --------------------
public class TestingClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of students detail : ");
int numberOfInputs = input.nextInt();
ArrayList<Student> StudentList = new ArrayList<Student>();
for( int i=0; i < numberOfInputs ; i++){
System.out.println("Please enter Name : ");
String name = input.next();
System.out.println("Please enter Address : ");
String address = input.next();
Student std = new Student(name, address);
StudentList.add(std);
}
for(Student std : StudentList){
System.out.println(std.toString());
}
}
}
-------------------- Student Java File ----------------------
public class Student {
public String name = "";
public String address = "";
public Student(String name2, String address2) {
this.name = name2;
this.address = address2;
}
#Override
public String toString() {
return "Student [name=" + this.name + ", address=" + this.address + "]";
}
}
Please excuse what is probably a very basic question, but I am writing a program to store employee info and it works fine until it tries to set the info inside my employee class. It gives a stackoverflow error and I cannot figure out why. Thanks for any help.
Main class:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner Input = new Scanner(System.in);
System.out.println("Enter the number of employees to enter.");
int employeeCount = Input.nextInt();
Input.nextLine();
Employee employee[] = new Employee[employeeCount];
String namesTemp;
String streetTemp;
String cityTemp;
String stateTemp;
String zipCodeTemp;
String address;
String dateOfHireTemp;
for(int x = 0; x < employeeCount; x++)
{
System.out.println("Please enter the name of Employee " + (x + 1));
namesTemp = Input.nextLine();
System.out.println("Please enter the street for Employee " + (x + 1));
streetTemp = Input.nextLine();
System.out.println("Please enter the city of Employee " + (x + 1));
cityTemp = Input.nextLine();
System.out.println("Please enter the state of Employee " + (x + 1));
stateTemp = Input.nextLine();
System.out.println("Please enter the zip code of Employee " + (x + 1));
zipCodeTemp = Input.nextLine();
address = streetTemp + ", " + cityTemp + ", " + stateTemp + ", " + zipCodeTemp;
System.out.println("Please enter the date of hire for Employee " + (x + 1));
dateOfHireTemp = Input.nextLine();
System.out.println("The employee ID for employee " + (x + 1) + " is " + (x + 1));
employee[x] = new Employee(x, namesTemp, address, dateOfHireTemp);
}
}
}
Employee class:
public class Employee
{
private int employeeID;
private Name name;
private Address address;
private DateOfHire hireDate;
public Employee()
{
}
public Employee(int employeeID, String name, String address, String hireDate)
{
String temp;
Name employeeName = new Name(name);
this.employeeID = employeeID;
}
}
Name class:
public class Name
{
public Name name;
public Name(String name)
{
Name employeeName = new Name(name);
this.name = employeeName;
}
}
The most common cause of StackoverflowExceptions is to unknowingly have recursion, and is that happening here? ...
public Name(String name)
{
Name employeeName = new Name(name); // **** YIKES!! ***
this.name = employeeName;
}
Bingo: recursion!
This constructor will create a new Name object whose constructor will create a new Name object whose constructor will... and thus you will keep creating new Name objects ad infinitum or until stack memory runs out. Solution: don't do this. Assign name to a String:
class Name {
String name; // ***** String field!
public Name(String name)
{
this.name = name; // this.name is a String field
}
Typically a class is used to group data together with functionality. It appears that the Name class is simply a wrapper for a String without adding any functionality. At this point in your Java career, it is probably better to declare String name; in the Employee class and remove the Name class all together. (Note that this would remove the error from your code that Hovercraft Full of Eels described.)