I am trying to add a new element to an array list but when I print the structure I get the adress in memory. Any idea?
I read the information from a file and I try to put it in a structure Assignatures which is an in numAssignatures and one ArrayList and assignatura has an string with the name and one integer.
public static void llegeixFitxer(Curs[] curs) throws IOException {
FileReader file = new FileReader("assignatures.txt");
BufferedReader reader = new BufferedReader(file);
for (int j=0; j< 5; j++){
curs[j] = new Curs();
curs[j].numAssignatures = Integer.parseInt(reader.readLine());
for (int i = 0; i<curs[j].numAssignatures; i++){
String aux = reader.readLine();
String[] parts = aux.split("-");
String assignaturallegida = parts[0];
int creditsllegits = Integer.parseInt(parts[1].replace(" ",""));
curs[j].addAssignatura(assignaturallegida,creditsllegits);
}
System.out.println(curs[j].getNumAssignatures() + " + " + curs[j].getAssignatures());
}
reader.close();
}
}
I get this:
7 + [model.Assignatura#7eda2dbb, model.Assignatura#6576fe71, model.Assignatura#76fb509a, model.Assignatura#300ffa5d, model.Assignatura#1f17ae12, model.Assignatura#4d405ef7, model.Assignatura#6193b845]
Thank you!!
You have to override the toString() method in your model.Assignatura class.
The default implementation of toString() would print Fully Qualified class name followed by '#' and the object's hash code in hexadecimal format. That's explaining what you are receiving.
Related
Hi. I'm having the issue in an error of exception. I don't know what is wrong. But please help me fix this. I'm trying to store data from the file to ArrayList and display the data in the ArrayList. Here, I attached my code and data Code and data source.
the NoSuchElementException appears because you are calling input.nextToken(); while input doesn't have any token.It's due to the last empty line of your file listbook.txt. By deleting this line, the exception shouldn't appear.
A proper manner could be to ensure that you have sufficient tokens to retrieve all your fields for a given line.
public class TextFile
{
public static void main(String[] args)
{
try
{
FileReader read = new FileReader("C:\\Users\\ogawi\\Downloads\\listbook.txt");
BufferedReader bf = new BufferedReader(read);
Book B = new Book();
ArrayList<Book> bookList = new ArrayList<Book>();
String data = null;
StringTokenizer input = null;
while((data = bf.readLine()) != null)
{
input = new StringTokenizer(data,";");
//we ensure that we have enough tokens to retrieve all fields
if(input.countTokens() == 6)
{
String title = input.nextToken();
String author = input.nextToken();
String publisher = input.nextToken();
String genre = input.nextToken();
int year = Integer.parseInt(input.nextToken());
int page = Integer.parseInt(input.nextToken());
B = new Book(title, author, publisher, genre, year, page);
bookList.add(B);
}
}
//This part of code has been moved outside the while loop
//to avoid to print the total content of the array each time
//an element is added
int count=0;
for(int i=0;i<bookList.size();i++)
{
B = (Book)bookList.get(i);
System.out.println(B.toString());
System.out.println("=============================");
count++;
}
System.out.println("Number of Books: " + count);
bf.close();
}
catch(FileNotFoundException fnf)
{ System.out.println(fnf.getMessage());}
catch(EOFException eof)
{ System.out.println(eof.getMessage());}
catch(IOException io)
{ System.out.println(io.getMessage());}
finally
{ System.out.println("System end here..TQ!!");}
}
}
This issue is due to the extra line without book information:
You can see the line 31 and 32 in above figure.
To solve this issue you can add one if condition data.contains(";") . Text file has ; delimiter if we check the condition if given line has ; delimiter then it won't cause an issue.
while ((data = bf.readLine()) != null) {
if (data.contains(";")) {
input = new StringTokenizer(data, ";");
String title = input.nextToken();
String author = input.nextToken();
String publisher = input.nextToken();
String genre = input.nextToken();
int year = Integer.parseInt(input.nextToken());
int page = Integer.parseInt(input.nextToken());
B = new Book(title, author, publisher, genre, year, page);
bookList.add(B);
int count = 0;
for (int i = 0; i < bookList.size(); i++) {
B = (Book) bookList.get(i);
System.out.println(B.toString());
System.out.println("=============================");
count++;
}
System.out.println("Number of Books: " + count);
}
}
Here is the screenshot for successful execution of the code.
I am going through a project where I need to remove all java keywords from a java file. First I create a keyword.java file and store all java keywords into this file.Like abstract continue for new switch assert default goto package etc which I store keyword.java file. I have another file named newFile.java and I read all data from newFile.java as a String. I have to remove all java keywords from newFile.java file. As far I tried:
public void processFile() throws IOException {
String data = "";
data = new String(Files.readAllBytes(Paths.get("H:\\java\\Clone\\newFile.java"))).trim();
String rmvPunctuation = removePunctuation(data);
String newLineRemove = rmvPunctuation.replace("\n", "").replace("\r", "");
String spaceRemove = newLineRemove.replaceAll("( ){2,}", " ");
removeKeyword(spaceRemove);}
public void removeKeyword(String fileAsString) throws FileNotFoundException, IOException {
ArrayList<String> keyWordList = new ArrayList<>();
ArrayList<String> methodContentList = new ArrayList<>();
FileInputStream fis = new FileInputStream("H:\\java\\keyword.java");
byte[] b = new byte[fis.available()];
fis.read(b);
String[] keyword = new String(b).trim().split(" ");
String newString = "";
for (int i = 0; i < keyword.length; i++) {
keyWordList.add(keyword[i].trim());
}
String[] p = fileAsString.split(" ");
for (int i = 0; i < p.length; i++) {
if (!(keyWordList.contains(p[i].trim()))) {
newString = newString + p[i] + " ";
}
}
System.out.println("" + newString);
}
But I could not found my desired output. All the java keywords are not removed from newFile.java file. I think StackOverflow community help me to solve this. I am also a beginner.
I also tried:
public void removeKeyword(String fileAsString) throws IOException {
String keyWord = new String(Files.readAllBytes(Paths.get("H:\\java\\keyword.java"))).trim();
String text = fileAsString.trim();
ArrayList<String> wordList = new ArrayList<>();
ArrayList<String> keyWordList = new ArrayList<>();
wordList.addAll(Arrays.asList(text.split(" ")));
keyWordList.addAll(Arrays.asList(keyWord.split(" ")));
wordList.removeAll(keyWordList);
System.out.println("" + wordList.toString());
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
I have an array of call records and I want to store the ones that have a call disposition of "DNC" in a different array. The function opens a csv file and reads the entire file into an array of objects and sets the attributes. The original array contains 680 object records. I have an if statement after the my object setters that says if userArray[count].getDisposition == "DNC" then add this records to my new array DNC_List[dnc_count] and increment dnc_count++.
dnc_count is initialized to 0 and at the end of the process, it is still 0. There are 4 records in my original array that have "DNC" as an attribute. Can anyone tell me what is wrong with my code and why it is not recognizing when disposition is DNC?
public static void myCSVReader(String filename) {
String path = "C:\\Users\\My_Username\\Downloads\\" + filename;
file_path = path;
BufferedReader reader = null;
String line = "";
String csvSplitBy = ",";
int count = 0;
String fullName, U_ID;
int dnc_count = 0;
User userArray[] = new User[1000];
User[] DNC_List = new User[1000];
System.out.println("Starting csv reader");
try {
reader = new BufferedReader(new FileReader(path));
while ((line = reader.readLine()) != null) {
String[] s = line.split(csvSplitBy);
fullName = s[13] + " " + s[15];
U_ID = s[44];
userArray[count] = new User(s[1], s[2], s[0], fullName, U_ID);
userArray[count].setDisposition(s[2]);
userArray[count].setNumber(s[1]);
userArray[count].setName(fullName);
userArray[count].setID(U_ID);
if(userArray[count].getDisposition() == "DNC" || userArray[count].getDisposition() == "CS"){
DNC_List[dnc_count].setKey(String.valueOf(dnc_count));
DNC_List[dnc_count].setDisposition("DNC");
DNC_List[dnc_count].setName(userArray[dnc_count].getName());
DNC_List[dnc_count].setID(userArray[dnc_count].getID());
dnc_count++;
}
count++;
User user = new User(s[1], s[2], s[0], fullName, U_ID);
user.setDisposition(s[2]);
user.setNumber(s[1]);
user.setName(fullName);
user.setID(U_ID);
}
} catch (Exception e) {
e.printStackTrace();
}
// Prints out the array index, name, disposition, and phone_number
System.out.println("\n\nUser array: \n");
for (int i = 0; i < userArray.length; i++) {
if (userArray[i] != null) {
System.out.println(i + ": " + userArray[i].getName() + "\t | Dispo = " + userArray[i].getDisposition()
+ "\t | Phone = " + userArray[i].getNumber());
}
}
System.out.println("\nDNC_COUNT = " + dnc_count);
for (int i = 0; i < dnc_count; i++) {
System.out.println(DNC_List[i] + "\n");
}
}
The value of the string object can't be compared using '==' operator and should use the equals() method.
Change your comparison to use equals method of String class.
Use
userArray[count].getDisposition().equals("DNC") "CS"
instead of
userArray[count].getDisposition() == "DNC"
Try with equals() method instead of ==
public class Main {
public static void main(String[] args) {
String a = "DNC";
String b = new String("DNC");
System.out.println(a == b);
System.out.println(a.equals(b));
}
}
Output:
false
true
How can I count the number of cities per country from the data file? I would also like to display the value as percentage of the total.
import java.util.StringTokenizer;
import java.io.*;
public class city
{
public static void main(String[] args)
{
String[] city = new String[120];
String country = null;
String[] latDegree =new String[120];
String lonDegree =null;
String latMinute =null;
String lonMinute =null;
String latDir = null;
String lonDir = null;
String time = null;
String amORpm = null;
try
{
File myFile = new File("CityLongandLat.txt");
FileReader fr = new FileReader(myFile);
BufferedReader br = new BufferedReader(fr);
String line = null;
int position =0;
int latitude=0;
while( (line = br.readLine()) != null)
{
// System.out.println(line);
StringTokenizer st = new StringTokenizer(line,",");
while(st.hasMoreTokens())
{
city[position] = st.nextToken();
country = st.nextToken();
latDegree[latitude] =st.nextToken();
latMinute =st.nextToken();
latDir = st.nextToken();
lonDegree =st.nextToken();
lonMinute =st.nextToken();
lonDir = st.nextToken();
time = st.nextToken();
amORpm = st.nextToken();
}
if(city.length<8)
{
System.out.print(city[position] + "\t\t");
}
else
{
System.out.print(city[position] + "\t");
}
if(country.length()<16)
{
System.out.print(country +"\t\t");
}
else
{
System.out.print(country);
}
System.out.print(latDegree + "\t");
System.out.print(latMinute + "\t");
System.out.print(latDir + "\t");
System.out.print(lonDegree + "\t");
System.out.print(lonMinute + "\t");
System.out.print(lonDir + "\t");
System.out.print(time + "\t");
System.out.println(amORpm + "\t");
position++;
}
br.close();
}
catch(Exception ex)
{
System.out.println("Error !!!");
}
}
}
One easy way that comes to my mind would be as follows...
Create a hashMap Object where the key is a string (the country) and the value is an integer (number of cities found for the country) so it would be something like
Map countryResultsFoundMap = new HashMap< String,Integer>();
In short, for each row you would pick the country, (I would recommend that you .trim() and .toLowerCase() the value first) and check if it is existing in the hashMap, if not, add the entry like countryResultsFoundMap.put(country,0), otherwise, if the country already exists the pick the value from the hashMAp and add +1 to its integer value.
Eventually you will have all the values stored in the map and you can have access to that data for your calculations.
Hope that helps
"here are some of the output from the data file from my programme"
Aberdeen Scotland 57 2 [Ljava.lang.String;#33906773 9 N [Ljava.lang.String;#4d77c977 9 W 05:00 p.m. Adelaide Australia 34 138 [Ljava.lang.String;#33906773 55 S [Ljava.lang.String;#4d77c977 36 E 02:30 a.m...
The reason why your getting that output, is because you're trying to print the array object latDegree.
String[] latDegree
...
System.out.print(latDegree + "\t");
Also, you have lattitude = 0; but you never increment it, so it will always use the index 0 for the array. You need to increment it, like you did position++.
So for the print statement, print the print the value at index lattitude, not the entire array
Try this
System.out.print(latDegree[lattitude] + "\t");
...
lattitude++;
If for some reason you do want to print the array, then use Arrays.toString(array); or just iterate through it
I would also start with a map, and group the cities by country with a map.
Map<String,<List<String>>
Where the key is the country and the value is the list of cities in this country. With the size() methods you can perform the operations cities per country and percentage of total.
When you read one line you check if the key (country) already exists, if not you create a new list and add the city, otherwise add the city only to the existing list.
As a starter you could use the following snippet. However this sample assumes that the content of the file is read already and given as an argument to the method.
Map<String,List<String>> groupByCountry(List<String> lines){
Map<String,List<String>> group = new HashMap<>();
for (String line : lines) {
String[] tokens = line.split(",");
String city = tokens[0];
String country = tokens[1];
...
if(group.containsKey(country)){
group.get(country).add(city);
}else{
List<String> cities = new ArrayList<>();
cities.add(city);
group.put(country, cities);
}
}
return group;
}
I have this code in Java. The randomName() function returns a string with (unsurprisingly) a random string.
File handle = new File(file);
String parent = handle.getParent();
String lastName = "";
for (int i = 0; i < 14; i++)
{
lastName = parent + File.separator + randomName();
handle.renameTo(new File(lastName));
}
return lastName;
I have the appropriate permissions, and when I log to logcat the randomName() function does all the strings, but upon the end of the loop handle appears to have a file name of the value of the first randomName() call.
The reason this didn't work as expected is because once the file was renamed the first time, handle no longer referred to the file. That is why the subsequent rename operations failed. File represents a path name, not an actual object on disk.
This is my solution:
File handle = null;
String parent = "";
String lastName = "";
for (int i = 0; i < 14; i++)
{
if (i == 0)
{
handle = new File(file);
parent = handle.getParent();
}
else
{
lastName = parent + File.separator + randomName();
handle.renameTo(new File(lastName));
handle = new File(lastName);
}
}