Simple ArrayList question - java

I have this class:
public class User {
public User(String nickname, String ipAddress) {
nickname = nickname.toLowerCase();
System.out.println(nickname + " " + ipAddress);
}
}
And another class that creates an array containing User objects.
class UserMananger {
static User user;
static User user2;
static User user3;
static ArrayList allTheUsers;
public void UserManager() {
allTheUsers = new ArrayList();
user = new User("Slavisha", "123.34.34.34");
user2 = new User("Zare", "123.34.34.34");
user3 = new User("Smor", "123.34.34.34");
allTheUsers.add(user);
allTheUsers.add(user2);
allTheUsers.add(user3);
}
}
What I want to do is to call a main method that will give me all elements from the list that are type User in format: "nickname ipAddress"
public static void main(String args[]) {
System.out.println(allTheUsers.get(0));
}
For example, this main method should give me something like:
Slavisha 123.34.34.34
but it doesn't. What seems to be the problem?

First problem: you haven't overridden toString() in User. For example:
#Override
public String toString() {
return nickname + " " + ipAddress;
}
Second problem: each time an instance of UserManager is created, you're changing the values of your static variables... but you're not doing anything unless an instance of UserManager is created. One option is to change the constructor of UserManager into a static initializer:
static {
// Initialize the static variables here
}
Third problem: you haven't shown us where your main method is, so we don't know whether it has access to allTheUsers.
Fourth problem: "it doesn't" isn't a good description of your problem. Always say what appears to be happening: are you getting an exception? Is it just printing the wrong thing?

Related

Method and Variable Scope Issue in Java

I need help I cannot figure out how to fix the scope of my variables. I want this to be an example for my notes but have been on it for almost 2 hours.
public class methodPractice{
String streetName;
int streetNum;
public static void streetName()
{
String streetName = "Pope Ave.";
}
public static void streetNum()
{
int streetNum = 11825;
}
public static void main(String[] args)
{
streetName();
streetNum();
System.out.println("This is your home adress: " + streetNum +
streetName);
}
}
Thank you for your help.
You are shadowing the fields. Use this to make sure you get the fields, or a compile error.
public static void streetName()
{
this.streetName = "Pope Ave.";
}
public static void streetNum()
{
this.streetNum = 11825;
}
Here is your main method, with line numbers added:
1. public static void main(String[] args) {
2. streetName();
3. streetNum();
4. System.out.println("This is your home adress: " + streetNum + streetName);
5. }
A few points...
When line 2 runs, "streetName()" calls the static method below. The static keyword says you are free to call the method by itself – that is, you don't need an object; you don't need to call new methodPractice() first.
public static void streetName() {
String streetName = "Pope Ave.";
}
When line 3 runs, it's the same thing: "streetNum()" calls a different static method – again, totally fine to call this by itself.
public static void streetNum() {
int streetNum = 11825;
}
Line 4 is different, there are a few things going on. Your expectation is that "streetNum" finds the int that you declared on the class, but it doesn't work. Why? Because you defined that member with "int streetNum" – without "static". So what? Without being declared static, it means "streetNum" belongs to an object instance. What does that look like? Here's an example showing object creation, followed by setting the object member "streetNum" to 1.
methodPractice object = new methodPractice();
object.streetNum = 1;
You could work around this by declaring both of the non-static members to be static (static String streetName, and static int streetNum). Or you could leave them as is, and interact with them through an object instance (after doing new ..).

How to access string from one method in another

I have a method getMyName and want to access the String myName outside the method.
public String getMyName() {
setTestStart("Returning name");
String myName = getActiveName().getMyName();
setTestInfo("My name is: " + myName);
setTestEnd();
return myName;
}
I want to get a String myName result and use that result in other methods without constantly calling the whole getMyName method. How can i do that? Sorry for this silly question, I am new in Java.
you could put your var out of the all method scopes
public class Test{
private String myName; // it's out of all scopes and will can catch in all methods
public void getMyName(){
setTestStart("Returning name");
myName = getActiveName().getMyName(); // setting value
}
public void testMyNameInOtherMethod(){
setTestInfo("My name is: " + myName); // reading value. so important treating non-declaring and null values
setTestEnd();
}
// others methods...
}
you can use contructors to set values when init instances of new class as well

How do I print the array of another class?

I have created an array with flight destinations in the public class flights and now I want to print out the array using a method in the public class customers. But for some reason the array always prints out as null and I sandly can't my mistake.
main class:
public class Main {
public static void main(String[] args) {
flight flight = new flight();
customer customer = new customer();
flight.createExampleData();
customer.output();
}
}
public class flights:
public class flight{
public String[] destination = new String[2000];
public void createExampleData(){
this.destination[1] = "Paris";
this.destination[2] = "Geneve";
this.destination[3] = "Florida";
}
}
public class customers:
public class customer{
flight flight = new flight();
public int i;
public void output() {
this.i=1;
while (i<4){
System.out.println("Flightnumber: " + this.i);
System.out.println("Destination: " + flight.destination[this.i]);
System.out.println("");
this.i++;
}
}
}
(I can't put the print in the flights class for reasons not visible in this simplyfied version of the program)
Outcome from the method outpout after the method createExampleData:
Flightnumber: 1
Destination: null
Flightnumber: 2
Destination: null
Flightnumber: 3
Destination: null
Thanks for the help
Maybe you haven't executed the function createExampleData() in your customers class?
You are using two different flight objects, one created in main and one created in your customer class and then you call flight.createExampleData on the instance created in main but the output method uses the one in the customer object so the array in that one was never given any values, hence null in the output.
My suggestion for now is to make the flight variable in customer public
public class customer{
public flight flight = new flight();
...
}
and then change main to
public class Main {
public static void main(String[] args) {
customer customer = new customer();
customer.flight.createExampleData();
customer.output();
}
}
A better solution could be to add a getFlight() method to customer instead and keep the variable private.
flight.createExampleData();
When you call this, createExampleData method in Flight class is executed.
customer.output();
When you call this output method in Customer class is executed.
There is no relationship between Flight and Customer class in your code. So, customer object's output method wouldn't know what happened in the createExampleData of Flight class.
You can rather do this
String [] flightDestinations = flight.createExampleData();
customer.output(flightDestinations);
You will have to change your output method in customer class to use this string array and print its details. Also, the return type for createExampleData should be String [] for this to work.

Why can't I seem to find the error in my program when compiling. Help needed

The pet store program should start with the user being able to choose to adopt a pet or give a pet the to the shop. If the user wants to adopt a pet, they should be able to see either all available pets, unless they say they know what type of pet they want, then show only available pets of that type.
The 4 methods that will need to be created for this program should:
add new pets
get a pet adopted
show pets by type
show pets available for adoption
Object Class: Pets.java
import java.util.*;
public class Pets {
public static void main(String[] args){
private double age; // age of the animal (e.g. for 6 months the age would be .5)
private String petName; // name of the animal
private String aType; // the type of the pet (e.g. "bird", "dog", "cat", "fish", etc)
private int collarID; // id number for the pets
private boolean isAdopted = false; // truth of if the pet has been adopted or not
private String newOwner;
private Date adoptionDate;
public double getAge() {
return age;
}
public void setAge(double age) {
this.age = age;
}
public String getPetName() {
return petName;
}
public void setPetName(String petName) {
this.petName = petName;
}
public String getaType() {
return aType;
}
public void setaType(String aType) {
this.aType = aType;
}
public int getCollarId() {
return collarID;
}
public void setCollarId(int collarId) {
this.collarID = collarId;
}
public boolean isAdoptated() {
return isAdopted;
}
public void setAdoptated(boolean isAdoptated) {
this.isAdopted = isAdoptated;
}
public Date getAdoptionDate() {
return adoptionDate;
}
public void setAdoptionDate(Date adoptionDate) {
this.adoptionDate = adoptionDate;
}
#Override
public String toString() {
return "Pets [age=" + age + ", petName=" + petName + ", aType=" + aType + ", collarId=" + collarID
+ ", isAdoptated=" + isAdopted + ", adoptionDate=" + adoptionDate + "]";
}
}
}
You should define the data fields and methods inside the class, but not inside the main()-method. The main()-method is the entry point of your java application and could be used to create an instance of your Pets class.
e.g.:
public static void main(String[] args) {
Pets pet = new Pets();
}
This code is not compiling for 2 main reasons:
You are specifying access modifiers on variables inside a method (in this case main), which is forbidden;
You are writing methods (e.g. getAge) inside another method (main) and trying to return a variable (e.g. age) that is out of that scope, in fact the variable age is not known inside the getAge method, because it's declared in the main method.
You should move the variable declaration to class level, and then have all methods separated using those variables. I'll give you a sketch, not the complete solution:
import java.util.*;
public class Pets {
/* Insert all variable declarations here */
private double age;
/* Constructor if you need it */
public Pets(/* parameters you think you need */) {
// Set attributes when you declare a new Pets()
}
/* Insert all methods you need here */
public double getAge() {
return this.age;
}
The positioning of the main method - for what I've understoon from your description - should be placed outside this class, in another class where the whole application will start to run. The Pet class should serve only for anything concerning pets (the four methods you will need to implement and all getters/setters for retrieving private class variables).
You’ve happened to put about everything — private fields and public methods — inside you main method. That doesn’t make sense. Everything that is in your main, move it outside, right under the line public class Pets {. That should fix your compiler error.

How do I get the dynamic class name of an object?

So I have a List of Actors and I want to get each Actors dynamic class name.
For example here is my Actor list: People, Birds, Cows.
I want to get as result the same: "People, Birds, Cows" but without a name attribute in the Actors class. Is it possible?
Example code (here instead of list I used array) :
public Area map[][];
map[0][0] = new AntHillArea();
String name = map[0][0].getClass().getName(); //this results "Area" instead of AntHillArea
Edit: There was other problems with the code, getClass().getName() works fine. Thanks anyway.
String className = obj.getClass().getSimpleName();
Update:
public class Test {
public static void main(String[] args) {
Area map[][] = new Area[1][1];
map[0][0] = new AntHillArea();
String name = map[0][0].getClass().getSimpleName(); // returns "AntHillArea"
System.out.println(name);
}
}
class Area {
}
class AntHillArea extends Area {
}
Use getSimpleName method. It gives you only class and will remove any package if having.
You can do this:
class Dog
{
//code
public String getName()
{
return Dog.class.getName();
}
//better
#Override
public String toString()
{
return Dog.class.getName();
}
}
And similarly for each class. Or have a global one as mentioned in other answers as:
public static String getClassName(Class<?> clas){
return clas.getName();
}
To use Dog dog = new Dog(); getClassName(dog.class);

Categories