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.)
Related
so im just starting to study java and planning to learn it in-depth and then i wanna ask this thing because im stuck and to learn more.
im trying to use the get and return method.
i wanted to do this in an input way but i cant use the
"int age = person1.GetAge()
System.out.println("Age:" + age) because it will become 2 variables (age)
i hope you understand my question and i know it sounds stupid but i wanna learn xD.
CODE:
//unfinished
//cant use the getAge, no idea how; the value in yrsleft is always 65 despite of the formula that i give
package practice;
import java.util.Scanner;
class person{
String name;
int age;
void speak() {
System.out.print("Hello my name is:" + name);
}
int retire() {
int yrsleft = 65 - age;
return yrsleft;
}
int GetAge() {
return age;
}
}
public class curiosity1{
public static void main(String[]args) {
person person1 = new person();
Scanner input = new Scanner(System.in);
System.out.print("What is your name:");
String name = input.next();
System.out.print("What is your age:");
int age = input.nextInt();
//person1.name = "John";
//person1.age = 30;
System.out.println("Name: " + name);
int age = person1.GetAge();
System.out.println("Age:" + age);
int years = person1.retire();
System.out.println("Years till retirement:" + years);
}
}```
I hope I understood your question correctly, you want to do this?
person1.age = input.nextInt();
person1.name = input.next();
System.out.println("Age:" + person1.getAge());
Or you can override toString() method in your class (since all java classes are inherited from Object, which has this method) to represent your object with a string. Also, you should create a constructor for your Person class.
class Person { // always start class name with a capital letter
int age;
String name;
public Person(int age, String name) {
this.age = age;
this.name = name;
}
// Your methods and etc.
#Override
public String toString() {
return "Name:" + this.name + ". Age:" + this.age;
}
}
And then:
int age = input.nextInt();
String name = input.next();
Person person1 = new Person(age, name);
System.out.println(person1.toString());
I am in an Object-Oriented Programming course in college and I have to use Java to start a program that will eventually incorporate a full on GUI by the end of the course. For the beginning of this project, I have to basically use message boxes to set up how a customer would order a sub to be delivered to their home.
Here's what I have so far:
This is the main class
import javax.swing.*;
//Here is the main class
public class Subs {
public static void main(String[] args) {
// Begin Main Method
char letter;
String input;
String input1, input2, input3, input4, input6, input8;
int input5, input7;
int subL; //length of sub in inches
int cup; //size of drink in ounces
JFrame frame = new JFrame("Message");
JOptionPane.showMessageDialog(frame, "Welcome to Famous Subs! ");
input1 = JOptionPane.showInputDialog(frame, "Please Enter Your Name: ");
input2 = JOptionPane.showInputDialog(frame, "Please Enter Your Address: ");
do {
input3 = JOptionPane.showInputDialog(frame, "What kind of sub would "
+ "you like? " +
"\n Turkey Club" +
"\n Philly" +
"\n Meatball" +
"\n Chicken Parm");
input4 = JOptionPane.showInputDialog(frame, "What type of bread? " +
"\n White" +
"\n Wheat" +
"\n Rosemary" +
"\n Italian Herb");
subL = getValidLength();
input6 = JOptionPane.showInputDialog(frame, "What would you like to "
+ "to drink? " +
"\n Water" +
"\n Soda" +
"\n Juice");
cup = getValidCup ();
input8 = JOptionPane.showInputDialog(frame, "Do you wish to continue?\n "+
"'y' or 'Y' for YES\n"+
"'n' or 'N' for NO\n");
Order firstOrder = new Order(input1, input2, input3, input4, input6, subL, cup);
JOptionPane.showMessageDialog(frame, firstOrder.toString());
letter = input1.charAt(0);
}
while (letter == 'Y'|| letter == 'y');
System.exit(0);
}
private static int getValidLength()
{
int s;
String input5;
do{
input5 = JOptionPane.showInputDialog(null, "What size of sub do you wish "
+ "to order? "+
"\n 6 inch"+
"\n 12 inch");
s = Integer.parseInt(input5);
} while (!(s==6 || s==12));
return s;
}
private static int getValidCup()
{
int c;
String input8;
do{
input8 = JOptionPane.showInputDialog(null, "What size drink? " +
"\n Small 12oz." +
"\n Medium 24oz." +
"\n Large 36oz.");
c = Integer.parseInt(input8);
}
while (!(c==12 || c==24 || c==36));
return c;
}
}
This is my subclass
//This is the class for the order
public class Order {
//creating my variables
private String Customer;
private String Address;
private String name;
private String bread;
private String drink;
private int length; //in inches
private int size; //in ounces
private double SubPrice;
private double DrinkPrice;
private double total;
//blank constructor
public Order(){}
//Create a constructor to hold variables
public Order (String Customer, String Address, String name, String bread, String drink, int subL, int cup){
this.Customer = Customer;
this.Address = Address;
this.name = name;
this.bread = bread;
this.drink = drink;
subL = length;
cup = size;
}
//create the getters and setters for the variables
public String getCustomer(){
return Customer;
}
public void setCustomer(String Customer){
this.Customer = Customer;
}
public String getAddress(){
return Address;
}
public void setAddress(String Address){
this.Address = Address;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getBread(){
return bread;
}
public void setBread(String bread){
this.bread = bread;
}
public String getDrink(){
return drink;
}
public void setDrink(String drink){
this.drink = drink;
}
public int getLength(){
return length;
}
public void setLength (int length){
this.length = length;
}
public int getSize(){
return size;
}
public void setSize (int size){
this.size = size;
}
public void setSubPrice (int subL, double SubPrice){
if (subL == 6)
SubPrice = 7.95;
else if (subL == 12)
SubPrice = 12.75;
}
public void setDrinkPrice(int cup, double DrinkPrice){
if (cup == 12)
DrinkPrice = 2.00;
else if (cup == 24)
DrinkPrice = 4.00;
else if (cup == 36);
DrinkPrice = 6.00;
}
public void setTotal(){
total = SubPrice + DrinkPrice;
}
#Override
public String toString(){
String grandOrder = "Greetings " + Customer +
"\nHere is your order: " +
"\n" + name +
"\n" + bread +
"\n" + drink +
"\nThe length of your sub is: " + length +
"\nThe size of your drink is: " + size +
"\nThe Price for your sub is: " + SubPrice +
"\nThe Price for your drink is: " + DrinkPrice +
"\nHere is your total: $" + calculateTotal(DrinkPrice, SubPrice) +
"\nThis will be delivered to: " + Address;
return grandOrder;
}
}
Everything runs just fine except the fact that the last box to show up returns all the string fields as null and the int and double variables as 0 or 0.0.
How do I return the values for what the user inputs on each dialog box? In addition, how do I get he customer's name and address to appear on this final screen? Thanks.
You never initialize fields of your Order. You call constructor without parameters public Order(){}. So you see the default values of the fields.
What you should do:
Be sure that you keep in a variable the value for the name of the client. (input = JOptionPane.showInputDialog(frame, "Please Enter Your Name: ");)
Be sure that you keep in variable user's input after "input = JOptionPane.showInputDialog(frame, "What kind of sub would "
+ "you like? " ...".
After get all inputs from the user, create Order object passing user's values
Order firstOrder = new Order(name, bread,drink,int subL, cup);
Change the constructor with parameters like that:
public Order (String name, String bread, String drink, int subL, int cup). You should not pass subPrice and drinkPrice because you Order class already know these values (see setdrinkPrice()). You determine the price of a cup based on the int cup. BTW, can you change the name of the method? Something like setDrinkPrice().
You never call setDrinkPrice() and setsubPrice()(should be setSubPrice(). You can do this when you calculate the total.
Start with these changes and if you have more problems ask .
Okay, a few things are going on here.
Order firstOrder;
firstOrder = new Order();
Can just be written as
Order firstOrder = new Order();
there's no need to do that on two lines. But, more importantly, you've not giving it any parameters, so Java is linking that to the empty constructor (the one that doesn't assign anything.) All of that nice constructor code you have isn't getting called.
To do that, you need to actually do something with those input fields you keep assigning (at the moment you're just ignoring them and writing over them); specifically, you should store them in local variables, and then pass them to the constructor like:
firstOrder = new Order(arg1, arg2, ...)
Also, Order isn't a subclass; it isn't extending anything. (Except Object, but we don't generally call something a subclass just for that.
input = JOptionPane.showInputDialog(frame, "Please Enter Your Name: ");
input = JOptionPane.showInputDialog(frame, "Please Enter Your Address: ");
On the first line above, you get the customer's name. then you call the second line, throwing away the customer's name without saving it anywhere.
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.
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.