Saving Inputs to ArrayList - java

So I am making a project and I want to create a new clinic.
On my UI we insert all the topics that we need to create the clinic and they must be saved as ArrayList and I am struggling with this method.
this is how i am asking for the input, should i change to a scanner?
laboratoryId = Utils.readLineFromConsole("Enter Clinic Id: ");
class to the array
public class ClinicalAnalysisLabStore{
private ArrayList<ClinicalAnalysisLab> cliniclist;
public ClinicalAnalysisLabStore(){
cliniclist = new ArrayList<>();
}
public ArrayList<ClinicalAnalysisLab> getCliniclist() {
return cliniclist;
}
cals = new ClinicalAnalysisLabStore();
ArrayList<ClinicalAnalysisLab> cliniclist = cals.getCliniclist();
for(ClinicalAnalysisLab cals : cliniclist){
System.out.print(cals.getLaboratoryId()+"\n");
System.out.print(cals.getName()+ "\n");
System.out.print(cals.getAddress()+"\n");
System.out.print(cals.getPhoneNumber()+"\n");
System.out.print(cals.getTinNumber()+"\n");
System.out.print(cals.getTestType()+"\n");
}
Utils.readLineFromConsole("The Operation was a success!");
this is a short cut from my code where i am trying to print the arraylist but it only prints "The Operation was a success!"

You're ArrayList is empty. So, the code is actually working perfectly.
What you'll need to do is add items to the ArrayList.
To add an item:
laboratoryId = Utils.readLineFromConsole("Enter Clinic Id: ");
ClinicalAnalysisLab obj = new ClinicalAnalysisLab(laboratoryId, *name*, *address*, *phoneNumber*, *tinNumber*) {
clinicList.add(obj);
In this case, you would just create the object based on however you want. So, change the variables "name", "address", "phoneNumber", and "tinNumber" with whatever you want.
One example would be:
laboratoryId = Utils.readLineFromConsole("Enter Clinic Id: ");
ClinicalAnalysisLab obj = new ClinicalAnalysisLab(laboratoryId, "First Lab", "32 Lincoln Rd", "666 666 6666, "102") {
clinicList.add(obj);

Related

Creating Objects with dynamic Subclasses using a String Array

im actually working on a Project for my University.
In a case, the user is able to produce new Objects and my problem is, that ALL needed Objects are from a SubClass of ASpaceShip.
The Question is now how to create dynamic objects with a array of String Inputs from the User.
One of the Problems is, that there will be more SubClasses in the Future and a switch for 50+ subclasses ... naaaa
Example:
class SpaceShipOne extends ASpaceShip
class SpaceShipTwo extends ASpaceShip
class SpaceShipSpecial extends ASpaceShip
class SpaceShipN extends ASpaceShip
Input from User, Stringarray
input[0] = "SpaceShipTwo";
input[1] = "SpaceShipSpecial";
input[n] = "AlreadyExistingClassName";
Needed:
ArrayList<ASpaceShip> shipList; // Containts all Objects from the User input.
I would love to just loop the userinput and
ASpaceShip ship = new (input[0])(); // casting the class with the String name
But this sadly doesnt work ...
Inet isnt giving much help on this topic or stuff that could work but is deprecated :(
Some ideas here?
Code of Servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Required Objects
HttpSession session = request.getSession();
Player player = (Player)session.getAttribute("player");
TechTree techtree = player.getTechTree(); // Ships need their TechTree
ArrayList<ASpaceShip> ships = new ArrayList<ASpaceShip>(); // to save Ships which are build
ArrayList<ASpaceShip> allResearchedShips = techtree.getAllResearchedShips(); // to save Ships which are build
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String shipName = parameterNames.nextElement();
String[] paramSValue = request.getParameterValues(shipName);
int pVal = Integer.parseInt(paramSValue[0]);
if (hasShip(allResearchedShips, shipName)) {
if (pVal > 0) {
//ASpaceShip newShip = new Class<shipName>(techtree,1);
}
}
}
} // End doPost
If I understand well your question, you would simply need to have a switch / case statement or an if etc, checking user input string and constructing the appropriate object using the proper subclass. Then all constructed object could be added to an ArrayList<ASpaceShip> , eg holding all objects that extend ASpaceShip
ASpaceShip a = null;
ArrayList<ASpaceShip> myList = new ArrayList<>();
for (String s : inputArray) {
if ("SpaceShipOne".equals(s)) a = new SpaceShipOne();
if ("SpaceShipTwo".equals(s)) a = new SpaceShipTwo();
...
myList.add(a);
}
UPDATE:
Using reflection :
ASpaceShip a = null;
ArrayList<ASpaceShip> myList = new ArrayList<>();
String[] array = {"SpaceShipTwo","SpaceShipSpecial"};
for (String className : array) {
Class aClass = Class.forName("yourPackagePath" + className); // need to pass full class name here
a = (ASpaceShip)aClass.newInstance();
myList.add(a);
}
for (ASpaceShip as : myList) System.out.println(as.getClass().getSimpleName());

int array or string array or im wrong

Im trying to put date&time into the array but im getting the error since i cannot put date/time with or just variables, i have tried changing the array of int to string but im getting the error that it cannot be resolved into a variable
private static void listM() {
// TODO Auto-generated method stub
System.out.println("Here is the list of Movie(s) to select from," // gives user a list of movies to choose from
+ "\nPlease enter its respective ID:\n"
+ "1. Captain America\t|2. Toy Story\t|3. Jumanji\n4. Black Panther\t|"
+ "5. Green Lantern\t|6. Detective Pikachu\n7. Thor\t|8. 2012\t|9. Geostorm\n");
System.out.println("");
Scanner scanner = new Scanner(System.in); //use scanner to get ID of Movie
System.out.print("Input the ID of the Movies to view their information: ");
int idmovie = scanner.nextInt();
String[] movie = new String[9]; //make an array to store the movie information
movie[0] = test;
movie[1] = Captain;
movie[2] = xxx;
movie[3] = xxx;
movie[4] = xxx;
movie[5] = xxx;
movie[6] = xxx;
movie[7] = xxx;
movie[8] = xxx;
You need to put quotes around strings. When you write movie[0] = test;, java will try to put the value of a variable named test into the movie array. Because you don't have a variable named test defined, Java will throw the error you are getting.
Here is how you probably want to define your array:
movie[0] = "test";

Java string array doesn't print correctly

I am currently working on a Java program that crawls a webpage and prints out some information from it.
There is one part that I can't figure out, and thats when I try to print out one specific String Array with some information in it, all it gives me is " ] " for that line. However, a few lines before, I also try printing out another String array in the exact same way and it prints out fine. When I test what is actually being passed to the "categories" variable, its the correct information and can be printed out there.
public class Crawler {
private Document htmlDocument;
String [] keywords, categories;
public void printData(String urlToCrawl)
{
nextURL=urlToCrawl;
crawl();
//This does what its supposed to do. (Print Statement 1)
System.out.print("Keywords: ");
for (String i :keywords) {System.out.print(i+", ");}
//This doesnt. (Print Statement 2)
System.out.print("Categories: ");
for (String b :categories) {System.out.print(b+", ");}
}
public void crawl()
{
//Gather Data
//open up JSOUP for HTTP parsing.
Connection connection = Jsoup.connect(nextURL).userAgent(USER_AGENT);
Document htmlDocument = connection.get();
this.htmlDocument=htmlDocument;
System.out.println("Recieved Webpage "+ nextURL);
int guacCounter = 0;
for(Element guac : htmlDocument.select("script"))
{
if(guacCounter==5)
{
//String concentratedGuac = guac.toString();
String[] items = guac.toString().split("\\n");
categories = processGuac(items);
break;
}
else if(guacCounter<5) {
guacCounter++;
}
}
}
public String[] processKeywords(String totalKeywords)
{
String [] separatedKeywords = totalKeywords.split(",");
//System.out.println(separatedKeywords.toString());
return separatedKeywords;
}
public String[] processGuac(String[] inputGuac)
{
int categoryIsOnLine = 6;
String categoryData = inputGuac[categoryIsOnLine-1];
categoryData = categoryData.replace(",","");
categoryData = categoryData.replace("'","");
categoryData = categoryData.replace("|",",");
categoryData = categoryData.split(":")[1];
//this prints out the list of categories in string form.(Print Statement 3)
System.out.println("Testing here: " + categoryData.toString());
String [] categoryList=categoryData.split(",");
//This prints out the list of categories in array form correctly.(Print statement 4)
System.out.println("Testing here too: " );
for(String a : categoryList) {System.out.println(a);}
return categoryList;
}
}
I cut out a lot of the irrelevant parts of my code so there might be some missing variables.
Here is what my printouts look like:
PS1:
Keywords: What makes a good friend, making friends, signs of a good friend, supporting friends, conflict management,
PS2:
]
PS3:
Testing here: wellbeing,friends-and-family,friendships
PS4:
Testing here too:
wellbeing
friends-and-family
friendships

Java - Text File - Reading between certain Strings

I tried to figure out the following problem for the last 20 hours, so I thought before I start thinking about jumping out of the window ;-), I better ask here for help:
I have a text file with following content:
ID
1
Title
Men and mice
Content
Lenny loves kittens
ID
2
Title
Here is now only the Title of a Book
ID
3
Content
Here is now only the Content of a Book
The problem as you can see is that there is either both title and content after id or only title after id.
I want to create text files which contain an ID value (for example 1) and the corresponding title value and/or content value.
The best I achieved was three lists. One with id values, one with title values and one with content values. But it is actually useless, because the information between id, content and title is lost.
I would really appreciate your held.
So you want to populate a collection of a class with three fields.
class Data {
int id;
String title;
String content;
// helper method to read a file and return a list.
public static List<Data> readAll(String filename) throws IOException {
// List we will return.
List<Data> ret = new ArrayList<Data>();
// last value we added.
Data last = null;
// Open a file as text so we can read the lines.
// us try-with-resource so the file is closed when we are done.
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
// declare a String and use it in a loop.
// read line and stop when we get a null
for (String line; (line = br.readLine()) != null; ) {
// look the heading.
switch (line) {
case "ID":
// assume ID is always first
ret.add(last = new Data());
// read the next line and parse it as an integer
last.id = Integer.parseInt(br.readLine());
break;
case "Title":
// read the next line and save it as a title
last.title = br.readLine();
break;
case "Content":
// read the next line and save it as a content
last.content = br.readLine();
break;
}
}
}
return ret;
}
}
Note: the only field which matters is ID. Content and Title are optional.
To get from 20 hours down to 5 minutes, you need to practice, a lot.
You can keep "the information between id, content and title" in your program if you create a Book class and then have a list of Book instances.
Book class:
public class Book {
private int id;
private String title;
private String content;
//...
//getters and setters
}
List of books:
private List<Book> books = new ArrayList<Book>();

Read in text file pass to an array of objects Java

I am creating a program like Mint.
right now, I am getting information from a text file, splitting it by the spaces, then going to pass it to the Constructor of another class to create objects. I am having a bit of trouble getting that done properly.
I don't know how to get the information I actually need from the text file with all the extra stuff that's in it.
I need to have an array of objects that has 100 spots. The Constructor is
public Expense (int cN, String desc, SimpleDateFormat dt, double amt, boolean repeat)
The file comes as :
(0,"Cell Phone Plan", new SimpleDateFormat("08/15/2015"), 85.22, true);
(0,"Car Insurance", new SimpleDateFormat("08/05/2015"), 45.22, true);
(0,"Office Depot - filing cabinet", new SimpleDateFormat("08/31/2015"), 185.22, false);
(0,"Gateway - oil change", new SimpleDateFormat("08/29/2015"), 35.42, false);
Below is my code for the main:
Expense expense[] = new Expense[100];
Expense e = new Expense();
int catNum;
String name;
SimpleDateFormat date = new SimpleDateFormat("01/01/2015");
double price;
boolean monthly;
try {
File file = new File("expenses.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String array[] = line.split(",");
expenses[i] = new Expense(catNum, name, date, price, monthly);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Step by step:
//(0,"Cell Phone Plan", new SimpleDateFormat("08/15/2015"), 85.22, true);
String array[] = line.split(",");
Will produce this array
[0] (0
[1] "Cell Phone Plan"
[2] new SimpleDateFormat("08/15/2015")
[3] 85.22
[4] true);
So
expenses[i] = new Expense(catNum, name, date, price, monthly);
Wont work because it expects another data in almost each parameter:
In order to fix this:
you must ignore ( and ); when splitting line
be careful with " in the given string, you must scape this characters or ignore them
you wont be able to use: new SimpleDateFormat("08/15/2015") you must create the object by yourself
this is not a correct date format "08/15/2015"!!!!
SOLUTION: if you are creating the file to parse, I would recommend to change it's format to:
//(0,"Cell Phone Plan", new SimpleDateFormat("08/15/2015"), 85.22, true);
0,Cell Phone Plan,MM/dd/yyyy,85.22,true
Then:
String array[] = line.split(",");
Will produce
[0] 0
[1] Cell Phone Plan
[2] MM/dd/yyyy
[3] 85.22
[4] true
Then you can simply parse non string values with:
new SimpleDateFormat(array[2]).
Double.parseDouble(array[3])
Boolean.parseBoolean(array[4])
UPDATE
Check here a working demo that you must adapt to make it work.
OUTPUT:
public Expense (0, Cell Phone Plan, 08/15/2015, 85.22, false );
public Expense (0, Car Insurance, 08/05/2015, 45.22, false );

Categories