I am working on my final project in a computer class and am trying to implement a basic if/else statement in a nested class but it is only opting to use the else case.
import java.util.Scanner;
public class CollegeApplication {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//create object by default constructor
College c1 = new College();
//create object by overloaded constructor
College c2 = new College("Frostburg", "Frostburg", "MD", 5142);
College c3 = new College("UMBC", "Baltimore", "MD", 14000);
//set the information of object 1
c1.setName("Full Sail");
c1.setCity("Winter Park");
c1.setState("FL");
c1.setStudent_Body(19285);
System.out.println("Enter your states two-letter abbreviation");
String user_State = scan.nextLine();
c1.printCollege();
System.out.println();
c2.printCollege();
System.out.println();
c3.printCollege();
}
}
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
import java.util.Scanner;
public class College {
// private data members
private String name;
private String city;
private String state;
private int student_Body;
private String tuition;
private String user_State;
// default constructor which set the data member to default value
public College() {
this.name = "";
this.city = "";
this.state = "";
this.student_Body = 0;
this.tuition = "";
this.user_State = "";
}
// parameterized constructor
public College(String name, String city, String state, int student_Body) {
super();
this.name = name;
this.city = city;
this.state = state;
this.student_Body = student_Body;
}
// getter and setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getStudent_Body() {
return student_Body;
}
public void setStudent_Body(int student_Body) {
this.student_Body = student_Body;
}
// print college data
public void printCollege() {
System.out.println("Name of College: " + name);
System.out.println("City of Collge: " + city);
System.out.println("State of Collge: " + state);
System.out.println("Student Body Count: " + student_Body);
this.user_State = user_State;
if (state.equals(user_State)) {
this.tuition = "Eligible";
}
else {
this.tuition = "Ineligible";
}
System.out.println("In-State Tuition: " + tuition);
}
}
If anyone could help id be greatly appreciative in knowing how to alter the if statement to not only print ineligible
This question does not contain a question but I see the problem area.
Ask yourself why your College has both a state and a user_State. Why would this class have an aspect of itself be a user_State? There isn't even a getter and setter for it (as there shouldn't be).
public void printCollege() {
this.user_State = user_State;
if (state.equals(user_State)) {
this.tuition = "Eligible";
}
else {
this.tuition = "Ineligible";
}
System.out.println("In-State Tuition: " + tuition);
}
This function takes no input and gives no output, but has side-effects of printing something and modifying fields.
The only other time user_State is referenced in College is when it's set to the empty string.
this.user_State = "";
And that's only when a College object is constructed with the default constructor. If a College object is made using the argument constructor, user_State remains null.
Anyway, this method begins by setting this empty string (or null) to itself:
this.user_State = user_State;
So it's just going to be the empty string (or null).
Next it compares the strings state with the empty string or null in user_State.
if (state.equals(user_State)) {
state is not equal to the empty string nor null in any of your test cases, so it continues to the else clause:
else {
this.tuition = "Ineligible";
}
What you probably intend is for printCollege() to take the user_State variable you asked the user for. In which case it does not take 0 arguments, it takes 1 string argument.
public void printCollege(String userState) {
if (state.equals(userState)) {
this.tuition = "Eligible";
}
else {
this.tuition = "Ineligible";
}
System.out.println("In-State Tuition: " + tuition);
}
and the invocations of printCollege(String userState) should be done as appropriate, with the input you received from the user.
Please follow Java naming conventions in the future, something like user_State should just be userState.
there is no setter method for user_State instance variable
no parameter provided for initialization of user_State instance variable
so if condition fails as it considers user_State variable as instance variable it will always be "" in case of default constructor and "null" in case of parameterized constructor
either
provide parameter to printCollege() method according to #PatricChen
or
remove the statement this.user_State = user_State from
printCollege() and provide setter method for user_State variable and
a user_State parameter to parameterized constructor of College class
Related
I want to get rid of each object's reference in my tester class, but I'm getting errors. The methods I'm using were given to me in notes but not sure if they're correct.
Any help will be appreciated :)
Here's my code:
public class Bicycle {
// Instance Variables
private String name; // Owner's name
private int age; // Owner's age
private char gender; // Owner's gender
private static int instanceCounter = 0;
// Default Constructor - doesn't take in values
public Bicycle() {
this("Not Given", 0, 'U');
instanceCounter++;
}
// Parameter constructor
public Bicycle(String name, int age, char gender) {
this.name = name;
this.age = age;
this.gender = gender;
instanceCounter++;
}
// Getter and setters
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;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public int countInstances(){
return instanceCounter;
}
}
Tester:
public class BicycleTester {
public static void main(String args[]){
// Instance one
Bicycle bicycle1 = new Bicycle(null, 0, 'U');
bicycle1.setName("John");
System.out.println("Name: " +bicycle1.getName());
bicycle1.setAge(18);
System.out.println("Age: " +bicycle1.getAge());
bicycle1.setGender('M');
System.out.println("Gender: " +bicycle1.getGender());
System.out.println("");
// Instance two
Bicycle bicycle2 = new Bicycle(null, 0, 'U');
bicycle2.setName("Mary");
System.out.println("Name: " +bicycle2.getName());
bicycle2.setAge(23);
System.out.println("Age: " +bicycle2.getAge());
bicycle2.setGender('F');
System.out.println("Gender: " +bicycle2.getGender());
System.out.println("");
// Instance three
Bicycle bicycle3 = new Bicycle(null, 0, 'U');
bicycle3.setName("Billy");
System.out.println("Name: " +bicycle3.getName());
bicycle3.setAge(15);
System.out.println("Age: " +bicycle3.getAge());
bicycle3.setGender('M');
System.out.println("Gender: " +bicycle3.getGender());
System.out.println("");
// Three ways to get rid of object's reference
void go() {
Life bicycle1 = new Life();
}
Life bicycle2 = new Life();
bicycle2 = new Life();
Life bicycle3 = new Life();
bicycle3 = null;
}
}
Ok Ma'am Lets go over the basics again.
We will start with the difference between an Object AKA instance and a reference.
Life bicycle2 = new Life();
Here, bicycle2 is a reference it will be on the Stack. The reference points to the instancecreated by the call to new Life(). The instance will be on the Heap
You can't get rid of an Object's reference. You can get rid of an instance.
There is only one wayof doing that.
Set the reference pointing to the instance to null or to some other instance
example : Life bicycle2 = new Life();
bicycle2 = null;// the instance created above will be eligible for GC
or you could also do :
Life bicycle2 = new Life();
bicycle2 = new Life();// the life instance created above will be discarded.
Note that : a reference is scope dependent once it goes out of scope, it will not be accessible. I don't think you arre talking about that here.
In the case of your no-argument constructor, you're incrementing instanceCounter twice - once when you call the other constructor with parameters, and once when that completes in the no-args constructor as well.
You're also not decrementing the count anywhere, so if you're using that as a means to keep track of how many instances of your class are in memory, your count will be off.
I have defined a class
class Prop{
public static enum property{
NAME,
CITY,
ADDRESS;
}
private String NAME;
private String CITY;
private String ADDRESS;
public String getValue(property pro){
switch(pro){
case NAME:
return NAME;
case CITY:
return CITY;}
return null;}
}
class CallPro{
private String name;
name=Prop.getValue("");
}
I am not exactly getting how to call getValue from class CallPro.
Basically what parameters should be passed to get the desired value.
I am a beginner in java
To run this program you need a public static void main(String[]) method first. That's your entry point into any Java program. Since, you want to assign the values inside callPro, add the main() method there.
Next, you want to call getProperty() which is an instance method belonging to class prop, so you'll need to create an instance of it first using the new constructor() syntax.
class callPro {
private static String name;
private static String city;
private static String address;
public static void main(String[] args) {
// create prop instance
prop property = new prop();
// call prop's method getValue()
name = property.getValue(prop.property.CITY);
city = property.getValue(prop.property.NAME);
address = property.getValue(prop.property.ADDRESS);
// New York, John, Central Park
System.out.println(name + ", " + city + ", " + address);
}
}
Notice, how I had to make callPro's members static to be able to access them inside the main() method because that's static too. Also, note how I referenced the Enums: className.enumType.enumValue.
To be able to see the values print from the main() method, you'll also need to provide values for your prop class members as
private String NAME = "John";
private String CITY = "New York";
private String ADDRESS = "Central Park";
public String getValue(property pro) {
switch (pro) {
case NAME:
return NAME;
case CITY:
return CITY;
case ADDRESS:
return ADDRESS;
}
return null;
}
Yes, you can loop through an enum's values and retrieve your properties in a loop as
prop property = new prop();
for (prop.property prop : prop.property.values()) {
System.out.println(property.getValue(prop));
}
enumType.values() returns an enumType[] of all enumValues which can be used with a for-each loop as shown above.
I've been toying for hours, changing static, private, public etcetera :) But it still won't work. If I change static at one place, I get an error at another place etc.
I have a class called person. I've used NON-static Setters because the Person() constructor is also non-static.
public class Person {
private String name;
private String lastname;
private String nickname;
Person() {
this.name = "";
this.lastname = "";
this.nickname = "";
}
public void setName(String name) {
this.name = name;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
}
Then I have a file with my main method, and different methods for interacting with the user.This method is also static because it calls that methods that take the userInput which is using the Scanner class.
public class Interaction {
public static void takeName() {
String name;
String lastname;
String nickname;
System.out.println("What is your firstname:");
name = userInput(); // calls method with Scanner class
System.out.println("What is your lastname:");
lastname = userInput(); // calls method with Scanner class
System.out.println("What is your nickname:");
nickname = userInput();
person.setName(name);
person.setLastname(lastname);
person.setNickname(nickname);
}
//editor: missing closing bracket
What I've tried:
I've tried to dat Person.person.setname(name);
Declare the String in the public class Interaction, and then pass the String using this.name and call the method from the public class Interaction
tried to change static, private etc. etc.
Delete the constructor class Person() in Person class.
What am I missing here?
EDIT: I'VE ADDED SOME MORE INFO as you requested :)
My new Person object will be declared if it passes an if statement.
IF there is a place available then a new person will be created and added to this place.
public class Theater {
void reservationSystem () {
if (availability > 0) {
for (int i = 0; i < freespaces.length; i++) {
if (freespaces[i].person == null) {
freespaces[i].person = new Person();
break;
}
}
} else {
System.out.println("No tickets for you today :) ");
}
}
//editor: missing closing bracket
So my way of thinking is:
I fill a constructor with the data from the Userinput() using the Scanner class;
and THEN I create the new Person object so it has that data!
When I create a new Person in the reservation system, then the data in the constructor will be filled with data AGAIN but now with new data :)
If you need any more information please let me know :)
The first thing to note is that your Person constructor is a little useless, you can rewrite Person as such:
public class Person {
private String name = "";
private String lastname = "";
private String nickname = "";
public void setName(String name) {
this.name = name;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
}
Now onto your Interaction class. This needs to by public rather than Public but I assume that's a typo.
You need to have an instance of Person to call your setters on as they are instance methods. You need to somewhere call new Person().
The easiest way of writing your takeName() method is by creating a Person in the method and returning the instance:
public class Interaction {
public static Person takeName() {
final Person person = new Person();
System.out.println("What is your firstname:");
person.setName(userInput());
System.out.println("What is your lastname:");
person.setLastname(userInput());
System.out.println("What is your nickname:");
person.setNickname(userInput());
return person;
}
}
Your 'takeName()` function should update a single instance of the Person class.
One approach is to create the Person externally and pass it to the function:
Public class Interaction {
public static void takeName(Person person) {
String name;
String lastname;
String nickname;
System.out.println("What is your firstname:");
name = userInput(); // calls method with Scanner class
System.out.println("What is your lastname:");
lastname = userInput(); // calls method with Scanner class
System.out.println("What is your nickname:");
nickname = userInput();
person.setName(name);
person.setLastname(lastname);
person.setNickname(nickname);
}
}
But I think it would be more intuitive to create the person instance inside the function and return it:
Public class Interaction {
public static Person takeName() {
String name;
String lastname;
String nickname;
Person person = new Person();
System.out.println("What is your firstname:");
name = userInput(); // calls method with Scanner class
System.out.println("What is your lastname:");
lastname = userInput(); // calls method with Scanner class
System.out.println("What is your nickname:");
nickname = userInput();
person.setName(name);
person.setLastname(lastname);
person.setNickname(nickname);
return person;
}
}
Because this is not valid syntax: Person.person.setname(name);
What this would mean in this context is:
get class named Person
get static field of Person class named person
find and invoke instance methid setname with argument name
But your Person class - appropriately - does not have a static field named person...
The root cause of your issues is most likely not being entirely familiar with the concept of classes, instances, and in connection, the meaning of static and instance members and methods...
Static always means the referenced part is connected with the class.
Whereas an instance variable or method (e.g. everything non-static) is connected to the instances of said classes.
Hello I'm new to Java. I'm trying to create a object and pass name through it. I don't have a clue what I'm doing wrong?.
public class Employee
{
private String name, number;
private String date;
public Employee()
{
name= "";
number = "";
date = "";
}
public Employee(String name, String number, String date)
{
setName(name);
setNumber(number);
setDate(date);
}
public void setName(String n)
{
name = n;
}
public void setNumber(String n)
{
number = n;
// you can check the format here for correctness
}
public void setDate(String d)
{
date = d;
}
public String getName()
{
return name;
}
public String getNumber()
{
return number;
}
public String getDate()
{
return date;
}
}
import java.util.Scanner;
public class TeamLeadDemo
{
public static void main(String[] args)
{
String name;
// create scanner object
Scanner keyboard = new Scanner(System.in);
// inputting data
System.out.println("Enter Name:");
name = keyboard.nextLine();
// instantiating object, HERE IS THE PROBLEM
Employee thename = new Employee(name);
// outputting data
System.out.println("Employee Name:"+thename.getName());
System.out.println("Employee Details:\n" + thename);
}
}// Function definition
What should i do??
Hey fellow newbie programmer!
Take a look at how you initialize your object:
Employee thename = new Employee(name);
Since you only give it the String name as a parameter, Java cannot initialize your Employee object because it does not have a single argument constructor!
Here are your constructors method signatures:
public Employee()
public Employee(String name, String number, String date)
One takes no arguments, and the other takes 3 arguments.
If you look at the way you initialize it, you only pass 1 argument!
You would need to create a new Constructor that has a single argument in order for your code to work. Or easier yet, you could just pass in "", "" for your number and date string values.
More experienced programmers please do not hesitate to correct my programming semantics if they are wrong. I feel like I'm using words that I do not fully understand.
You need a constructor that receives only the name that you are passing:
public Employee(String name) {
this.name = name;
this.number = "";
this.date = "";
}
Currently you only have one default constructor and one that receives all three properties.
Your Employee class has two constructors: one taking zero arguments and one taking three arguments. Yet you're attempting to construct it with one argument. That wouldn't compile.
There are two possible solutions:
Add another constructor taking one argument.
public Employee(String name) {
this.name = name;
}
Use the constructor taking three arguments and pass null through.
Employee employee = new Employee(name, null, null);
Unrelated to the concrete problem, setting values to empty strings in the default constructor and calling the setters in the second constructors is not a nice practice. In the first, just do nothing, keep them default null. In the second constructor, you should prefer setting the property directly instead of calling the setter.
You need to pass in the number and date to the constructor as well. Try:
Employee thename = new Employee(name, "", "");
Employee thename = new Employee(name);
You have no constructor that takes only one String
If you have some very very strong reasons not to use Employee thename = new Employee(name, "", "");, you may try "varargs"
As :
public class Employee {
String fname="";
String lname="";
public Emp(String... attrs) {
if ( attrs.length > 1 ) {
fname = attrs[0];
lname = attrs[1];
}else if(attrs.length == 1) {
fname = attrs[0];
}
}
public String toString() {
return fname + " " + lname;
}
public static void main(String[] args){
Employee e1 = new Employee ("Test");
Employee e2 = new Employee ("Test" ,"case");
System.out.println(e1);
System.out.println(e2);
}
}
Caution : this is just to answer your question- Think before using in real world situations. Not from design/ best approach perspective. But it is different and caters to your question though ;-)
Please can anyone tell me what the error is in the following piece of code?
Question is
Create a class person which has
A variable ‘name’ which stores the name of the person.
A constructor that takes a single argument that is used to initialize the name variable
A method getName() which displays the name.
A protected method setName() that takes one argument which is used to modify the name variable.
Create a subclass of the above class called student, which contains
A variable to store PRN of a student
A variable to store course the student belongs to
A method, which displays all the details of the student i.e, name, prn and course.
Program :
class Person
{
String name;
Person(String s)
{
name=s;
}
void getName()
{
System.out.println("Name is "+name);
}
void setName(String sa)
{
name=sa;
}
}
class subPerson extends Person
{
//String sa;
int Prn;
String course;
subPerson(String s,int P,String co)
{
name=s;
Prn=P;
course=co;
}
void displayal()
{
System.out.println("Name is ");
System.out.println("PRN is "+Prn);
System.out.println("course is "+course);
}
}
class Inher
{
public static void main(String args[])
{
int area,volumea;
subPerson h1 = new subPerson("Abhishek",20,"MBA");
h1.displayal();
}
}
Person's constructor takes a String. Since subPerson extends Person, its constructor will invoke a constructor of Person. By default it'll use the no-arg constructor, but since Person doesn't have one, it won't work.
Try changing subPerson's constructor to this:
subPerson(String s,int P,String co)
{
super(s);
Prn=P;
course=co;
}
I assume that compiles (I'm not going to check that), then the fundamental problem is that in the displayal() method, you don't actually print out the name...
System.out.println("Name is ");
should actually be something like
System.out.println("Name is " + name);
Aside from that, there are some problems with not following typcial java coding conventions. While the code may compile and do what is desired, most java guys will likely get hung up on "not following naming conventions" instead of trying to fix the problem because the code looks unusual.
I'd also recommend that you pay more attention to names. They matter a great deal and deserve careful thought.
"subPerson" as a class name leaves me quite cold. Aside from the poor camel case style, the assignment explicitly calls for a class Student. Why did you go with "subPerson"?
I would advise against the "displayal" (sic) method as well. The proper idiom is to override the toString() method in Object.
I'd write it like this:
/**
* Person
* User: Michael
* Date: Sep 27, 2009
* Time: 10:00:00 AM
*/
public class Person
{
private String name;
public static void main(String[] args)
{
Person s = new Student("Foo Bar", "35", "Intro To Java");
System.out.println(s);
}
public Person(String name)
{
if ((name == null) || (name.trim().length() == 0))
throw new IllegalArgumentException("name cannot be blank or null");
this.name = name;
}
public String getName()
{
return name;
}
public void setName(String name)
{
if ((name == null) || (name.trim().length() == 0))
throw new IllegalArgumentException("name cannot be blank or null");
this.name = name;
}
#Override
public String toString()
{
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
class Student extends Person
{
private String prn;
private String course;
Student(String name, String prn, String course)
{
super(name);
this.prn = prn;
this.course = course;
}
#Override
public String toString()
{
return "Student{" +
"name='" + getName() + '\'' +
", prn='" + prn + '\'' +
", course='" + course + '\'' +
'}';
}
}