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());
Related
So i've been trying to solve this issue for hours but cant seem to find an answer which would work.
i have an object array which stores flight information and i had to remove flights which had Valstybe: "Maldyvai"
so i made a new object array without them, but when i try to print it i get a memory location.
How do i convert the object array to string array?
even though i have a tostring method in my java class
package com.company;
import java.util.*;
import com.company.Isvestine.OroUostasKeleivis;
public class Main {
public static void main(String[] args) {
// write your code here
OroUostasKeleivis Keleiviai1 = new OroUostasKeleivis("Skrydis","Washington","JAV","Tomas","tomaitis","Washington",5465);
OroUostasKeleivis Keleiviai2 = new OroUostasKeleivis("Skrydis","Washington","Maldyvai","Tomas","tomaitis","Maldyvai",5466);
OroUostasKeleivis Keleiviai3 = new OroUostasKeleivis("Skrydis","Washington","JAV","Tomas","tomaitis","Washington",5467);
OroUostasKeleivis Keleiviai4 = new OroUostasKeleivis("Skrydis","Washington","Maldyvai","Tomas","tomaitis","Maldyvai",5468);
OroUostasKeleivis Keleiviai5 = new OroUostasKeleivis("Skrydis","Washington","JAV","Tomas","tomaitis","Washington",5469);
OroUostasKeleivis Keleiviai6 = new OroUostasKeleivis("Skrydis","Washington","Maldyvai","Tomas","tomaitis","Maldyvai",5470);
OroUostasKeleivis Keleiviai7 = new OroUostasKeleivis("Skrydis","Washington","JAV","Tomas","tomaitis","Washington",5475);
OroUostasKeleivis Keleiviai8 = new OroUostasKeleivis("Skrydis","Washington","Maldyvai","Tomas","tomaitis","Maldyvai",5476);
OroUostasKeleivis Keleiviai9 = new OroUostasKeleivis("Skrydis","Washington","JAV","Tomas","tomaitis","Washington",5477);
OroUostasKeleivis Keleiviai10 = new OroUostasKeleivis("Skrydis","Washington","JAV","Tomas","tomaitis","Washington",5488);
OroUostasKeleivis[] keleiviai = new OroUostasKeleivis[10];
keleiviai[0] = Keleiviai1;
keleiviai[1] = Keleiviai2;
keleiviai[2] = Keleiviai3;
keleiviai[3] = Keleiviai4;
keleiviai[4] = Keleiviai5;
keleiviai[5] = Keleiviai6;
keleiviai[6] = Keleiviai7;
keleiviai[7] = Keleiviai8;
keleiviai[8] = Keleiviai9;
keleiviai[9] = Keleiviai10;
for (OroUostasKeleivis keleiveliai:keleiviai) {
System.out.println(keleiveliai);
}
System.out.println("test debug");
OroUostasKeleivis[] keleiviaibemaldyvu = new OroUostasKeleivis[10];
for (int i = 0; i < 10; i++) {
}
System.out.println(IsstrintiMaldyvus(keleiviai));
String convertedStringObject = IsstrintiMaldyvus(keleiviai) .toString();
System.out.println(convertedStringObject );
}
static Object[] IsstrintiMaldyvus(OroUostasKeleivis[] keleiviai){
OroUostasKeleivis[] keleiviaiBeMaldyvu = new OroUostasKeleivis[10];
int pozicija = 0;
for ( OroUostasKeleivis keleiveliai: keleiviai) {
if (keleiveliai.getValstybe() != "Maldyvai"){
keleiviaiBeMaldyvu[pozicija] = keleiveliai;
pozicija++;
}
}
return keleiviaiBeMaldyvu;
}
}
but when i try to print it i get a memory location
Yes, you will NOT have result as you expected, especially calling toString() with any array. See documentation of java.lang.Object.toString() for more details.
So how can we solve problem?
first, override toString() method in OroUostasKeleivis like this:
class OroUostasKeleivis {
#Override
public String toString() {
// your implementation here
return null; // TODO: change here
}
}
Second, you may do either way:
If you're interested in just print out, you can do that with System.out.println(keleiveliai) in for-each loop like you do.
If you're interested in converting OroUostasKeleivis[] to String[], you can:
// this requires Java 8 or later
String[] converted = Arrays.asList(keleiviai)
.stream()
.map(OroUostasKeleivis::toString)
.toArray(String[]::new);
// then use `converted`
Use System.out.println(Arrays.toString(IsstrintiMaldyvus(keleiviai)))
https://www.geeksforgeeks.org/arrays-tostring-in-java-with-examples/
It will print the array contents similar to how ArrayList would get printed if it had the same content.
Think of it as:
[ obj1.toString(), obj2.toString(), ... ]
Using java.util.Arrays#stream(T[]) filter and convert object array to string array and use java.util.Arrays#toString(java.lang.Object[]) convert array to readable string.
final String[] oroUostasKeleivis = Arrays.stream(keleiviai)
.filter(
k -> k.getValStybe() != "Maldyvai"
)
// or other convert code
.map(OroUostasKeleivis::toString)
.toArray(String[]::new);
System.out.println(Arrays.toString(oroUostasKeleivis));
I am working on a JSF based Web Application where I read contents from a file(dumpfile) and then parse it using a logic and keep adding it to a list using an object and also set a string using the object. But I keep getting this error. I am confused where I am wrong. I am a beginner so can anyone be kind enough to help me?
List<DumpController> FinalDumpNotes;
public List<DumpController> initializeDumpNotes()
throws SocketException, IOException {
PostProcessedDump postProcessedDump = (PostProcessedDump) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("postProcessedDump");
List<DumpController> FinalNotes = new ArrayList<>();
if (postProcessedDump.getDumpNotes() == null) {
dumpNotes = new DumpNotes();
}
DumpListController dlcon = (DumpListController) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("dumpListController");
DumpInfo dumpinfo = dlcon.getSelectedDumpInfo();
String fileName = dumpinfo.getDate() + dumpinfo.getTime() + dumpinfo.getSeqNo() + dumpinfo.getType() + dumpinfo.getTape() + dumpinfo.getDescription() + ".txt";
if (checkFileExistsInWin(fileName)) {
postProcessedDump.setDumpnotescontent(getFileContentsFromWin(fileName));
String consolidateDumpnotes = getFileContentsFromWin(fileName);
String lines[];
String content = "";
lines = consolidateDumpnotes.split("\\r?\\n");
List<String> finallines = new ArrayList<>();
int k = 0;
for (int i = 0; i < lines.length; i++) {
if (!lines[i].equalsIgnoreCase("")) {
finallines.add(lines[i]);
k++;
}
}
for (int j = 0; j < finallines.size(); j++) {
if (finallines.get(j).startsWith("---------------------SAVED BY")) {
PostProcessedDump dump = new PostProcessedDump();
dump.setDumpMessage(content);
content = "";
FinalDumpNotes.add(dump);
} else {
content = content + finallines.get(j);
}
}
}
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("postProcessedDump", postProcessedDump);
return FinalDumpNotes;
}
I get the following error:
If you want to add instances of type PostProcessedDump to your List you should change it's type. Also, don't forget to initialize it. Something like,
List<PostProcessedDump> FinalDumpNotes = new ArrayList<>();
Also, Java naming convention is to start variable names with a lower case letter. FinalDumpNotes looks like a class, I would suggest something like
List<PostProcessedDump> processedList = new ArrayList<>();
Problems with your code:
List<DumpController> FinalDumpNotes;
You declare FinalDumpNotes to be a List of DumpController objects, but you never initialize it. In addition, your IDE is barfing on the following line of code:
FinalDumpNotes.add(dump);
because you are attempting to add a PostProcessedDump object to the List instead of a DumpController object.
For starters, you need to initialize your list like this:
List<DumpController> finalDumpNotes = new ArrayList<DumpController>();
Notice that I have made the variable name beginning with lower case, which is the convention (upper case is normally reserved for classes and interfaces).
I will leave it to you as a homework assignment to sort out the correct usage of this List.
I recently started working on an app that does a request to a server and gets a json response.
The "thing" functioned beautifully until i had to implement new stuff in the list and now i have a hard time to fix it.
Any help is very appreciated:
class RemoteConfig
{
// names and type must match what we get from the remote
String[] username;
ArrayList<accDetails> in_groups;
String[] in_groups_sorted;
class accDetails
{
int group_id;
String group_label;
Boolean _is_system;
}
This is just a part of how the class starts, and here is how the json reponse looks like:
{
"username":[
"mike"
],
"in_groups":[
{
"group_id":2,
"group_label":"All users",
"_is_system":true
},
{
"group_id":4372,
"group_label":"Privileged User",
"_is_system":false
},
{
"group_id":4979,
"group_label":"Supervisor",
"_is_system":false
}
]
}
The problem that i encounter now, is that i have no idea on how to split the in_groups array list and get into String[] in_groups_sorted the value of Group_label if the _is_system value is false.
Any help is highly appreciated.
Thank you,
Mike
After checking the responses, the cleanest and simplest was the one provided by Abbe:
public String[] groupSettings()
{
String[] levels = new String[] {};
if (remoteConfig != null && remoteConfig.in_groups != null){
for (accDetails ad: remoteConfig.in_groups)
{
if (!ad._is_system) {
levels = ArrayUtils.addAll(levels, ad.group_label); ;
}
}
}
return levels;
}
From your question, I suppose the JSON is already parsed and stored in the in_groups field of RemoteConfig class. And you just need to filter the information you need to populate the in_group_sorted field.
Add the following to the RemoteConfig class:
public initGroupSorted() {
// Temporary list, since we don't know the size once filtered
List<String> labels = new ArrayList<>();
for (accDetails ad : in_groups) {
if (ad._is_system) {
groups.add(ad.group_label);
}
}
in_group_sorted = labels.toArray(new String[labels.size()]);
}
if you donĀ“t want to change the way you parse your JSON, you could always do this:
Let accDetails implement Comparable and then use Collections.sort passing in_groups.
if you really want the String[] you could always iterate over in_groups, add to in_groups_sorted and then using Arrays.sort
Mike, let me give you something that should get you going. From your question i got the feeling that your problem was on how to parse the JSON, so before you go write your own parser, consider the following piece of code that i just wrote:
public void createObjects(String rawJSON) {
try {
JSONObject object = new JSONObject(rawJSON);
JSONArray username = object.getJSONArray("username");
JSONArray inGroups = object.getJSONArray("in_groups");
RemoteConfig config = new RemoteConfig();
config.in_groups = new ArrayList<>();
config.username = username.getString(0);
for (int i = 0; i < inGroups.length(); i++) {
JSONObject group = inGroups.getJSONObject(i);
if (!group.getBoolean("_is_system")) {
accDetails details = new accDetails();
details.group_id = group.getInt("group_id");
details.group_label = group.getString("group_label");
details._is_system = false;
config.in_groups.add(details);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Here is a Java 8 Solution using Stream's filter,sorted, and map methods:
//ArrayList<accDetails> in_groups is already populated
Stream<accDetails> tempStream= in_groups.stream().filter(p -> p._is_system == false);
tempStream= tempStream.sorted((accDetails o1, accDetails o2) -> o1.group_label.compareTo(o2.group_label));
String[] in_groups_sorted = tempStream.map(s -> s.group_label).toArray(String[]::new);
Separated the calls for visibility, but they can be a one liner:
String[] in_groups_sorted = in_groups.stream().filter(p -> p._is_system == false).sorted((accDetails o1, accDetails o2) -> o1.group_label.compareTo(o2.group_label)).map(s -> s.group_label).toArray(String[]::new);
I'll list my code at the bottom, but here's the deal.
I have a parser class with a process method. This method scrapes data from a web page. I want to take each line of the scrape, split the string into an array and add the values to an object, then add the object to an ArrayList. As the loop iterates, new values from each line of the scrape are added to an ArrayList via the object. The relevent method in this code is public ArrayList process()
I'm getting the following compile errors:
The constructor Flight(String) is undefined
Syntax error on token "[", Expression expected after this token
The method add(String) in the type ArrayList is not applicable for the arguments (Flight)
What am I doing wrong here, and how do if fix it?
public class HtmlParser {
public String url;
public String airline;
public static String lastFlight;
static ArrayList<String> capture = new ArrayList<String>();
public HtmlParser(Properties config) throws IOException{
url = config.getProperty("url");
airline = config.getProperty("airline");
print("Fetching.........%s" , url);
}
public ArrayList<String> process() throws IOException{
Document doc = Jsoup.connect(url).get();
Elements tableRow = doc.getElementsByTag("tr");
for(Element tr : tableRow){
if(tr.text().contains(airline)){
String delims = "[ ]+";
String singleRowArray[] = tr.text().split(delims);
Flight f = new Flight(singleRowArray[]);
capture.add(f);
}
}
return capture;
}
Here's my flight Class.
public class Flight {
public Flight(String singleRowArray[]) {
String origin = singleRowArray[0];
String airline1 = singleRowArray[1];
String airline2 = singleRowArray[2];
String flightNo = singleRowArray[3];
String date = singleRowArray[4];
String ArrTime = singleRowArray[5];
String status = singleRowArray[6];
}
}
"The constructor Flight(String) is undefined Syntax error on token "[", Expression expected after this token"
Try switching the brackets to the type, not the variable: String[] singleRowArray
"The method add(String) in the type ArrayList is not applicable for the arguments (Flight)"
You have a List<String> where you want to input an object of type Flight, so you should change the list type to List<Flight>.
static ArrayList<String> capture = new ArrayList<String>();
You can't add the Flight class object in capture list which can only contain element in String type.
Flight f = new Flight(singleRowArray[]);
capture.add(f); // Issue
-----------------^
I am using Blackberry Plug-in and i am using Rich Lists of blackberry.
I want to make lists appear the same number of times as there are entries in the database table.
I m using the below code but it shows only one name in list view.
I need to show all the entries in database into list view...Kindly help me..
I have already used list.add(); inside the for loop but it is showing Exception: java.lang.IllegalStateException: Field added to a manager while it is already parented.
public static void richlistshow(){
String name = null;
list = new RichList(mainManager, true, 2, 0);
Bitmap logoBitmap = Bitmap.getBitmapResource("delete.png");
delete = new BitmapField(logoBitmap, Field.FIELD_HCENTER);
for (int c = 0; c < target_list.size();c++){
City tar_city = new City();
tar_city = (City)target_list.elementAt(c);
name = tar_city.get_city_name().toString();
}
//adding lists to the screen
list.add(new Object[] {delete,name,"time-date"});
}
You didn't posted full codes you are working with. But following code may help you to get rid of IllegalStateException. You were adding same BitmapField instance for every list entries, which caused the exception.
public static void richlistshow() {
final Bitmap logoBitmap = Bitmap.getBitmapResource("delete.png");
list = new RichList(mainManager, true, 2, 0);
for (int c = 0; c < target_list.size(); c++) {
// create a new BitmapField for every entry.
// An UI Field can't have more than one parent.
final BitmapField delete = new BitmapField(logoBitmap, Field.FIELD_HCENTER);
City tar_city = (City) target_list.elementAt(c);
final String name = tar_city.get_city_name().toString();
// add to list
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
list.add(new Object[] { delete, name, "time-date" });
}
});
}
}