Why Object "Adult" cannot be printed out? - java

package com.java.zha;
public class Person{
private String name;
public Person(){
}
public Person(String name1){
this.name=name1;
}
public void printkk(){
for (int i=0; i<3;i++){
System.out.println(Adult[i].name);/*the prompt message said that" the Adult can not be resolved as an variant.*/
}
}
public static void main(String[] args){
Person[] Adult= new Person[3];
Adult[0]=new Person("zhangbin");
Adult[1]=new Person("zhangchangqing");
Adult[2]=new Person("nana");
System.out.println(Adult[2].name);
Adult[1].printkk();
}
}
PS: I created an object Adult and a printkk() method which used to print all the member's name of the Adult array. But it give me an error. So I ask help from your guys. I am just starting to code please answer it in detail. thanks in advance!

You're trying to access private fields, change private String name; to public String name; or add a getName() method so that you can print out the name with System.out.println(Adult[2].name); or System.out.println(Adult[2].getName();.
Your printkk() method is trying to print out a non-existant Adult array. You'll need to pass it as an argument to the method, so change public void printkk() to public void printkk(Person[] Adult) and then change Adult[1].printkk(); to Adult[1].printkk(Adult);
This is probably the easiest way to get your code to work, but it would be better to scrap what you have and rewrite most of it.

Related

How to make setStudentName method?

I'm supposed to kinda create a student account in java (I'm very new to Java so please don't flame me). Everything is working fine except for when I need to set a Name/degree program (so string I believe). By the way, I'm using BlueJ.
I have tried using the void instead of string but I get the same problem. I also did this before the method starts:
private String studentName;
public String setStudentName (String setStudentName) {
return studentName = setStudentName;
}
I just want to set the Student Name so I can work with it, but if I try running it, I get the following error: "Error: cannot find symbol - variable Robin" Robin is the Name I tried to enter.
Your class and methods should look something like this:
public final class Student {
private String studentName;
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
}
Then, you can use your class like so:
public static void main(String[] args) {
Student student = new Student();
student.setStudentName("Robin");
System.out.println(student.getStudentName());
}
Take a look into the official Java Tutorials on how to write classes.
Just want to sum up all responses above, you have to write this.studentName = studentName instead of studentName = studentName, because in your context you have both method class field and method parameter studentName, so if you write inside your method studentName you work with method parameter. this is link to 'class instance itself' and this.studentNamecalls exactly class field.
One more solution is to rename studentName method param to e.g. newStudentName so it wouldn't be in conflict with class field and afterwords studentName = newStudentName will work as you expects.

I am trying to figure out how to create a user within a method

I have a method:
public User(String name) {
//create a user with the appropriate name}
I want to create something where if someone types in
User (bob);
an instance of the user class with the name "bob" will appear.
I tried to use this code:
public User(String name) {
User name = new User();
but I am getting errors that state the the constructor User(); is undefined and also that there is a duplicate local variable name. I know this is a basic question, but I can't seem to figure it out and any help would be appreciated.
The first bit of code you have is a constructor, not a method. It exists to tell Java how to create your class when using the new keyword.
You likely want to do this:
public class User{
private String name;
public User(String n){
name = n; // When creating my User, give him this name
}
public String getName(){
return name;
}
}
That defines your User class. Now you can create one anywhere
public class MyApplication{
public static void main(String[] args){
User user = new User("Tom");
System.out.println(user.getName());
}
}
Not sure if I followed what you were asking for... but this might be it. As some of the comments mention, I would highly recommend picking up a good beginner Java programming book to better grasp the basics of constructors.
public User(String inName) {
name = inName;
}
//...
new User("Bob");
Use:
User name = new User("yourname");
Then add a constructor with a string parameter.

Writing an object value in java [duplicate]

This question already has answers here:
How to create a println/print method for a custom class
(6 answers)
Closed 8 years ago.
Hello I have question to my small program how I can print the value of p1? When I am using p1.toString() method this still shows me the address of an object I was searching in google some other ways and I still don't know how to do this. Here is the code:
public class Boss {
String name;
public Boss(String input) { // This is the constructor
name = "Our Boss is also known as : " + input;
}
public static void main(String args[]) {
Boss p1 = new Boss("Super-Man");
System.out.println(p1.toString());
}
You seem to have forgotten to override toString()
// Add this to Boss
public String toString() {
return name;
}
Or (as you currently have your code),
// System.out.println(p1.toString());
System.out.println(p1.name);
You should probably add a getName() method to Boss as well,
public String getName() {
return name;
}
You need to override the toString method to get the functionality that you are expecting. Also I recommend setting the String name to private while you're at it. If you need to provide access to the String then create a get method to return it. This prevents someone from modifying it when they shouldn't have access. Not providing an access modifier in Java defaults to protected.
public class Boss {
private String name; // Change access modifier to private
public Boss(String input) {
name = "Our Boss is also known as : " + input;
}
#Override
public String toString(){ // Override the toString method
return name;
}
public static void main(String args[]) {
Boss p1 = new Boss("Super-Man");
System.out.println(p1.toString());
}
}
The default toString() method in Object prints class name # hash code. You can override toString() method in your class to print proper output.
#Override
public String toString(){
return name;
}
Sources:
http://javarevisited.blogspot.com/2012/09/override-tostring-method-java-tips-example-code.html
http://www.geeksforgeeks.org/overriding-tostring-method-in-java/

Problems adding objects from a different class into an Arraylist - java

I'm working on a project where i have 3 different classes creating objects CommissionEmployee, SalariedEmployee and HourlyEmployee. I need to add these to an arraylist in the main class, but not sure where i'm going wrong.
public class Company {
public String companyName;
public SalariedEmployee owner;
public ArrayList<SalariedEmployee> salariedEmployee;
public ArrayList<HourlyEmployee> hourlyEmployee;
public ArrayList<CommissionEmployee> commissionEmployee;
public Company (String companyName, SalariedEmployee owner){
this.companyName = companyName;
this.owner = owner;
}
public void addSalariedEmployee (SalariedEmployee SalariedEmployee){
salariedEmployee.add(SalariedEmployee); **
}
public void addHourlyEmployee (HourlyEmployee HourlyEmployee){
//HourlyEmployee = new HourlyEmployee (name, position, ratePerHour);
hourlyEmployee.add(HourlyEmployee);
}
public void addCommissionEmployee (CommissionEmployee CommissionEmployee){
//CommissionEmployee = new CommissionEmployee (,, ratePerItem);
commissionEmployee.add(CommissionEmployee);
}
** = this is the line where my editor is telling me i'm going wrong.
Cheers, any help will be appreciated
You've attempted to name the parameter the same as your class name. A class name is not acceptable as a parameter name. Name the parameter something different. Even something of different case would be good, e.g.:
public void addSalariedEmployee (SalariedEmployee salariedEmployee){
Because you have two variables with the same name in that line (i.e. salariedEmployee). Here is the fix for you:
public void addSalariedEmployee (SalariedEmployee aSalariedEmployee){
salariedEmployee.add(aSalariedEmployee);
}
you are using class name as parameter name. it should be different case or any other name instead of class name.
but it is better to have camel case name.
just example:
public void addSalariedEmployee (SalariedEmployee salariedEmployee)
Your method parameter is SINGLE OBJECT. You are trying to put a LIST not an object. You have to change your method parameter
When youll changed, here's an example to deal with the iterator objects.
public static void main(String[] args) {
Curso curso=new Curso();
Evento evento=new Evento();
Publicacion publicacion=new Publicacion();
List objectList = new ArrayList();
objectList.add(curso);
objectList.add(evento);
objectList.add(publicacion);
for(Object o:objectList){
if(o instanceof Curso){
//do some thing
}
if(o instanceof Evento){
//do some thing
}
if(o instanceof Publicacion){
//do some thing
}
}
}
Remember that JAVA works with objects and everyting its a object. Regards

Prevent object stored in ArrayList from being over written

Basically I have to write a simple contact manager, and store objects in array list.
What frustrates me is that I have newContact method, which when called creates new instance of Contact, and stores it in ArrayList. The problem is that every time I call that method, all other objets in the list gets overwritten.
import java.util.ArrayList;
public class ContactManager {
public static ArrayList<Contact> contactList = new ArrayList<Contact>();
public static Contact[]c = {};
public static void main(String[]args){
newContact();
newContact();
System.out.println(contactList.get(1).getName());
System.out.println(contactList.get(0).getName());
}
public static void newContact(){
Contact c = new Contact();
contactList.add(c);
}
}
In Contact class constructore there is code that initializes the object's properties using Scanner class.
If in first call I Enter "John" and in second function call I enter "Peter", the above code will print out:
Peter
Peter.
Why doesn't it prints out John Peter?
Only thing I can think of is that maybe Java stores only reference to object in arraylist, and that unlike variables objects don't get destroyed after function executes..
Any ways around this?
I hope this explains what I am trying to achieve.
PS. I know people hate people that as homework questions. But I am doing this as an extra, in order to learn new stuff. Original assignment barely asks to instantiate 5 objects and store them in ArrayList. And I have that done, now I am just trying to see if I could come up with more dynamic solution.
Contact class code:
import java.util.Scanner;
public class Contact{
private static String name, number;
//constructor will ask to enter contact details
public Contact(){
Scanner in = new Scanner(System.in);
System.out.println("Enter name:");
name = in.next();
System.out.println("Enter number:");
number = in.next();
}
//getters and setters
public static String getName(){
return name;
}
public static String getNumber(){
return number;
}
public static void setName(String newName){
name = newName;
}
public static void setNumber(String newNumber){
number = newNumber;
}
}
It's because the members in the Contact class are static. That means that all Contact instances share the same name and number. You should make them instance members so that each time you do new Contact you get a new copy of these variables.

Categories

Resources