Jumping pair lines using .readLine() method at a while loop - java

I am new at Java and I am having a little trouble:
I am trying to read chemical samples to represent them at a X-Y graph.
The input file looks like this:
La 0.85678
Ce 0.473
Pr 62.839
...
...
My code stocks only the unpair lines value (0.85678, jumps line, 62.839 at the example), and I cannot realize what is the problem:
public class Procces {
public void readREE() throws IOException {
try{
rEE = new BufferedReader (new FileReader ("src/files/test.txt"));
while ( (currentLine = rEE.readLine() ) != null) {
try {
for (int size = 3;size<10;size++) {
String valueDec=(currentLine.substring(3,size));
//char letra =(char)c;
if ((c=rEE.read()) != -1) {
System.out.println("Max size");
} else
valueD = Double.parseDouble(valueDec);
System.out.println(valueDec);
}
}
catch (Exception excUncertainDecimals) {
}
}
}finally {
try { rEE.close();
} catch (Exception exc) {
}
}
}
String line;
int c = 0;
int counter = 0;
String valueS = null;
String valueSimb = null;
Double valueD = null;
Double logValue = null;
Double YFin=450.0;
String currentLine;
BufferedReader rEE;
}
Thank you in advance, as I can't see why the program jumps the pair lines.

use Java Scanner class.
import java.io.*;
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) throws IOException {
try (Scanner s = new Scanner(new BufferedReader(new FileReader("file.txt"))){
while (s.hasNext()) {
System.out.println(s.next());
}
}
}
}

Please have a look at Scanner.
In general is Java a well established language and in most cases you do not have to re-implemented "common" (e.g. reading custom text files) stuff on a low level way.

I get it. Thank you.
Here the code:
import java.io.*
import java.util.Scanner;
public class Process implements Samples{
public void readREE() throws IOException {
try
(Scanner rEE = new Scanner(new BufferedReader(new FileReader("src/files/test.txt")))){
while (rEE.hasNext()) {
element = rEE.next();
if (element.equals("La")) {
String elementValue = rEE.next();
Double value = Double.parseDouble(elementValue);
Double valueChond = 0.237;
Double valueNorm= value/valueChond;
Double logValue = (Math.log(valueNorm)/Math.log(10));
Double yLog = yOrd - logValue*133.33333333;
Sample NormedSampleLa=new Sample("La",yLog);
sampleREE.add(NormedSampleLa);
}
}
} finally {
}
}
public String LaS, CeS, PrS, NdS, PmS, SmS, EuS, GdS, TbS, DyS, HoS, ErS, TmS, YbS, LuS;
public String element, elementValue;
public Double yOrd=450.0;
}

Related

Sentiment Analysis with OpenNLP on a text file

I have 100 sentences of test data. I am trying to run sentiment analysis on them but no matter what input String I am using, I am only getting a positive estimation of the input string. Each sentence gets a return value of 1.0. Any idea why this might be happening? Even if I use negative example inputs from the .txt file, the result is a positive value.
public class StartSentiment
{
public static DoccatModel model = null;
public static String[] analyzedTexts = {"Good win"};
public static void main(String[] args) throws IOException {
// begin of sentiment analysis
trainModel();
for(int i=0; i<analyzedTexts.length;i++){
classifyNewText(analyzedTexts[i]);}
}
private static String readFile(String pathname) throws IOException {
File file = new File(pathname);
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner = new Scanner(file);
String lineSeparator = System.getProperty("line.separator");
try {
while(scanner.hasNextLine()) {
fileContents.append(scanner.nextLine() + lineSeparator);
}
return fileContents.toString();
} finally {
scanner.close();
}
}
public static void trainModel() {
MarkableFileInputStreamFactory dataIn = null;
try {
dataIn = new MarkableFileInputStreamFactory(
new File("src\\sentiment\\Results.txt"));
ObjectStream<String> lineStream = null;
lineStream = new PlainTextByLineStream(dataIn, StandardCharsets.UTF_8);
ObjectStream<DocumentSample> sampleStream = new DocumentSampleStream(lineStream);
TrainingParameters tp = new TrainingParameters();
tp.put(TrainingParameters.CUTOFF_PARAM, "1");
tp.put(TrainingParameters.ITERATIONS_PARAM, "100");
DoccatFactory df = new DoccatFactory();
model = DocumentCategorizerME.train("en", sampleStream, tp, df);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dataIn != null) {
try {
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
public static void classifyNewText(String text) throws IOException{
DocumentCategorizerME myCategorizer = new DocumentCategorizerME(model);
double[] outcomes = myCategorizer.categorize(text.split(" ") );
String category = myCategorizer.getBestCategory(outcomes);
if (category.equalsIgnoreCase("1")){
System.out.print("The text is positive");
} else {
System.out.print("The text is negative");
}
}

Read data that has an integer and string in a text file - Java

I have read the file and it should print out the data on the console, but the problem is that I get this error message: Exception in thread "main" java.lang.NumberFormatException: For input string: "UNKNOWN". I've put the maximum length as an integer, but how do I put it as a string as well?
Here's what I have done so far:
import java.util.*;
import java.io.*;
public class Task1 {
public static void main(String[] args) {
List<Person> personFile = new ArrayList<>();
try {
BufferedReader br = new BufferedReader(new FileReader("people-data.txt"));
String fileRead = br.readLine();
while (fileRead != null) {
String[] peopleData = fileRead.split(":");
String commonName = personData[0];
String latinName = personData[1];
int maximumLength = Integer.parseInt(personData[2]);
Person personObj = new Person(commonName, latinName, maximumLength);
personFile.add(personObj);
fileRead = br.readLine();
}
br.close();
}
catch (FileNotFoundException ex) {
System.out.println("File not found!");
}
catch (IOException ex) {
System.out.println("An error has occured: " + ex.getMessage());
}
System.out.println(personFile);
}
}
Person Class:
import java.util.*;
public class Person1 {
private String commonName;
private String latinName;
private int maximumLength;
public Person1(String personName, String latinName, int maximumLength) {
this.commonName = personName;
this.latinName = latinName;
this.maximumLength = maximumLength;
}
public String getCommonName() {
return commonName;
}
public String getLatinName() {
return latinName;
}
public int getMaximumLength() {
return maximumLength;
}
#Override
public String toString() {
return null;
}
}
Text File:
Alisha Khan:Cephaloscyllium ventriosum:100
Jessica Lane:Galeocerdo cuvier:UNKNOWN
Michael Brown:Sphyrna mokarren:600
...
This line in your input file:
Jessica Lane:Galeocerdo cuvier:UNKNOWN
is causing problem on this line in your code:
int maximumLength = Integer.parseInt(personData[2]);
because parseInt throws NumberFormatException on UNKNOWN. You need to decide what you want to do in this case. For example this code will keep maximumLength to default value -1 when an invalid integer is encountered:
int maximumLength = -1;
try {
int maximumLength = Integer.parseInt(personData[2]);
} catch (NumberFormatException e) {
}
You should teach your code your convention of UNKNOWN. Currently the code treats it as number.

Compare one Array List object with the next one

Hello guys here my Code
public class Main {
public static List<String> globalList;
public static void main(String[] args) {
globalList = new ArrayList<String>();
File folder = new File("\\Documents\\Folder);
File[] listOfFiles = folder.listFiles();
for(File file : listOfFiles) {
dosomething(file);
}
for( String t : globalList)
{
System.out.println(t);
}
}
public static void dosomething(File file) {
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String str;
while ((str = in.readLine()) != null) {
globalList.add(str);
}
in.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
In my folder i have a few files. Every file contains a line of information so i took every line and saved the lines to my Arraylist globalList. Now i want to compare one object in my ArrayList with the next one, is this possible?
Just like: if (firstobj == nextobj) remove it.
Edit
Sorry guys i forgot something to write....
The problem is, the line i need to delete arent completly the same, because they start with ah generated number, this number is important for those files so i cant just delete it...
So i need to compare one part of my line if its the same i need to remove it.
One example:
10133;1;XXXX 110;4100;Autotour 4M100;30;0;K;0;;;0;2;3;XXXX
10134;1;XXXX 110;4100;Autotour 4M100;30;0;K;0;;;0;2;3;XXXX
10135;1;XXXX 110;4100;Autotour 4M100;15;0;K;0;;;0;2;3;XXXX
So now you see the first 2 lines are almost the same except the starting number, i need to find those lines and delete them. Because of changes i cant do somthing like if(list.contains("10135;1;XXXX 110;4100;Autotour 4M100;15;0;K;0;;;0;2;3;XXXX") ).
In your case if you don't want to check if the part string contains in the list every time then it will take hours if you have a hugefile instead you can use a Set which does not allow duplicates. Unique feature of set is that it does not allow duplicates so instead of taking list of string wrap the string in a custom class and then override the equals and hashcode implementation of the class so that it will not consider the the part of string until the first occurrence of semicolon in the string.
Finally found the working code..
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
public class MyString
{
public static Set<MyString> globalSet;
private String line;
public String getLine(){
return this.line;
}
public void setLine(String newLine){
this.line = newLine;
}
public static void main(String[] args) {
File folder = new File("C:\\Users\\hbm5cf7\\Documents\\NewF");
globalSet = new HashSet<MyString>();
File[] listOfFiles = folder.listFiles();
for(File file : listOfFiles) {
dosomething(file);
}
for(MyString t : globalSet)
{
System.out.println(t.getLine());
}
}
public static void dosomething(File file)
{
try {
BufferedReader in = new BufferedReader(new FileReader(file));
MyString str;
String line;
while ((line = in.readLine()) != null) {
str = new MyString();
str.setLine(line);
globalSet.add(str);
}
in.close();
}catch(IOException e)
{
System.out.println(e);
}
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((line == null) ? 0 : line.split(";", 2)[1].hashCode());
return result;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (getClass() != obj.getClass())
{
return false;
}
if (this.line.equals(((MyString) obj).getLine()))
{
return true;
}
String splitString = ((MyString) obj).getLine().split(";", 2)[1];
if(this.line.endsWith(splitString))
{
return true;
}
return false;
}
}
by overriding the equals and hashcode methods you can decide which one is duplicate and which is not depending upon your requirement
Yes, it's possible. You can use equals method to compare the lines. However, you should rather compare the lines while reading the files and not store the file content in a list and compare. E.g.:
try(BufferedReader reader1 = new BufferedReader(new FileReader(file1));
BufferedReader reader2 = new BufferedReader(new FileReader(file2));){
String line1 = reader1.readLine();
String line2 = reader2.readLine();
if(line1 != null && line1.equals(line2)){
//Do something
}
}catch(Exception e){
//Exception handling
}
I think you're simply trying to ensure that you end up with a single list containing every 'unique' line from every file.
If this is the case you could use an implementation of Set (https://docs.oracle.com/javase/7/docs/api/java/util/Set.html) in place of your globaList such as HashSet https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html
The set implementation will ensure that no duplicates are added.
I think you are looking for something like this
Iterator<String> iterator = globalList.iterator();
String lastObj = null;
String nextObj = null;
while (iterator.hasNext()){
nextObj = iterator.next();
if(lastObj == null ){
lastObj = nextObj;
}
else {
if(lastObj.equals(nextObj)){
iterator.remove();
}
}
}
EDIT:
If you have the same generated number followed by an escape character like semicolon you can get the index of the first semicolon and get the substring that start from the next character:
public static void dosomething(File file) {
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String str;
while ((str = in.readLine()) != null) {
globalList.add(str);
String subString = str.substring(str.indexOf(";") + 1, str.length());
for(Iterator<String> iter = globalList.iterator(); iter.hasNext();)
{
String elem = (String) iter.next();
if(elem.contains(subString))
iter.remove();
}
}
}
in.close();
} catch (IOException e) {
System.out.println(e);
}
}
Another version:
public static void dosomething(File file) {
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String str;
while ((str = in.readLine()) != null) {
// remove spaces from beginning and end of the input string
str = str.trim();
String subString = str.substring(str.indexOf(";") + 1, str.length());
boolean match = false;
// search in globalList for a match
for(String elem : globalList)
{
if(elem.contains(subString)){
match = true;
break;
}
}
// if it doesn't contain the string add it
if(!match)
globalList.add(str);
}
in.close();
} catch (IOException e) {
System.out.println(e);
}
}
#Harish Barma
Files Content:
File1:
2;XXXX;XXXX;;P;XX;XXX;1N410;20170719;1;;;0;0;1;999;1;1;;
10000;1;XXXX 096;1410;Autotour 1N410;15;0;K;0;;;0;2;;XXXX
10001;2;XXXX 097;1410;Autotour 1N410;10;0;K;0;;;0;2;;XXXX
10002;3;XXXX 098;1410;Autotour 1N410;13;0;K;0;;;0;2;;XXXX
10003;4;XXXX 099;1410;Autotour 1N410;19;0;K;0;;;0;2;;XXXX
10004;5;XXXX 100;1410;Autotour 1N410;15;0;K;0;;;0;2;;XXXX
File2:
2;XXXX;XXXX;;P;XX;XXXX;3A680;20170726;1;;;0;0;1;999;1;1;;
10082;1;XXX S146;3680;Autotour 3A680;5;0;K;0;;;0;2;;XXXx
10083;2;XXX S147;3680;Autotour 3A680;8;0;K;0;;;0;2;;XXXX
10084;3;XXX 095;3680;Autotour 3A680;6;0;K;0;;;0;2;3;XXXX
File3:
2;XXXX;XXXX;;P;XX;XXX;4M100;20170719;1;;;0;0;1;999;1;1;;
10129;1;XXXX 110;4100;Autotour 4M100;30;0;K;0;;;0;2;3;XXXX
10130;1;XXXX 110;4100;Autotour 4M100;30;0;K;0;;;0;2;3;XXXX
10131;1;XXXX 110;4100;Autotour 4M100;30;0;K;0;;;0;2;3;XXXX
10132;1;XXXX 110;4100;Autotour 4M100;30;0;K;0;;;0;2;3;XXXX
10133;1;XXXX 110;4100;Autotour 4M100;30;0;K;0;;;0;2;3;XXXX
10134;1;XXXX 110;4100;Autotour 4M100;30;0;K;0;;;0;2;3;XXXX
10135;1;XXXX 110;4100;Autotour 4M100;15;0;K;0;;;0;2;3;XXXX
(File 5-100 can cointain same lines like file 3 or different lines like file 1 or 2.)
Code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class MyString
{
public static Set<MyString> globalSet;
private String line;
public String getLine(){
return this.line;
}
public void setLine(String newLine){
this.line = newLine;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (getClass() != obj.getClass())
{
return false;
}
if (this.line.equals(((MyString) obj).getLine())) //compiler said i need to do this so...
{
return true;
}
String splitString = ((MyString) obj).getLine().split(";", 2)[1]; //compiler said i need to do this so...
if(this.line.endsWith(splitString))
{
return true;
}
return false;
}
public static void main(String[] args) {
File folder = new File("C:\\Users\\V90xxxxPCN\\Documents\\Neuer Ordner");
File[] listOfFiles = folder.listFiles();
for(File file : listOfFiles) {
dosomething(file);
}
for(MyString t : globalSet)
{
System.out.println(t.getLine());
}
}
public static void dosomething(File file)
{
try {
globalSet = new HashSet<MyString>();
BufferedReader in = new BufferedReader(new FileReader(file));
MyString str = new MyString();
String line;
while ((line = in.readLine()) != null) {
str.setLine(line);
globalSet.add(str);
}
}catch(IOException e)
{
System.out.println(e);
}
}
}
Expected Output:
2;XXXX;XXXX;;P;XX;XXX;1N410;20170719;1;;;0;0;1;999;1;1;;
10000;1;XXXX 096;1410;Autotour 1N410;15;0;K;0;;;0;2;;XXXX
10001;2;XXXX 097;1410;Autotour 1N410;10;0;K;0;;;0;2;;XXXX
10002;3;XXXX 098;1410;Autotour 1N410;13;0;K;0;;;0;2;;XXXX
10003;4;XXXX 099;1410;Autotour 1N410;19;0;K;0;;;0;2;;XXXX
10004;5;XXXX 100;1410;Autotour 1N410;15;0;K;0;;;0;2;;XXXX
2;XXXX;XXXX;;P;XX;XXXX;3A680;20170726;1;;;0;0;1;999;1;1;;
10082;1;XXX S146;3680;Autotour 3A680;5;0;K;0;;;0;2;;XXXx
10083;2;XXX S147;3680;Autotour 3A680;8;0;K;0;;;0;2;;XXXX
10084;3;XXX 095;3680;Autotour 3A680;6;0;K;0;;;0;2;3;XXXX
2;XXXX;XXXX;;P;XX;XXX;4M100;20170719;1;;;0;0;1;999;1;1;;
10135;1;XXXX 110;4100;Autotour 4M100;15;0;K;0;;;0;2;3;XXXX
Output:
10135;1;XXXX 110;4100;Autotour 4M100;15;0;K;0;;;0;2;3;XXXX

Output issues: Passing from BufferedReader to array method

I've compiled and debugged my program, but there is no output. I suspect an issue passing from BufferedReader to the array method, but I'm not good enough with java to know what it is or how to fix it... Please help! :)
public class Viennaproj {
private String[] names;
private int longth;
//private String [] output;
public Viennaproj(int length, String line) throws IOException
{
this.longth = length;
this.names = new String[length];
String file = "names.txt";
processFile("names.txt",5);
sortNames();
}
public void processFile (String file, int x) throws IOException, FileNotFoundException{
BufferedReader reader = null;
try {
//File file = new File("names.txt");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void sortNames()
{
int counter = 0;
int[] lengths = new int[longth];
for( String name : names)
{
lengths[counter] = name.length();
counter++;
}
for (int k = 0; k<longth; k++)
{
int counter2 = k+1;
while (lengths[counter2]<lengths[k]){
String temp2;
int temp;
temp = lengths[counter2];
temp2 = names[counter2];
lengths[counter2] = lengths[k];
names[counter2] = names[k];
lengths[k] = temp;
names[k] = temp2;
counter2++;
}
}
}
public String toString()
{
String output = new String();
for(String name: names)
{
output = name + "/n" + output;
}
return output;
}
public static void main(String[] args)
{
String output = new String ();
output= output.toString();
System.out.println(output+"");
}
}
In Java, the public static void main(String[] args) method is the starting point of the application.
You should create an object of Viennaproj in your main method. Looking at your implementation, just creating an object of Viennaproj will fix your code.
Your main method should look like below
public static void main(String[] args) throws IOException
{
Viennaproj viennaproj = new Viennaproj(5, "Sample Line");
String output= viennaproj.toString();
System.out.println(output);
}
And, if you are getting a FileNotFound exception when you execute this, it means that java is not able to find the file.
You must provide complete file path of your file to avoid that issue. (eg: "C:/test/input.txt")

DoubleStream returning the value 0.0 when should be 136.0

In my program I am using a DoubleStreamto sum the values of an array.
I have the following code
Training P List
import java.io.*;
import java.util.*;
import java.lang.*;
import java.util.stream.DoubleStream;
public class TrainingPList
{
int aSize=500; // size of constant
TrainingP[] arrayTrainingP= new TrainingP[aSize]; // array name + aSize constant called to define size of the array
int nextPosition=0;// size of constant
double[] MoneyList;
public void readPersonal()
{
try
{
BufferedReader br=new BufferedReader(new FileReader("TrainingP.txt"));
String theNextPublicInfo = br.readLine();
nextPosition=0;
while (theNextPublicInfo !=null)
{
String[] arrayStringPersonalInfo = theNextPublicInfo.split(",");
TrainingP tempPInfo = new TrainingP();
tempPInfo.AthleteID = arrayStringPersonalInfo[0];
tempPInfo.rMoneyRaised = Double.parseDouble(arrayStringPersonalInfo[1]);
arrayTrainingP[nextPosition] = tempPInfo;
nextPosition++;
theNextPublicInfo = br.readLine();
}
}
catch(Exception e)
{
System.out.println("Invalid read data");
}
}
public void outputarrayTrainingP()
{
for(int i=0;i<nextPosition;i++)
{
System.out.println ("Position "+":"+arrayTrainingP[i]);
}
}
public void ListAth()
{
AthList = new String[nextPosition];
for(int i=0;i<nextPosition;i++)
{
AthList[i]=arrayTrainingP[i].AthleteID+"";
}
}
public void ListMoney()
{
MoneyList = new double[nextPosition];
for(int i=0;i<nextPosition;i++)
{
MoneyList[i]=arrayTrainingP[i].rMoneyRaised;
}
DoubleStream d = DoubleStream.of(MoneyList);
double dv = d.sum();
System.out.println("The sum is " + dv);
}
public static void main(String[] args)
{
TrainingPList tp = new TrainingPList();
tp.ListMoney();
tp.readPersonal();
tp.outputarrayTrainingP();
}
}
TrainingP
public class TrainingP
{
String AthleteID;
double rMoneyRaised;
public String toString()
{
return AthleteID+","+rMoneyRaised;
}
}
Document
DJ44,136.0
DB15,0.0
There are only two values for rMoneyRaised and they are 136.0 and 0.0. However it only returns 0.0 instead of the value 136.0. Does anyone know what the problem is?
There is a problem in the main method:
public static void main(String[] args)
{
TrainingPList tp = new TrainingPList();
tp.ListMoney();
tp.readPersonal();
tp.outputarrayTrainingP();
}
You should call tp.ListMoney() after reading in the data, not before.

Categories