Adding elements from one array to another Java - java

Just coming back to Java after a few years break. I am trying to select elements from one array and store them in another in Java. I have created a new array of the same type with a fixed number of elements. The array that I am copying from is not null I have printed it out. But when I try to display the new array the values are not there - just a reference to the element. There probably something that I have overlooked. I have been searching for the last day but am not getting anywhere. I would really appreciate some help. Code below:
PersonDetails user = new PersonDetails(userName,userGender,userAge,userInterests);
PersonDetails [] userArray = new PersonDetails [numberOfDaters];
PersonDetails [] dateArray = new PersonDetails [numberOfDaters];
userArray = user.getArray("datingdata.txt", numberOfDaters);
dateArray = Arrays.copyOf(userArray, userArray.length);
char [][] interestArray = new char[numberOfDaters][5];
for (int z =0;z<userArray.length; z++) {
interestArray[z] =
userArray[z].getAllInterests( userArray[z].getInterests());
}
String remove = user.getOnes(interestArray);
System.out.print(remove);
StringTokenizer st = new StringTokenizer(remove);
int num = st.countTokens();
PersonDetails [] userRemoveArray = new PersonDetails [num];
while(st.hasMoreTokens()) {
int token = Integer.parseInt(st.nextToken());
for(int x =0;x<userRemoveArray.length;x++) {
userRemoveArray[x] = userArray[token];
}
System.out.println(userRemoveArray);
}
The output is as follows:
[LPersonDetails;#a8c488
[LPersonDetails;#a8c488
[LPersonDetails;#a8c488
[LPersonDetails;#a8c488
[LPersonDetails;#a8c488
[LPersonDetails;#a8c488
[LPersonDetails;#a8c488
[LPersonDetails;#a8c488
[LPersonDetails;#a8c488
[LPersonDetails;#a8c488
[LPersonDetails;#a8c488
Thanks in advance

You can use the .addAll(...) method or one of the many methods found here.
As for printing out the elements of the array... you will have to implement your own .toString() method to avoid displaying the object reference.

Here is a small example to make it more easier for you since you had noted that you are just coming back to Java after sometime and i hope this helps you out :)
public class PersonDetails {
private String userName;
private String gender;
#Override
public String toString() {
return "PersonDetails [userName=" + userName + ", gender=" + gender
+ "]";
}
}
Now when you print out the Array, the String created within the toString() method will print for each PersonDetail object.

You should use System.out.println(Arrays.asList(userRemoveArray));.
or
for(int i = 0; i < userRemoveArray.length;i++) {
System.out.print(userRemoveArray[i]+", ");
}
System.out.println();

Related

Java converting object array to string array

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 want to use a stringtokenizer to store strings into an object User array but get an error message

I am getting an error that says Exception in thread "main" java.lang.NullPointerException at Members. init (Members.java:23) at Main.main(Main.java:9)
And what I'm trying to do is to use StringTokenizer to store strings from a file input into and object array.
In main, line 9 just initiates the object and the code is: Members members = new Members("users.txt");
Line 23 is class Members is: users[nm].setId(st.nextToken());
I can't figure out what the error is.
import java.io.*;
import java.util.*;
public class Members {
int nm = 0; //Number of members
User [] users = new User[100]; //Assuming max
number of user is 100
StringTokenizer st;
Scanner s1;
File f1;
String var1; //this string determines if it a standard or admin user;
String var2;
public Members(String fn) throws FileNotFoundException {
f1 = new File(fn);
s1 = new Scanner(f1);
while(s1.hasNext()) {
//System.out.println("true");
st = new StringTokenizer(s1.nextLine(),"/");
while(st.hasMoreTokens())
{
//System.out.print(((String)st.nextToken()));
users[nm].setId(st.nextToken());
users[nm].setPw(st.nextToken());
var1 = st.nextToken();
users[nm].setFn(st.nextToken());
users[nm].setLn(st.nextToken());
users[nm].setEmail(st.nextToken());
//System.out.print(st.nextToken() + " ");
if(var1.equals("Admin")) {
users[nm].setAdmin(true);
((Admin)users[nm]).setRank(st.nextToken());
}
if(var1.equals("Standard")) {
users[nm].setStandard(true);
while(st.hasMoreTokens())
{
((Standard)users[nm]).addCar(st.nextToken());
}
}
}
nm++;
System.out.println();
}
s1.close();
System.out.println("Number of members: " + nm);
}
You're creating an array that can hold Users, but as far as I can tell you aren't creating any instances of User. When you first try to reference users[nm] its value is going to be null.
You could do something like this:
users[nm] = new User();
users[nm].setId(st.nextToken());
The main culprit is User [] users = new User[100]; //Assuming max
This is creating a array of size 100 only. Not Creating any object. You are setting Id to a null object. Before setting the Id you have to initialize your user object.

String cannot be added to List using Object in Java

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.

Using Java need to create a hashmap that is populated with data from a file

I am trying to figure out a way to iterate through a file and generate a new hashset based on the first column. The value in the first column will server as the key in a hashmap. So for example, say I have a file that contains the following:
element1 value1
element1 value2
element1 value3
element2 value1
element2 value2
I need to have a hashmap with a key of element1 and values of value1 value2 and value3. The next key will be of element2 and values of value1 and value2. Use of the hashset of type User is required.
I can get through element1 and populate it fine. But when it gets to element2 I am not sure how to grab that information without erasing the entire hashset. Or what would be the best way to generate a new hashset dynamically as the values of the file are not static.
Of course any help will be appreciated.
`
public class User {
public T Username;
String key = null;
public HashSet<User> friends = new HashSet<User>();
public HashSet<User> temps = new HashSet<User>();
HashMap<String, HashSet<User>> map = new HashMap<String, HashSet<User>>();
public HashSet readFile(){
String temp = null;
try
{
File f = new File("file.txt");
Scanner input = new Scanner(f);
String line = null;
line = input.nextLine();
int count = 0;
while (input.hasNextLine()){
String parts[] = line.split("\t");
temp = parts[0];
if(!parts[0].equals(temp)){
friends.add(new User(parts[1]));
map.put(parts[0], friends);
//here I had friends.clear(); thinking to clear out
//the set and start to populate with the values
//of new hashset but it clears set for all keys.
}else if(parts[0].equals(temp)){
friends.add(new User(parts[1]));
map.put(temp, friends);
}
temp = parts[0];
line = input.nextLine();
}
}
catch (FileNotFoundException e){
System.out.println("File not found");
}
return friends;
}
public void setKey(String fKey){
key = fKey;
//return key;
}
public static void outputSet(HashSet<User> set){
Iterator<User> i = set.iterator();
while (i.hasNext()){
System.out.print(i.next() + " ");
}
System.out.println();
}
public void buildMap(String fKey, HashSet<User> mappy){
map.put(fKey, mappy);
System.out.println(map);
}
#Override
public String toString() {
return ("" + Username +"");
}
}
`
It looks like you want friends = new HashSet<User>(); instead of friends.clear() to create a new list. But this code is really messy, I suggest you head over to Code Review to get help with cleaning it.

How to convert String to ArrayList

I need your help about retreive data from mysql db. I cant add string to array list.
my list declare
ArrayList<HandleListReport> reportList = new ArrayList<HandleListReport>();
here my code
report_data = json.getJSONArray(TAG_REPORT_DATA);
for (int i = 0; i < report_data.length(); i++) {
//storing variable
JSONObject c = report_data.getJSONObject(i);
String reportID = c.getString(TAG_REPORT_ID);
String userID = c.getString(TAG_UID);
String projectName = c.getString(TAG_PROJECT_NAME);
String localWork = c.getString(TAG_LOCATION);
String timeStart = c.getString(TAG_TIME_START);
String timeEnd = c.getString(TAG_TIME_END);
Log.d(TAG_LOCATION, localWork);
// add data to Arraylist
reportList.add(new HandleListReport(reportID, userID, projectName, localWork, timeStart, timeEnd));
my problem my listReport missing string data. Logcat show reportList ---> []
thanks for answer!
create a list of string
List<String> list ......
list.add(String)
then list.toArray() method
http://docs.oracle.com/javase/6/docs/api/java/util/List.html#toArray(T[])
it seems you are trying to store object of HandleListReport in arraylist. In that case use the following to initiate
ArrayList<HandleListReport> reportList = new ArrayList<HandleListReport>();
It seems that the length of variable report_data is 0, so the element does not add the list.

Categories