adding value on treeset - java

ı read text. my text is like that
AYSE;SERDAR-9.8;EMRE-5.2;AYTAC-3.3
FATMA;OYTUN-8.8;ORKUN-7.5;ONUR-5.4;UMUT-4.4;BERK-3.3;CAN-3.2
DERYA;VELI-7.7;ALI-6.5;SUAT-6.0;YAVUZ-5.0;OYTUN-4.2;ORKUN-3.1
DILARA;DOGUS-8.8;VELI-7.4;ALI-6.5;SUAT-5.5;YAVUZ-3.1
BEGUM;SUAT-6.6;YAVUZ-5.1;OYTUN-4.3;ORKUN-4.0
BERIL;CANER-8.7;DOGUS-7.5;VELI-6.2;ALI-6.1;SUAT-5.8;YAVUZ-4.8;OYTUN-4.0
FUNDA;ORKUN-9.7;ONUR-8.3;UMUT-7.2;BERK-6.5;CAN-5.5
ISIL;AYTAC-8.3;CANER-7.4;DOGUS-6.5;VELI-5.5;ALI-5.4;SUAT-4.4;YAVUZ-4.0;OYTUN-3.9;ORKUN-3.5;ONUR-3.4;UMUT-3.2;BERK-3.1;CAN-3.0
ELIF;EMRE-7.4;AYTAC-6.1
ı cant add "u.eleman" and "u.uyum" values to "treeset tSU". it gives memory address when ı do syso ı cant see them in the tSU TREESET. I want to add all of them to treeset. How can ı do that.. please help
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.TreeSet;
public class Rapor {
static class Uyum implements Comparable<Uyum> {
String eleman;
Double uyum;
public int compareTo(Uyum u) {
if (uyum < u.uyum)
return -1;
if (uyum > u.uyum)
return 1;
return 0;
}
}
public static void main(String[] args) {
FileInputStream fIS;
try {
fIS = new FileInputStream("C:\\deneme\\rapor.txt");
Reader r;
r = new InputStreamReader(fIS, "UTF-8");
BufferedReader bR = new BufferedReader(r);
String satır;
String[] point, p2;
while ((satır = bR.readLine()) != null) {
point = satır.split(";");
String kelime = point[0];
HashMap<String, TreeSet<Uyum>> uyumlar = new HashMap<String, TreeSet<Uyum>>();
TreeSet<Uyum> tSU = new TreeSet<Uyum>() ;
Uyum u ;
for (int i = 1; i < point.length; i++) {
p2=point[i].split("\\-");
u = new Uyum();
u.eleman = p2[0];//EMRE,AYTAC,..
u.uyum = Double.parseDouble(p2
[1]);//7.8,9.5
tSU.add(u);
}
uyumlar.put(kelime, tSU);
System.out.println(uyumlar);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}// main end
}// class end

it gives memory address when ı do syso ı cant see them in the tSU TREESET.
No, it does not print the memory address. It prints the class name, an # and the hash code for the object in hexadecimal - that's what Object.toString() does by default.
If you want your Uyum objects to be printed differently, then override the toString() method in your class Uyum.

Related

Could it not delete the entire file content while saving into file? Java [duplicate]

This question already has answers here:
PrintWriter append method not appending
(5 answers)
Closed 4 years ago.
I've recently made a Snake game with function that allows to store and find the best score of his. But unfortunetely it every time it saves your score into file, it deletes the previous file content. Is there any way to avoid that? As it is visible in the code below, I've made 3 methods. The first one is to save your score into a file. Last ones are to find the best score.
package matajus.snake;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Score {
private File file;
public static int score;
private static final String fileName = "BestScores.txt";
public Score() {
file = new File(fileName);
if(!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void saveToFile() throws FileNotFoundException {
PrintWriter print = new PrintWriter(fileName);
print.println(score);
print.close();
}
public int findBestScore() {
List<Integer> lines = new ArrayList<Integer>();
Scanner input;
int bestScore = 0;
try {
input = new Scanner(file);
if(linesNumber() > 0) {
for(int i = 0; i < linesNumber(); i++) {
String readLine = input.nextLine();
int line = Integer.parseInt(readLine);
lines.add(line);
}
bestScore = Collections.max(lines);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bestScore;
}
private int linesNumber() throws FileNotFoundException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
int lines = 0;
try {
while((line = reader.readLine()) != null) {
lines++;
}
} catch (Exception e) {
e.printStackTrace();
}
return lines;
}
}
PrintWritter will truncate the file: https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#PrintWriter(java.lang.String)
Have a look at the proposed solution here: How to append text to an existing file in Java

Sending a file line by line, in 2 seconds intervals, using ticker behaviours

My question is: How to send a line of a file to another agent every 2 seconds using ticker behaviours?
More specifically, in the first iteration, the agent sends the first line. In the second, the agent sends the second line etc.
My code below:
package pack1;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.TickerBehaviour;
import jade.lang.acl.ACLMessage;
import jade.wrapper.ControllerException;
public class Agent2 extends Agent {
private static final long serialVersionUID = 1L;
int nombre_ligne = 0;
BufferedReader lecteurAvecBuffer = null;
#Override
protected void setup() {
FileInputStream fis;
try {
fis = new FileInputStream("/home/hduser/Bureau/word.txt");
#SuppressWarnings("resource")
LineNumberReader l = new LineNumberReader(new BufferedReader(
new InputStreamReader(fis)));
while ((l.readLine()) != null) {
nombre_ligne = l.getLineNumber();
}
lecteurAvecBuffer = new BufferedReader(new FileReader(
"/home/hduser/Bureau/esclave1/abc.txt"));
int a = 1;
while (a <= ((int) nombre_ligne) / 3) {
a++;
String word = lecteurAvecBuffer.readLine();
addBehaviour(new TickerBehaviour(this, 2000) {
private static final long serialVersionUID = 1L;
#Override
protected void onTick() {
ACLMessage message = new ACLMessage(ACLMessage.INFORM);
message.addReceiver(new AID("agent1", AID.ISLOCALNAME));
message.setContent(word);
send(message);
}
});
a++;
}
lecteurAvecBuffer.close();
} catch (FileNotFoundException exc) {
System.out.println("Erreur d'ouverture");
} catch (IOException e) {
e.printStackTrace();
}
}
protected void takeDown() {
System.out.println("Destruction de l'agent");
}
#Override
protected void afterMove() {
try {
System.out.println(" La Destination : "
+ this.getContainerController().getContainerName());
} catch (ControllerException e) {
e.printStackTrace();
}
}
}
You don't say nothing about what is the problem with your code. I guess you get at least a compiler message about:
message.setContent(word);
As you access a local variable from an inner class, you must declare the variable as final in the context, like:
final String word = lecteurAvecBuffer.readLine();

Reading numbers from a file and creating an array (java)

I cannot figure out how to make this txt file with numbers into an array, I am able to get it to read and print the screen but I need to be able to organize the numbers and delete the duplicates. This is what my code looks like so far
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class File {
public static void main(String[] args) {
String filename = "C:/input.txt";
File rfe = new File();
rfe.readFile(filename);
}
private void readFile(String name) {
String input;
try (BufferedReader reader = new BufferedReader(new FileReader(name))) {
while((input = reader.readLine()) != null) {
System.out.format(input); // Display the line on the monitor
}
}
catch(FileNotFoundException fnfe) {
}
catch(IOException ioe) {
}
catch(Exception ex) { // Not required, but a good practice
}
}
}
I would recommend using an ArrayList rather than an Array.
With an array you would have to parse through the list and calculate the line count before you could even initialize it. An ArrayList is much more flexible as you don't have to declare how many values will be added to it.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class File {
private List<Integer> data = new ArrayList<Integer>(); //Create ArrayList
public static void main(String[] args) {
String filename = "C:/input.txt";
File rfe = new File();
rfe.readFile(filename);
}
private void readFile(String name) {
String input;
try (BufferedReader reader = new BufferedReader(new FileReader(name))) {
while((input = reader.readLine()) != null) {
data.add(Integer.parseInt(input));//Add each parsed number to the arraylist
System.out.println(input); // Display the line on the monitor
}
}
catch(FileNotFoundException fnfe) {
}
catch(IOException ioe) {
}
catch(Exception ex) { // Not required, but a good practice
ex.printstacktrace(); //Usually good for general handling
}
}
}

null pointer exception in reading tsv file

hi can anybody help me with below code. why this is throwing null pointer exception and how i can avoid it.
i am trying to read a tsv file and csv file and do some processing with this.
when i am calling getDictionaryValues function it throwing null pointer exception.
package com.ugam.qa.tittle;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class TittleMatch {
private static TittleMatchUtil tMU;
public static void main(String[] args) {
String fullname="d:/files/listing/Headphones.tsv";
Set<String> attributeSet=new HashSet<String>();
attributeSet.add("Storage Type");
attributeSet.add("Recording Definition");
attributeSet.add("Type");
attributeSet.add("Brand");
BufferedReader in = null;
try
{
System.out.println("file found");
in= new BufferedReader(new FileReader(fullname));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
String str;
String prv_Pid="-1";
try {
str = in.readLine();
while ((str = in.readLine()) != null) {
if (str.trim().length() == 0 ) {
System.out.println("while loop");
continue;}
String[] values = str.split("\\t");
//System.out.println(values.length);
if(prv_Pid=="-1" || values[9]==prv_Pid)
{
if(attributeSet.contains(values[12]))
{
ArrayList<Set<String>> dicValues=new ArrayList<Set<String>>();
if(values[12]!=null && values[13]!=null)
{
dicValues=tMU.getDictionaryValues(values[12],values[13]);
}
//Set<String> tittle=new HashSet<String>();
//tittle.add(values[8]);
//System.out.println(tittle);
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Obviously this variable is evaluated to null, since you never assign a value to it.
private static TittleMatchUtil tMU;
One solution would be assigning a new TittleMatchUtil object to the variable:
private static TittleMatchUtil tMU = new TittleMatchUtil();
and another one is to make the getDictionaryValues() method static, which I wouldn't do, because it may require more code re-factoring.

Correct syntax for inputing a String file into a 2D Array?

What is the correct syntax for creating a 2D array from a text file? This array must be string not char or int. None of the information I've found on this is for string, and I haven't been able to figure the exact syntax out myself.
You can use ArrayList object .Its internal implemetation is Resizable or growable array.
So you can achieve your requirement by ArrayList<String>.You can get even arry by using its utility methods.
For more details ArrayList docs
For sample click here
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Read2DimensionFileToList {
public static void main(String[] args) {
String [][] sList=new String[100][2];
BufferedReader br = null;
try {
String s;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
int i=0;
while ((s = br.readLine()) != null) {
String []sArray=s.split(",");
sList[i++][0]=sArray[0];
sList[i][1]=sArray[1];
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}

Categories