Need help creating an add/remove method for an indexable hashmap - java

I'm new at coding and can't seem to find a solution for my problem here. My teacher told me I should be able to make an easier method than my current one. I'm making a medicine list where the current user should be able to add a medicine to the current patient. I have a Medicine class where I have my Indexable map stored. Now, I also have a class called "Patient", where I am creating my medicine menu which will contain a "add, remove and edit" method. My teacher says I should be able to find an easier way. Does anyone know how to create these methods easily?
( Indexable hashmap :)
import java.util.*;
public class Medicine {
public String medication_name;
public String type;
public String dosage;
public Medicine(String name, String type, String dosage) {
this.medication_name = name;
this.type = type;
this.dosage = dosage;
}
public static IndexableMap<String, Medicine> getMedicineList(){
IndexableMap<String, Medicine> medicineList = new IndexableMap<>();
medicineList.put("1.", new Medicine( "Diclofenac", "(Painkiller)", "2 x a day"));
medicineList.put("2.", new Medicine("Amoxicilline", "(Antibiotic)", "3 x a week "));
medicineList.put("3.", new Medicine("Omeprazol", "(Anti-inflammatory)", "4 x a day"));
medicineList.put("4.", new Medicine("Doxycycline", "(Antibiotic)", "2 x a week"));
medicineList.put("5.", new Medicine( "Ibuprofen", "(Anti-inflammatory)", "7 x a day"));
medicineList.put("6.", new Medicine(" Metoprolol", "(B1-blocker)", "1 x a day"));
medicineList.put("7.", new Medicine("Salbutamol", "(B2-receptor)", "1 x a week"));
medicineList.put("8.", new Medicine( "Fusidinezuur", "(Antibiotic)", "2 x a week"));
medicineList.put("9.", new Medicine( "Acenocoumarol", "(Anticoagulant)", "4 x a day"));
TreeMap<String, Medicine> sorted_medicineList = new TreeMap<>();
sorted_medicineList.putAll(medicineList);
System.out.println("===== Available Medicine =====");
for (String temp : sorted_medicineList.keySet()) {
String key = temp.toString();
String value = sorted_medicineList.get(temp).toString();
System.out.println(key + " " + value);
System.out.println(temp);
}
return medicineList;
}
}
so far i have this for my add method:
Scanner scan = new Scanner(System.in);
System.out.print("Enter medicine id:");
int medicine_to_add = scan.nextInt();
scan.nextLine();
System.out.println("\n".repeat(80));
String medicine_name = String.valueOf(Medicine.getMedicineList().getKeyAt(medicine_to_add -1)).split(" ")[1];
System.out.println("Selected medicine" + medicine_name);

Related

ArrayList in Class A and user trigger the output from Class B. How do I correctly get an output from an ArrayList?

I doing a bigger school project (first part of basic objective programming in java - so not touched extended, polyphorism etc yet, thats next part), but run in to a small problem and tried for couple of days to find solution (thru books and internet). I constructed different ArrayLists in one class and different classes (at least two) should get access to them.
public class Customer
{
public void subMenuCustomer()
{
............code............
int subMenuCust;
ServiceLogic addCustomer = new ServiceLogic();
ServiceLogic listAllCustomers = new ServiceLogic();
while(true)
{
System.out.println("Please Choose your preference: ");
System.out.println("Create account, press \"1\": ");
System.out.println("Get list of clustomers, press \"2\": ");
System.out.println("Log out, press \"0\": ";
subMenuCust = input.nextInt();
switch(subMenuCust)
{
case 1 ://Call method createCustomer in class ServiceTech to add new customers
addCustomer.createCustomer(name, lastname, ssNo);
break;
case 3
listAllCustomers.getCustomer();
............more code..............
}
}
When user has added details (social secuity number, name and lastname) it is stored in seperate ArrayList. These three ArrayList are added(merge/concat) together to a fourth ArayList, listCustomer , so that all elements from the three ArrayList end up in same index [101 -54 Clark Kent, 242-42 Linus Thorvalds, ...].
import java.util.ArrayList;
import java.util.Scanner;
public class ServiceLogic
{
//Create new ArrayLists of Strings
private ArrayList<String> listSSNoCustomers = new ArrayList<>();
private ArrayList<String> listNameCustomers = new ArrayList<>();
private ArrayList<String> listLastnameCustomers = new ArrayList<>();
private ArrayList<String> listCustomers;
Scanner input = new Scanner(System.in);
public boolean createCustomer(String name, String lastname, String ssNo) //
{
System.out.println("Write social security number; ");
ssNo = input.next();
//loop to check that it is a uniq social security number
for(String ssNumber : listSSNoCustomers)
{
if (ssNumber.equals(ssNo))
{
System.out.println("This customer already exist. Must be uniq social security number.");
return true;
}
}
//If social security number is not on list, add it
//and continue add first name and surname
listSSNoCustomers.add(ssNo);
System.out.println(ssNo);
System.out.println("Write firstname; ");
name = input.next();
listNameCustomers.add(name);
System.out.println(name);
System.out.println("Write lastnamame; ");
surname = input.next();
listSurnameCustomers.add(lastname);
System.out.println(lastname);
return false;
}
public void setListCustomer(ArrayList<String> listCustomers)
{
this.listCustomers = listCustomers;
}
public ArrayList<String> getCustomer()
{
//ArrayList<String> listCustomers = new ArrayList<>();
for(int i = 0; i <listSSNoCustomers.size(); i++)
{
listCustomers.add(listSSNoCustomers.get(i) + " " + listNameCustomers.get(i) + " " + listFirstnameCustomers.get(i));
}
System.out.println("customer" + listCustomers);
return listCustomers;
}
}
According to the specification we got, when user want to see list of all customer the outputs should be in format [666-66 Bruce Wayne, 242-42 Linus Thorvalds, ...].
When user (staff) choose to enter details in class Customer ( Case 1 ) it works and elements get stored in the Arraylists for social security numbers, name and lastname (have checked that) .
The problem: when I run I can add customers, but when I try to get a list of customer the output: [] . I tried different solution, but same output only empty between the brackets.
So the question, how do I get ouput to work when user choose case 2 to get a list of all cutomers?

Implementing 2 Java Classes

I'm learning java and trying to implement two java classes.
Student: firstName, lastName, departmentIn, yearGraduation, an array of UAClass this student is taking, an array of integers corresponding to the grades received for these classes
UAClass: teacherFirstName, teacherLastName, semesterOffered, numCredits
In the Student class, implement a method that calculates GPA. In the Student’s main() method, initiate one Student object and print out her GPA.
In my student.java class I have:
import java.util.*;
public class Student {
private String firstName;
private String lastName;
private String departmentIn;
private String yearGraduation;
private float [] grade;
private int counter = 0;
private String Student;
public Student(String my_firstName, String my_lastName, String my_deptIn, String my_yearGrad) {
firstName = my_firstName;
lastName = my_lastName;
departmentIn = my_deptIn;
yearGraduation = my_yearGrad;
grade = new float[5];
}
public String toString(){
String value;
value = "First Name: " + firstName + "\n";
value += "Last Name : " + lastName + "\n";
value += "Department: " + departmentIn + "\n";
value += "Grad. Year: " + yearGraduation + "\n";
return value;
}
public static void main(String[] args) {
Student my1 = new Student("Bob", "Hope", "MBA", "2018");
Student my2 = new Student("John", "Smith", "MBA", "2020");
Student my3 = new Student("Jane", "Doe", "MBA", "2021");
UAClass cy1 = new UAClass[4];
String[] secondArray = cy1.getarrayClass();
System.out.println(my1);
System.out.println(my2);
System.out.println(my3);
System.out.println(Arrays.toString(cy1));
}
}
And in my UAClass.java class I have:
import java.util.*;
public class UAClass {
private String teacherFirstName;
private String teacherLastName;
private String semesterOffered;
private String numCredits;
private String[] arrayClass = {"MBA 501","MBA 505","MBA 513","MBA 545"};
public UAClass(String teacherF, String teacherL, String semesterO, String numC) {
teacherFirstName = teacherF;
teacherLastName = teacherL;
semesterOffered = semesterO;
numCredits = numC;
}
public String[] getarrayClass(){
return arrayClass.clone();
}
}
What I am trying to do is to create an Array in 'UAClass' and having it printed into 'Student' but I can't seem to get it working.
I've modified the code as Amit suggested. When I run it, I get this error.
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: Array.getarrayClass at Homework2.Student.main(Student.java:66)
It seems to be having an issue with String[] secondArray = cy1.getarrayClass();
I took out the line String[] secondArray = cy1.getarrayClass() and it seems to run fine but now all I get is [null, null, null, null]
First of all, your UAClass has one constructor that takes String teacherF, String teacherL, String semesterO, String numC as parameters.
So you need to call this constructor like this:
UAClass cy1 = new UAClass("Teacher F", "Teacher L", "Semester", "NumC");
Secondly, you use an String[] type. This is a low-level array type. You can do this in Java, but normally people rather use a List type, and then not the raw type, but better like List<String>. List is actually an interface, but you can reference it as the Arrays class returns an implementation of the List class.
You should then use:
private List<String> arrayClass = Arrays.asList("MBA 501","MBA 505","MBA 513","MBA 545");
And you return a clone of the array. I presume you do this because you don't want the array to be changed. I would just return a concatenated String with values. Here is a nice example with a stream.
public String getClasses() {
return arrayClass.stream().collect(Collectors.joining(","));
}
Now in the Student class you can just print the list of classes like this:
System.out.println(cy1.getClasses());
When you change your code like that it will work but I couldn't understand what you are trying to do in your code.
UAClass cy1 = new UAClass("Bob", "", "", "");
String[] secondArray = cy1.getarrayClass();
System.out.println(my1);
System.out.println(my2);
System.out.println(my3);
System.out.println(cy1.getarrayClass());

manipulate and sort text file

I am working on a project where I have been given a text file and I have to add up the points for each team and printout the top 5 teams.
The text file looks like this:
FRAMae Berenice MEITE 455.455<br>
CHNKexin ZHANG 454.584<br>
UKRNatalia POPOVA 453.443<br>
GERNathalie WEINZIERL 452.162<br>
RUSEvgeny PLYUSHCHENKO 191.399<br>
CANPatrick CHAN 189.718<br>
CHNHan YAN 185.527<br>
CHNCheng & Hao 271.018<br>
ITAStefania & Ondrej 270.317<br>
USAMarissa & Simon 264.256<br>
GERMaylin & Daniel 260.825<br>
FRAFlorent AMODIO 179.936<br>
GERPeter LIEBERS 179.615<br>
JPNYuzuru HANYU 197.9810<br>
USAJeremy ABBOTT 165.654<br>
UKRYakov GODOROZHA 160.513<br>
GBRMatthew PARR 157.402<br>
ITAPaul Bonifacio PARKINSON 153.941<br>
RUSTatiana & Maxim 283.7910<br>
CANMeagan & Eric 273.109<br>
FRAVanessa & Morgan 257.454<br>
JPNNarumi & Ryuichi 246.563<br>
JPNCathy & Chris 352.003<br>
UKRSiobhan & Dmitri 349.192<br>
CHNXintong &Xun 347.881<br>
RUSYulia LIPNITSKAYA 472.9010<br>
ITACarolina KOSTNER 470.849<br>
JPNMao ASADA 464.078<br>
UKRJulia & Yuri 246.342<br>
GBRStacey & David 244.701<br>
USAMeryl &Charlie 375.9810<br>
CANTessa & Scott 372.989<br>
RUSEkaterina & Dmitri 370.278<br>
FRANathalie & Fabian 369.157<br>
ITAAnna & Luca 364.926<br>
GERNelli & Alexander 358.045<br>
GBRPenny & Nicholas 352.934<br>
USAAshley WAGNER 463.107<br>
CANKaetlyn OSMOND 462.546<br>
GBRJenna MCCORKELL 450.091<br>
The first three letters represent the team.
the rest of the text is the the competitors name.
The last digit is the score the competitor recived.
Code so far:
import java.util.Arrays;
public class project2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] array = new String[41];
String[] info = new String[41];
String[] stats = new String[41];
String[] team = new String[41];
//.txt file location
FileInput fileIn = new FileInput();
fileIn.openFile("C:\\Users\\O\\Desktop\\turn in\\team.txt");
// txt file to array
int i = 0;
String line = fileIn.readLine();
array[i] = line;
i++;
while (line != null) {
line = fileIn.readLine();
array[i] = line;
i++;
}
//Splitting up Info/team/score into seprate arrays
for (int j = 0; j < 40; j++) {
team[j] = array[j].substring(0, 3).trim();
info[j] = array[j].substring(3, 30).trim();
stats[j] = array[j].substring(36).trim();
}
// Random stuff i have been trying
System.out.println(team[1]);
System.out.println(info[1]);
System.out.println(stats[1]);
MyObject ob = new MyObject();
ob.setText(info[0]);
ob.setNumber(7, 23);
ob.setNumber(3, 456);
System.out.println("Text is " + ob.getText() + " and number 3 is " + ob.getNumber(7));
}
}
I'm pretty much stuck at this point because I am not sure how to add each teams score together.
This looks like homework... First of all you need to examine how you are parsing the strings in the file.
You're saying: the first 3 characters are the country, which looks correct, but then you set the info to the 4th through the 30th characters, which isn't correct. You need to dynamically figure out where that ends and the score begins. There is a space between the "info" and the "stats," knowing that you could use String's indexOf function. (http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(int))
Have a look at Maps.
A map is a collection that allows you to get data associated with a key in a very short time.
You can create a Map where the key is a country name, with value being the total points.
example:
Map<String,Integer> totalScore = new HashMap<>();
if (totalScore.containsKey("COUNTRYNAME"))
totalScore.put("COUNTRYNAME", totalScore.get("COUNTRYNAME") + playerScore)
else
totalScore.put("COUNTRYNAME",0)
This will add to the country score if the score exists, otherwise it will create a new totalScore for a country initialized to 0.
Not tested, but should give you some ideas:
public static void main(String... args)
throws Exception {
class Structure implements Comparable<Structure> {
private String team;
private String name;
private Double score;
public Structure(String team, String name, Double score) {
this.team = team;
this.name = name;
this.score = score;
}
public String getTeam() {
return team;
}
public String getName() {
return name;
}
public Double getScore() {
return score;
}
#Override
public int compareTo(Structure o) {
return this.score.compareTo(o.score);
}
}
File file = new File("path to your file");
List<String> lines = Files.readAllLines(Paths.get(file.toURI()), StandardCharsets.UTF_8);
Pattern p = Pattern.compile("(\\d+(?:\\.\\d+))");
List<Structure> structures = new ArrayList<Structure>();
for (String line : lines) {
Matcher m = p.matcher(line);
while (m.find()) {
String number = m.group(1);
String text = line.substring(0, line.indexOf(number) - 1);
double d = Double.parseDouble(number);
String team = text.substring(0, 3);
String name = text.substring(3, text.length());
structures.add(new Structure(team, name, d));
}
}
Collections.sort(structures);
List<Structure> topFive = structures.subList(0, 5);
for (Structure structure : topFive) {
System.out.println("Team: " + structure.getTeam());
System.out.println("Name: " + structure.getName());
System.out.println("Score: " + structure.getScore());
}
}
Just remove <br> from your file.
Loading file into memory
Your string splitting logic looks fine.
Create a class like PlayerData. Create one instance of that class for each row and set all the three fields into that using setters.
Keep adding the PlayerData objects into an array list.
Accumulating
Loop through the arraylist and accumulate the team scores into a hashmap. Create a Map to accumulate the team scores by mapping teamCode to totalScore.
Always store row data in a custom object for each row. String[] for each column is not a good way of holding data in general.
Take a look in File Utils. After that you can extract the content from last space character using String Utils e removing the <br> using it as a key for a TreeMap. Than you can have your itens ordered.
List<String> lines = FileUtils.readLines(yourFile);
Map<String, String> ordered = new TreeMap<>();
for (String s : lines) {
String[] split = s.split(" ");
String name = split[0].trim();
String rate = splt[1].trim().substring(0, key.length - 4);
ordered.put(rate, name);
}
Collection<String> rates = ordered.values(); //names ordered by rate
Of course that you need to adjust the snippet.

Populating a HashMap with an Array

So I tried finding a tutorial on how to do this but nothing gets this complicated. This is the first I am learning of HAshMaps so I am sure my solution should be easy, but I don't know how to do it.
I am trying to use an Array to populate a HashMap, and when I run the program my print out shows up null, which indicates that it isn't populating for me. Been working on this for two days, and am really lost and confused.
I am trying to get my key "expenses" to be valued with a "type".
Edit: I would like my case two to be a printout of
1: groceries
2: Entertainment
3: Etc.....
public static void main(String[] args) throws FileNotFoundException, IOException
{
// TODO code application logic here
// HashMap<String, String> map = new HashMap<String, String>();
HashMap<String, List<Expenses>> map = new HashMap<>();
List <Expenses> expenseType = new ArrayList();
double amount, totalAmount;
int cmd, year, month, date;
String type, resp;
totalAmount = 0;
String fname = JOptionPane.showInputDialog("Enter the name of the budget file, none if no file");
if (fname.compareTo("none") !=0)
{
FileInputStream ist = new FileInputStream(fname);
ObjectInputStream ifile = new ObjectInputStream(ist);
}
boolean done = false;
while(!done)
{
resp = JOptionPane.showInputDialog("Enter a command from: \n"
+ "\t1:Add a new deduction\n" //think its done
+ "\t2:Add a new expense\n" //this is done, but could be made better wit
+ "\t3:Add a deposit\n" //This is done
+ "\t4:Deduction options\n"
+ "\t5:Expense Options\n"
+ "\t6:Total balances in bank\n"
+ "\t7:quit");
cmd = Integer.parseInt(resp);
switch(cmd)
{
case 1:
break;
case 2:
//Give the option to add new spending occurence.
//Give option to choose from array of spending types.
resp = JOptionPane.showInputDialog("Enter a command from: \n"
+ "\t1: Create a new expense\n" //done
+ "\t2: Choose from expense list\n"
+ "\t3:quit");
int cmd2 = Integer.parseInt(resp);
switch (cmd2)
{
case 1:
type = JOptionPane.showInputDialog("Enter the type of the expense:");
resp = JOptionPane.showInputDialog("Enter the amount of the expense:");
amount = Double.parseDouble(resp);
resp = JOptionPane.showInputDialog("Enter the year of the expense:");
year = Integer.parseInt(resp);
resp = JOptionPane.showInputDialog("Enter the month of the expense:");
month = Integer.parseInt(resp);
resp = JOptionPane.showInputDialog("Enter the date of the expense:");
date = Integer.parseInt(resp);
// List<Expenses> expenses = map.get(type);
// Does the map have a List for type?
if (expenseType == null) {
// No. Add one.
expenseType = new ArrayList<>();
map.put(type, expenseType);
}
Expenses e = new Expenses(type, amount, year, month, date);
expenseType.add(e);
// map.put(type, new ArrayList(expenses));
map.put(type, expenseType);
break;
case 2:
//Use a hashmap to search through the ArrayLIst and print out options.
//How do I populate the HashMap?
type = null;
List<Expenses> typelist = map.get(type); //reads from map
System.out.println(typelist);
break;
}
}
}
}
}
Please don't use raw types. And, if I understand you, then you want something like
Map<String, List<Expenses>> map = new HashMap<>();
Then, to add to the List in the Map - use something like
List<Expenses> expenses = map.get(type);
// Does the map have a List for type?
if (expenses == null) {
// No. Add one.
expenses = new ArrayList<>();
map.put(type, expenses);
}
Expenses e = new Expenses(type, amount, year, month, date);
expenses.add(e);
1) You should have this line
map.put(new String(type),expenses);
instead of
map.put(expenses, new String(type));
to get value from hashmap using key i.e. type.
2) Also remove double quotes from
List<Expenses> typelist = map.get("type");
to pass variable type.

Passing arrays into testclass constructors

I need to pass a 1d array that isn't defined in a method.
I need to create a testclass then make the arrays myself.
I'm just not sure about the syntax.
Example, here's my company class:
public class Company
{
String name;
String address;
Employee employeeList[] = new Employee[3];
public Company (String name, String address ,
Employee employeeList, String jobTitle )
{
this.name = name;
this.address = address;
}
public void printDetails()
{
for(int i = 0; i>employeeList.length;i++)
{
System.out.println(" The companys name is " + name);
System.out.println(" The Companys Address is "+ address);
System.out.println("The List of employees are " + employeeList[i].name);
System.out.println("The Titles of These Employees are " + employeeList[i].jobTitle);
}
}
}
But my testclass is where the problem lies.
Where do I go from here? Do do I put arrays(employees) into it?
public class TestCompany
{
public static void main(String[] args)
{ employees?
Company hungryBear = new Company("hungryBear ", "Those weird apartments ",////// );
}
}
public Company (String name, String address ,
Employee employeeList, String jobTitle )
Should be:
public Company (String name, String address ,
Employee []employeeList, String jobTitle )
Right now, you're not passing an array to your method, your passing an instance. You need to tell Java that you're passing an array.
Editted with new knowledge of the employee class...
Also, you will need to build the array in your main function before you pass it. Something like this:
public static void main(String[] args){
Employee [] employeeList = {
new Employee("Samuel T. Anders", "Player, Caprica Buccaneers"),
new Employee("William Adama", "Commander, Battlestar Galactica")
};
Company hungryBear = new Company("hungryBear ", "Those weird apartments ", employeeList);
}
Not really sure this answers your question, but maybe this will help you with the syntax of array passing a little.
Another edit, another way to initialize an array:
Empolyee [] employeeList = new Employee[2];
employeeList[0] = new Employee("Samuel T. Anders", "Player, Caprica Buccaneers");
employeeList[1] = new Employee("William Adama", "Commander, Battlestar Galactica");
Empolyee [] employeeList = new Employee[2];
for(int i=0;i<2;i++){
Scanner input = new Scanner(System.in);
employeeList[i] = input.next();
}

Categories

Resources