I have been stuck on this one for days, but I have broken it down here. What I need to do is to create an array of accounts with about 9 variables each (AccountID, WithdrawlDates, etc.) that the user can input in a command prompt. From the createAccount() method I can send an instance of user and a accountNum, but the user is not recognized on the receiving setAccount method.
Here's the code:
class User{
private int accountID;
User( int id )
{
accountID = id;
}
static void setAccountID(User user[], int accountNum)
{
user.accountID = accountNum; //accountID is not recognized here
}
static void getAccountID(User user){System.out.println(user.accountID);}
}
class TestUser
{
public static void main(String[] args)
{
createAccount();
}
static void createAccount(){
User[] user = new User[2];
user[0] = new User(25);
User.setAccountID(user, 2001);
}
}
I am open to changing the flow of this, but I don't know where to start.
Thanks!
To access the elements of an array instead of doing something with the array itself you use square brackets like so:
user[userIndex]
from there you can either change the element like this
user[userIndex] = new User(id);
or access/modify something about the element itself like this
user[userIndex].accountID = whatever;
Additionally, your use of static in the setAccountID is confusing things. A static method cannot know anything about accountID because accountID is a part of a uniquely created object where the static method belongs to the class, and not any particular object. If it must be static for some reason, you will need to change the method to look something like this
static void setAccountID(User user[], int userIndex, int accountNum)
{
user[userIndex].accountID = accountNum;
}
but the following would be much better, since you know the user inside the array anyway:
void setAccountID(int accountNum)
{
this.accountID = accountNum;
}
called like this:
user[userIndex].setAccountID(accountNum);
There's no reason to pass an array of User objects. Try this instead:
class User{
private int accountID;
User( int id )
{
accountID = id;
}
static void setAccountID(User user, int accountNum)
{
user.accountID = accountNum; //accountID is not recognized here
}
static void getAccountID(User user){System.out.println(user.accountID);}
}
class TestUser
{
public static void main(String[] args)
{
createAccount();
}
static void createAccount(){
User user = new User(25);
User.setAccountID(user, 2001);
}
}
EDIT: If you need to maintain an array of users as #Luiggi Mendoza suggests in his comment, just pass a single array element to setAccountID():
static void createAccount(){
User[] user = new User[2];
user[0] = new User(25);
User.setAccountID(user[0], 2001); // set id for first User
}
Related
I have created a class like this, which contains a bunch of arraylist as you can see. I've been setting the array with the methods add.. and then retrieving it with get.., when i tried to System.out.println numberofcitizen for example it is returning 0. Note that i have instantiated the class in another class to set the values.
public int numberOfCitizen;
private final ArrayList<Integer> citizenid = new ArrayList<>();
private final ArrayList<String> citizenName = new ArrayList<>();
private final ArrayList<Integer> citizenWaste = new ArrayList<>();
private final ArrayList<Float> longitude = new ArrayList<>();
private final ArrayList<Float> latitude = new ArrayList<>();
private final ArrayList<String> address = new ArrayList<>();
public void working() {
System.out.println("executing fine");
}
public void setnoOfcit(int number) {
this.numberOfCitizen = number;
}
public int getnumber() {
return this.numberOfCitizen;
}
public void addCitizenId(int citizen) {
citizenid.add(citizen);
}
public int getCitizenid(int i) {
int citId = citizenid.get(i);
return citId;
}
public void addCitizenName(String citizenname) {
citizenName.add(citizenname);
}
public String getCitizenName(int i) {
return citizenName.get(i);
}
public void addCitizenWaste(int waste) {
citizenWaste.add(waste);
}
public int getCitizenWaste(int i) {
return citizenWaste.get(i);
}
public void addLatitude(float lat) {
latitude.add(lat);
}
public float getLat(int i) {
return latitude.get(i);
}
public void addlng(float lng) {
longitude.add(lng);
}
public float getlng(int i) {
return longitude.get(i);
}
com.graphhopper.jsprit.core.problem.VehicleRoutingProblem.Builder vrpBuilder = com.graphhopper.jsprit.core.problem.VehicleRoutingProblem.Builder.newInstance();
public void runVPRSolver() {
System.out.println(numberOfCitizen);
System.out.println(getCitizenName(0));
//create a loop to fill parameters
Probable source of problem :
numberOfCitizen is a member attribute that you seem to never change. If you want it to represent the number of elements in your lists, either use citizenName.size() or increment the value of numberOfCitizen in one of the add methods.
Design flaw :
Your design takes for granted that your other class always use that one properly. Anytime you or someone uses that class, he must make sure that he add every single element manually. This adds code that could be grouped inside your class, which would be cleaner and easier to maintain.
So instead of several add method like this :
addCitizenid();
addCitizenName();
addCitizenWaste();
addLongitude();
addLatitude();
addAddress();
Design an other Citizen class which will contain those elements, and use a single list of instances of that class. That way you can use only one method :
private List<Citizen> citizenList = new ArrayList<>();
public void addCitizen(Citizen c) {
/*Add element in your list*/
citizenList.add(c);
}
This programming methodology is called "Encapsulation" which you can read about here
You need to increment numberOfCitizen in your add methods. For example:
public void addCitizenId(int citizen){
citizenid.add(citizen);
numberOfCitizen++;
}
I would also suggest encapsulating your variables into Objects, so create a citizen class:
public class Citizen {
private Integer id;
private Integer name;
private Integer waste;
}
And change your variable to an ArrayList of objects:
ArrayList<Citizen> citizens;
Okay. Here's my first page with the accessors and mutators
public class TimeCard {
private int employeeNum;
private String[] clockInTimes = new String[14];
private String[] clockOutTimes = new String[14];
private float[] decimalClockIn = new float[14];
private float[] decimalClockOut = new float[14];
private float[] timeElapsed = new float[14];
public String[] getClockInTimes()
{
return clockInTimes;
}
public void setClockInTimes(String[] value)
{
clockInTimes = value;
}
}
My second class acessessing those set/get arrays.
How would I ask for user input for each array subscript 0-13?
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
TimeCard josue = new TimeCard();
System.out.println("Enter Monday Clock In Times:");
//not sure if this is right?
josue.setClockInTimes[0](reader.next());
}
}
By the way I need to do it like this because teacher wants it this way. I'm just not really sure how to get user input and put it into an array using an object class.
I'd probably start by changing your setter to take an index and a value, so something like this:
public void setClockInTime(int day, String clockInTime) {
this.clockInTimes[day] = clockInTime; // note you don't need to write "this," but it's clearer that this is a member field
}
And then in your main method:
for (int i=0;i<14;i++) {
String input = <get input>
josue.setCliockInTime(i, input);
}
Now you can set one value at a time, and that should let you populate all of your fields.
I want the pass-in variable "aaa" to be returned the value from the argument of the function. I really need my argument in the function to be defined as String, and want whatever change of the argument in the function to be return to the pass-in variable.
How do I make this happen in Java? If anyone could help I will appreciate!
public class DeppDemo {
private String aaa;
public void abc(String aaa) {
aaa = "123";
}
public static void main(String[] args) {
DeppDemo demo = new DeppDemo();
demo.abc(demo.aaa);
System.out.println(demo.aaa);
}
}
You cannot do it like this: String class in Java is immutable, and all parameters, including object references, are passed by value.
You can achieve the desired result in one of three ways:
Return a new String from a method and re-assign it in the caller,
Pass mutable StringBuilder instead of a String, and modify its content in place, or
Pass an instance of DeppDemo, and add a setter for aaa.
Here are some examples:
public class DeppDemo {
private String aaa;
private StringBuilder bbb = new StringBuilder();
public String abc() {
return "123";
}
public void def(StringBuilder x) {
x.setLength(0);
x.append("123");
}
public static void main(String[] args) {
DeppDemo demo = new DeppDemo();
demo.aaa = demo.abc(); // Assign
demo.def(demo.bbb); // Mutate
System.out.println(demo.aaa);
}
}
It's really unclear what you're asking, but it sounds like you're trying to change the content of a variable passed into a function. If so, you can't in Java. Java doesn't do pass-by-reference.
Instead, you pass in an object or array, and modify the state of that object or array.
public class DeppDemo {
public void abc(String[] aaa) {
aaa[0] = "123";
}
public static void main(String[] args) {
String[] target = new String[1];
DeppDemo demo = new DeppDemo();
demo.abc(target);
System.out.println(target[0]);
}
}
But if you're asking how to update the aaa field using the aaa argument, then you need to qualify your reference to the field using this., since you've used the same name for both. Or change the name of the argument.
public class DeppDemo {
private String aaa;
public void abc(String aaa) {
this.aaa = aaa;
}
public static void main(String[] args) {
DeppDemo demo = new DeppDemo();
demo.abc("New value");
System.out.println(demo.aaa);
}
}
In this project the user must enter 1 or 2 hospitals but not 3 or more. So the program starts and I display a menu. If the user presses 1 he must enter a hospital(name and department). After this the program displays the menu again and the user can choose to insert another hospital.
But after that, if I choose to insert another one (which is not permitted) the program accepts it. It seems that every time InsertHospitals() is called from the main class, the value of numberofhospitals (which is a counter counting how many hospitals I entered) equals 0.
public class Hospital {
private String Name, Departments;
private char flag;
private int numberofhospitals;
private Hospital[] ListOfHospitals;
//private Patient[] ListOfPatiens;
//private Doctor[] ListOfDoctors;
//private Examination[] ListOfExaminations;
//private Folder[] ListOfFolders;
public Hospital(String Name, String Departments)
{
this.Name=Name;
this.Departments=Departments;
}
public Hospital()
{
ListOfHospitals = new Hospital[2];
//ListOfPatiens = new Patient[100];
//ListOfDoctors = new Doctor[100];
//ListOfExaminations = new Examination[100];
//ListOfFolders = new Folder[100];
}
public String getName()
{
return Name;
}
public void setname(String Name)
{
this.Name=Name;
}
public String getDepartments()
{
return Departments;
}
public void setdepartments(String Departments)
{
this.Departments=Departments;
}
public void InsertHospitals()
{
if(numberofhospitals==2)
{
System.out.println("You can give only two hospitals!");
}
else
{
String temp = sir.readString("Hospital's Name:");
Name=temp;
String temp1 = sir.readString("Hospital's departments:");
Departments=temp1;
Hospital hospital = new Hospital(Name, Departments);
ListOfHospitals[numberofhospitals]=hospital;
numberofhospitals=numberofhospitals+1;
}
}
}
Your misunderstanding something, the list of hospitals (as mentioned) should not be inside your hospital class. You have to consider your hospital class as a blueprint you are using in your application.
Which means that you need to have a list of hospitals, as a list inside your other application class (which runs the application) and the InsertHospitals method should not be in your hospital class either obviously.
As you add a new hospital in your program, you create a new hospital object and add it to the list of hospitals (fx an arraylist) your keeping as a field value.
Also posssibly make a new constructor with parameters in the hospital class so you can insert the values outside of the class.
Something like this fx.
public class MainApp {
private ArrayList<Hospital> hospitalList;
public static void main(String[] args) {
// Initialize or load it from a file or whatever here.
hospitalList = new ArrayList<Hospital>();
// your code here...
}
public void insertHospital(<insert parameters here to create a hospital>) {
Hospital newHospital = new Hospital(<insert params with new constructor>);
hospitalList.add(newHospital);
}
}
Whatever your problem, your program completely wrong. In insertHospital() your changing Name and Departments fields, and creating new Hospital with those values. When you print Hospital information all hospitals will have the same value.
I wanted to create array of an objects. There will be many user objects and I want to keep these user objects in an array. I have a class called Data. I tried and searched a lot but couldn't find the solution. When user enters a new name the names of all objects changes with the given name, and at last when i print all the names it prints the last entered name for several times. Here is my code, it will be much helpful you to understand:
testClass.java
public class testClass {
public static void main(String[] args) {
mainScreen();
}
public static void mainScreen(){
Scanner scan = new Scanner(System.in);
System.out.println("1) Add a new user:");
int choice = scan.nextInt();
switch(choice){
case 1:
System.out.println("Enter name:");
String name = scan.next();
Data.users[Data.count] = new Data(name);
mainScreen();
break;
case 2:
for(int i =0; i<=Data.count; i++){
System.out.println(Data.users[i].name);
}
break;
}
}
}
Data.java
public class Data {
public static Data[] users = new Data[600];
public static String name;
public static int count = 0;
public Data(String name) {
users[count].name = name;
count++;
}
}
I want that every object will have unique name, id, phone number, etc.. Does anybody have a suggestion for me?
Because name is static field of your Data class like count and users.
Remove static modifier from name field.
One solution is to remove the static modifier from name field in Data:
public static Data[] users = new Data[600];
public static int count = 0;
public String name;
public Data(String name) {
this.name = name;
Data.count++;
}
Also modify your for loop, because you'll get a NullPointerException, remove equals from the condition:
for(int i =0; i<Data.count; i++){
First you need to correct your Object structure
you have defined a class Data which contains a static array of Data Class itself
I prefer to have data class as:
class Data {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
create a array of Data class in your testClass
create new Data Object for each input and assign the name to the newly created Object using setName
maintain the count variable in testClass. Increment it each time when you get a new input and use count variable to assign newly created Object to the Data array