How to change the name of a object using user input? - java

how would i change the name of a object using user input.
for ex. i am asking the user to input their id as a string.
i want to then use that to create a constructor.
ex.:
RefUnsortedList<Patients> NewList = new RefUnsortedList<Patients>();
Patients entry1=null;
System.out.println("Please enter patient's ID: ");
String TargetID = scan.next();
I want to set
Patients entry1 = null;
to make it
Patients "the user input here" = null;

There are no dynamic variables in java, they have to be declared in the source code.
You could try using a Map and assigning each instance of a variable a key.
Map patientMap = new HashMap();
patientMap.put("entry1", new Patients());
patientMap.put("the user input here", new Patients());
Then when you want to retrieve the patient you can use:
Patients patient = patientMap.get("the user input here");

What you actually want to do is:
Map<String, Patient> patients = new HashMap<>();
patients.put("entry1", /* [insert Patient object here] */);
Things to note:
The class to represent a patient should be named Patient, not Paitents. A class should be named for its instances, not their collection.
It is meaningless to set the value in a map to null, unless you are using a special type of map that allows a null key (and makes it meaningfully different from not having an entry for that key).

I am assuming you are doing something like this:
Your Patient Class:
public class Patient {
private String patientID;
public Patient(String patientID) {
this.patientID = patientID;
}
public String getPatientID() {
return patientID;
}
public void setPatientID(String patientID) {
this.patientID = patientID;
}
}
...and your class that you are using for running the console:
public class Main {
public Main() {
}
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("System is ready to accept input, please enter ID : ");
String ID = console.nextLine();
Patient patient = new Patient(ID);
//do some fancy stuff with your patient
}
}
This would be a very basic example.
As you are learning to code, be sure to really think about how to name your classes. Calling your class "Patients" would make me expect you are holding a collection of "Patients" inside each instance of this java class, rather than a single "Patient" per instance.
Regarding the latest answers including Maps, the updated "Main" class could look like this:
public class Main {
static Map<String, Patient> patients = new HashMap<String, Patient>();
public Main() {
}
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("System is ready to accept input, please enter ID : ");
String id = console.nextLine();
patients.put(id, new Patient(id));
}
}

Related

Infinite loop when trying to populate a list of no more than two Hospitals

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.

How would I take user input and add it into an arraylist?

I have currently written a class called PostTUI and I need to know if I could take the input people write from my scanner and add it into my arraylist.
public class PostTUI {
private Scanner scan = new Scanner(System.in);
private PostManager manager;
private String userChoice;
private String author;
private String message;
public PostTUI(PostManager manager) {
this.manager = new PostManager();
}
public void run() {
System.out.println("1 - Create a new Message Post");
System.out.println("2 - Create a new Photo Post");
System.out.println("3 - Create a new Event Post");
this.userChoice = this.scan.nextLine();
if (this.userChoice.equals("1")) {
System.out.println("Who is the author?");
this.author = this.scan.nextLine();
System.out.println("What is the message?");
this.message = scan.nextLine();
this.manager.addPost(Post newPost);
}
}
}
The PostManager class is the class who's job it is to declare and initialize the arraylist. It has a method that accepts and stores a post (addPost) and a toString method.
You haven't made it explicitly clear where you use an ArrayList, but presumably inside the PostManager and you add to it with the add() method. In any case, that's not how you create a new object, which is why the last line is giving you an error message. You want this instead:
this.manager.addPost(new Post());
You haven't shown us the Post class, but maybe you want to pass the author and message Strings as arguments to the Post constructor?

Java - How to create a class instance from user input

I want this program to ask the user for input, and create a class instance with a name equal to the input of the user. Then, the createMember class will create a text file, where all the data of the user will be stored. How do I go about doing it?
Here's the main method:
public static void main(String[] args) {
String input = keyboard.nextLine();
input = new createMember(); // Error. can't do that for some reason?
}
}
Here's the createMember class
public class createMember {
public void setMembership() {
Scanner keyboard = new Scanner(System.in);
out.println("Username: ");
String input = keyboard.nextLine();
try {
//Creates a text file with the same name as the username where data is stored.
Formatter x = new Formatter(input);
} catch (Exception e) {
out.println("Could not create username");
}
}
//Methods for the user
Guys... I know I can simply create an instance like this:
createMember member = new createMember();
What I actually want to do is HAVE THE USER do that on his own, so the program is flexible and usable for many people. So, based on the input, there will be a separate folder that stores the data for each user.
Looks like you need a non-default Constructor: (Constructors CANNOT return any value, not even void, as the instance is what is actually returned.
String input = keyboard.nextLine();
Member m = new Member(input);
public class Member {
private String name;
public Member(String name) {
this.name = name;
}
public void setMembership() {
try {
//Creates a text file with the same name as the username where data is stored.
Formatter x = new Formatter(name);
} catch (Exception e) {
out.println("Could not create username");
}
}
}
You need a constructor
public class CreateMember {
private String input;
public CreateMember(String input){
this.input = input;
}
public String getInput(){
return input;
}
}
To access the input use CreateMember.getInput()
public static void main(String[] args){
String input = scanner.nextLine();
CreateMember member = new CreateMember(input);
System.out.println(member.getInput());
}

How do I allow vars to be accessed by any class/method?

import javax.swing.*;
class Person {
public String name;
public static void main(String[] args) {
new Person().enter();
}
void enter(){
Person a = new Person();
String first = JOptionPane.showInputDialog(null,"Enter your first name");
a.name = first;
new la().a();
}
}
class la{
void a(){
Person a = new Person();
System.out.println(a.name);
}
}
As you can see what I'm trying to do here is to set global var 'name' from the JOption input and to then be able to access 'name' with the new inputted var, from other classes later on. Since the workings of the classes later on depend on that var 'name'. Now I know I can simply pass these on through constructors to the relevant classes and avert this problem, but I want to know if this way is possible at all ?
You're example won't achieve what you are trying to achieve.
You create a new instance Person in Main, assign it a new, then create a new instance of la, which creates it's own instance Person
There is no coalition between these various instances.
public static void main(String args[]) {
String first = JOptionPane.showInputDialog(null,"Enter your first name");
// You should be checking the return result, but any way...
Person person = new Person();
person.name = first;
La la = new La(person);
}
public class La {
public La(Person person) {
System.out.println(person.name);
}
}
Right now by not specifying that your class is Public you are setting it as Default. Default is package private so classes in other packages will not have access to this class's public vars.
Declare the class as Public and set any global vars to Public and they will be accessible.

Java - Passing Arrays in Methods, Variables Not Recognized

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
}

Categories

Resources