Handling a string from text file and continue with java program - java

The Text file:
9310,12,120,2,1
9333,12,120,2,1
PRINT
9533,5,45,0,0
8573,10,120,1,0
6343,6,18,170,0
PRINT
9311,12,120,2,1
3343,7,20,220,0
Code
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
i mport java.util.Comparator;
import java.util.List;
public class FantasyPlayers {
int player_ID;
int total_score;
public FantasyPlayers(int player, int total) {
player_ID = player;
total_score = total;
}
public String toString() {
return player_ID + "," + total_score;
}
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
FileInputStream fstream = new FileInputStream("Stats.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String delims = "[,]";
List<FantasyPlayers> Stats = new ArrayList<FantasyPlayers>();
int a = 2;
int b = 1;
int c = 6;
int d = -1;
for (String line; (line = br.readLine()) != null;)
{
String[] parsedData = line.split(delims);
if (line != "PRINT")
{
int score = Integer.parseInt(parsedData[1])*a + Integer.parseInt(parsedData[2])*b + Integer.parseInt(parsedData[3])*c + Integer.parseInt(parsedData[4])*d ;
Stats.add(new FantasyPlayers(Integer.parseInt(parsedData[0]), score));
}
else
continue;
}
br.close();
System.out.println("Unordered");
for (FantasyPlayers str : Stats)
{
System.out.println(str);
}
Collections.sort(Stats, new Comparator<FantasyPlayers>()
{
public int compare(FantasyPlayers one, FantasyPlayers two)
{
if (one.total_score == two.total_score){
Integer playerOne = one.player_ID;
Integer playerTwo = two.player_ID;
return playerTwo.compareTo(playerOne);
}
Integer scoreOne = one.total_score;
Integer scoreTwo = two.total_score;
return scoreTwo.compareTo(scoreOne);
}
});
System.out.println("Ordered");
for (FantasyPlayers str : Stats)
{
System.out.println(str);
}
}
}
I Keep getting the Error ArrayIndexOutOfBoundsException:1 at the int score = location.
My question is how do I handle the PRINT statements in the code...I'm able to do what I want with the data but I need the logic to do something when I read in the print statement. Any suggestions?

You, my friend has fallen for the most common java mistakes....
try this
if (!line.equalsIgnoreCase("PRINT"))

Try to change this line
String delims = "[,]";
to
String delims = ",";
and this line
line != "PRINT"
to
!line.trim().equals("PRINT")

Related

Comparing two text files and display unique words in java

I have two text files. I have to develop a java program which compares the two files and find unique words. I have tried a few methods but didn’t work. Example:
test1.txt:
I am a robot. My name is Sofia.
test2.txt:
Hello I am a man. My name is Alex
Output:
Hello robot man Sofia Alex
I approach was like this:
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args)
throws FileNotFoundException {
Scanner input = new Scanner(new File("test1.txt"));
Scanner scan = new Scanner(new File("test2.txt"));
ArrayList<String> al = new ArrayList<String>();
ArrayList<String> a2 = new ArrayList<String>();
String test;
while (input.hasNext()) {
String next = input.next();
}
System.out.println("arraylist" + al);
while (scan.hasNext()) {
test = scan.next();
a2.add(test);
}
System.out.println("arraylist2" + a2);
for( int i = 0; i < al.size(); i++){
for(int j = 0; j < a2.size(); j++){
if(al.get(i).equals(a2.get(j))){
break;}
else{
System.out.println(al.get(i));break;
}
}
}
}
}
Note that this is a quick and dirty approach and pretty inefficient. Furthermore I dont know your exact requirements (full stops? Upper/lowercase?).
Also take into account that this program doesn't check which list is longer. But this should give you a good hint:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("test1.txt"));
Scanner scan = new Scanner(new File("test2.txt"));
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
while (input.hasNext()) {
list1.add(input.next());
}
while (scan.hasNext()) {
list2.add(scan.next());
}
// iterate over list 1
for (int i = list1.size() - 1; i >= 0; i--) {
// if there is a occurence of two identical strings
if (list2.contains(list1.get(i))) {
// remove the String from list 2
list2.remove(list2.indexOf(list1.get(i)));
// remove the String from list 1
list1.remove(i);
}
}
// merge the lists
list1.addAll(list2);
// remove full stops
for (int i = 0; i < list1.size(); i++) {
list1.set(i, list1.get(i).replace(".", ""));
}
System.out.println("Unique Values: " + list1);
}
}
Assumptions are the text file contains only (.) as sentence terminator.
public static void main(String[] args) throws Exception
{
// Skipping reading from file and storing in string
String stringFromFileOne = "I am a robot. My name is Sofia.";
String stringFromFileTwo = "Hello I am a man. My name is Alex";
Set<String> set1 = Arrays.asList(stringFromFileOne.split(" "))
.stream()
.map(s -> s.toLowerCase())
.map(m -> m.contains(".") ? m.replace(".", "") : m)
.sorted()
.collect(Collectors.toSet());
Set<String> set2 = Arrays.asList(stringFromFileTwo.split(" "))
.stream()
.map(s -> s.toLowerCase())
.map(m -> m.contains(".") ? m.replace(".", "") : m)
.sorted()
.collect(Collectors.toSet());
List<String> uniqueWords;
if (set1.size() > set2.size()) {
uniqueWords = getUniqueWords(set2, set1);
} else {
uniqueWords = getUniqueWords(set1, set2);
}
System.out.println("uniqueWords:" + uniqueWords);
}
private static List<String> getUniqueWords(Set<String> removeFromSet, Set<String> iterateOverSet) {
List<String> uniqueWords;
Set<String> tempSet = new HashSet<String>(removeFromSet);
removeFromSet.removeAll(iterateOverSet);
uniqueWords = iterateOverSet.stream().filter(f -> !tempSet.contains(f) && !f.isEmpty())
.collect(Collectors.toList());
uniqueWords.addAll(removeFromSet);
return uniqueWords;
}
You can use guava library which gives you difference between two sets.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import com.google.common.collect.Sets;
public class WordTest {
public static void main(String[] args) {
WordTest wordTest = new WordTest();
Set<String> firstFileWords = wordTest.getAllWords("E:\\testing1.txt");
Set<String> secondFileWords = wordTest.getAllWords("E:\\testing2.txt");
Set<String> diff = Sets.difference(firstFileWords, secondFileWords);
Set<String> diff2 = Sets.difference(secondFileWords, firstFileWords);
System.out.println("Set 1: " + firstFileWords);
System.out.println("Set 2: " + secondFileWords);
System.out.println("Difference between " + "Set 1 and Set 2: " + diff);
System.out.println("Difference between " + "Set 2 and Set 1: " + diff2);
}
public Set<String> getAllWords(String path) {
FileInputStream fis = null;
DataInputStream dis = null;
BufferedReader br = null;
Set<String> wordList = new HashSet<>();
try {
fis = new FileInputStream(path);
dis = new DataInputStream(fis);
br = new BufferedReader(new InputStreamReader(dis));
String line = null;
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, " ,.;:\"");
while (st.hasMoreTokens()) {
wordList.add(st.nextToken());
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (Exception ex) {
}
}
return wordList;
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
public class FileComparision {
public static void main(String[] args) throws IOException {
HashSet<String> uniqueSet=new HashSet<String>();
//split the lines based on the delimiter and add it to set
BufferedReader reader=new BufferedReader(new FileReader("test1.txt"));
String line;
while ((line = reader.readLine()) != null) {
Arrays.asList(line.split(" ")).forEach(word->uniqueSet.add(word) ); ;
}
reader.close();
reader=new BufferedReader(new FileReader("test2.txt"));
while ((line = reader.readLine()) != null) {
Arrays.asList(line.split(" ")).forEach(word->{
if(!uniqueSet.contains(word)) {
uniqueSet.add(word) ;
}else {
uniqueSet.remove(word);
}
});
}
reader.close();
//to remove unnecessary characters
//uniqueSet.remove(".");
System.out.println(uniqueSet);
}
}
public static String readFile(String fileName)throws Exception
{
String data = "";
data = new String(Files.readAllBytes(Paths.get(fileName)));
return data;
}
public static void main(String[] args) throws Exception
{
String data = readFileAsString("C:\\Users\\pb\\Desktop\\text1.txt");
String data1 = readFileAsString("C:\\Users\\pb\\Desktop\\text2.txt");
String array[]=data.split(" ");
String array1[]=data1.split(" ");
for(int i=0;i<=array1.length-1;i++){
if(data.contains(array1[i])){
}else{
System.out.println(array1[i]);
}
}
for(int i=0;i<=array.length-1;i++){
if(data1.contains(array[i])){
}else{
System.out.println(array[i]);
}
}
}

Read a file containing multiple entries and output one entry based on user input

I am new to java and this might sound really stupid but !
Assume you have this txt file somewhere in your pc
The_txt.txt
Anthony
anthonyk#somewhere.com
01234567891
location
Maria
maria#somewhere.com
1234561234
location2
George
george#somewhere.com
1234512345
location3
What i want to do with this txt is that , I prompt the user to insert a Phone number so if for example the user provides Maria's phone number (1234561234) the program will output
Maria
maria#somewhere.com
1234561234
location2
My piece of code for this task :
private static void Search_Contact_By_Phone(File file_location){
Scanner To_Be_String = new Scanner(System.in);
String To_Be_Searched = To_Be_String.nextLine();
System.out.println("\n \n \n");
BufferedReader Search_Phone_reader;
try {
Search_Phone_reader = new BufferedReader(new FileReader (file_location));
String new_line = Search_Phone_reader.readLine();
while (new_line != null) {
if (To_Be_Searched.equals(new_line)){
for (int i=0;i<=3;i++){
System.out.println(new_line);
new_line = Search_Phone_reader.readLine();
}
break;
}
new_line = Search_Phone_reader.readLine();
}
Search_Phone_reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Thank you in advance!!!
package com.mycompany.io;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
// For a small file
Path path = Paths.get("The_txt.txt");
String toBeSearched = "1234512345";
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
// Better performance if i starts at 2 and i += 4
for (int i = 0; i < lines.size(); i++) {
if (lines.get(i).equals(toBeSearched)) {
System.out.println(lines.get(i - 2));
System.out.println(lines.get(i - 1));
System.out.println(lines.get(i));
System.out.println(lines.get(i + 1));
}
}
// Else
try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
String line1;
while ((line1 = reader.readLine()) != null) {
String line2 = reader.readLine();
String line3 = reader.readLine();
if (line3.equals(toBeSearched)) {
// Found
System.out.println(line1);
System.out.println(line2);
System.out.println(line3);
System.out.println(reader.readLine());
break;
} else {
reader.readLine();
}
}
}
}
}

How to add a column to CSV which consists of data in Java

Can we add a new column to CSV as the last column which already has let's say 3 columns with some data in it? So this new one will be added later as 4th column moreover for every row it should have random numbers.
Example,
Id Name Address Calculated
1 John U.K. 341679
2 Vj Aus 467123
3 Scott U.S. 844257
From what I understand this will require first to read csv, for loop may be to iterate to the last column and then add a new calculated column i.e Write to csv. And to add values may be the Random class of Java. But how exactly can this be done is the real question. Like a sample code would be helpful.
Code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Demo1 {
public static void main(String[] args) throws IOException {
String csvFile = "C:\\MyData\\Input.csv";
String line = "";
String cvsSplitBy = ",";
String newColumn = "";
List<String> aobj = new ArrayList<String>();
/* Code to read Csv file and split */
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null)
{
String[] csvData = line.split(cvsSplitBy);
int arrayLength = csvData.length;
}
}
/* Code to generate random number */
String CHARS = "1234567890";
StringBuilder random = new StringBuilder();
Random rnd = new Random();
while (random.length() < 18) { // length of the random string.
int index = (int) (rnd.nextFloat() * CHARS.length());
random.append(CHARS.charAt(index));
}
String finaldata = random.toString();
}
}
Great, so based on the code you provide, this could look like the following
(just to give you the idea - I write it here on the fly without testing...)
:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Demo1 {
//moved your random generator here
public static String getRandomNumber() {
/* Code to generate random number */
String CHARS = "1234567890";
StringBuilder random = new StringBuilder();
Random rnd = new Random();
while (random.length() < 18) { // length of the random string.
int index = (int) (rnd.nextFloat() * CHARS.length());
random.append(CHARS.charAt(index));
}
String finaldata = random.toString();
return finaldata;
}
public static void main(String[] args) throws IOException {
String csvFile = "C:\\MyData\\Input.csv";
String temporaryCsvFile = "C:\\MyData\\Output_temp.csv";
String line = "";
String cvsSplitBy = ",";
String newColumn = "";
List<String> aobj = new ArrayList<String>();
/* Code to read Csv file and split */
BufferedWriter writer = new BufferedWriter(new FileWriter(
temporaryCsvFile));
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null)
{
//String[] csvData = line.split(cvsSplitBy);
//int arrayLength = csvData.length;
//actually you don't even need to split anything
String newFileLine = line + cvsSplitBy + getRandomNumber();
// ... We call newLine to insert a newline character.
writer.write(newFileLine);
writer.newLine();
}
}
writer.close();
//Now delete the old file and rename the new file
//I'll leave this to you
}
}
Based on #Plirkee sample code and his help I made a final working code. Sharing it here so that it might be useful for someone with a similar requirement.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class Demo1 {
public static String getRandomNumber() {
String CHARS = "1234567890";
StringBuilder random = new StringBuilder();
Random rnd = new Random();
while (random.length() < 18) // length of the random string.
{
int index = (int) (rnd.nextFloat() * CHARS.length());
random.append(CHARS.charAt(index));
}
String finaldata = random.toString();
return finaldata;
}
public static void main(String[] args) throws IOException {
File sourceCsvFile = null;
File finalCsvFile = null;
// String sourceCsvFileName = "";
sourceCsvFile = new File("C:\\MyData\\Input.csv");
finalCsvFile = new File("C:\\MyData\\Input_1.csv");
String line = "";
String cvsSplitBy = ",";
BufferedWriter writer = new BufferedWriter(new FileWriter(finalCsvFile));
try (BufferedReader br = new BufferedReader(new FileReader(sourceCsvFile))) // read the actual Source downloaded csv file
{
line = br.readLine(); // read only first line
String newFileLine = line + cvsSplitBy + "HashValue"; // append "," and new column <HashValue>
writer.write(newFileLine); // will be written as first line in new csv
writer.newLine(); // go to next line for writing next lines
while ((line = br.readLine()) != null) // this loop to write data for all lines except headers
{
newFileLine = line + cvsSplitBy + getRandomNumber(); // will add random numbers for each row
writer.write(newFileLine);
writer.newLine();
}
}
writer.close();
if(finalCsvFile.exists() && finalCsvFile.length() > 0)
{
System.out.println("New File with HashValue column created...");
if(sourceCsvFile.delete())
{
System.out.println("Old File deleted successfully...");
}
else
{
System.out.println("Failed to delete the Old file...");
}
}
else if (!finalCsvFile.exists())
{
System.out.println("New File with HashValue column not created...");
}
}
}

How to access a textfile entering its name in console? JAVA

What should one change in the code so that instead of entering a string in console, one enters a text name (exmple.txt) to get to the text (where the frequences will be counted)?
import java.io.*;
class FrequencyCount
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println ("Enter the Text: ");
String s = br.readLine();
System.out.println ("Enter suffix: ");
String sub = br.readLine();
int ind,count = 0;
for(int i = 0; i + sub.length() <= s.length(); i++)
{
ind = s.indexOf(sub, i);
if (ind >= 0)
{
count++;
i = ind;
ind = -1;
}
}
System.out.println("Occurence of '"+sub+"' in String is "+count);
}
}
First of I will refactor your code like this in order to reuse the calculateOcurrences method. Then I would read the text file line by line and sum all the occurrences by line.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println ("Enter the file path: ");
final String filePath = br.readLine();
System.out.println ("Enter suffix: ");
final String suffix = br.readLine();
int count = 0;
Path path = FileSystems.getDefault().getPath(filePath);
Charset charset = Charset.forName("US-ASCII");
try (BufferedReader reader = Files.newBufferedReader(path, charset)) {
String line = null;
while ((line = reader.readLine()) != null) {
count = count + calculateOcurrences(line,suffix);
}
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
System.out.println("Occurence of '"+suffix+"' in String is "+count);
}
public static int calculateOcurrences(final String text, final String suffix) {
int ocurrences = 0;
for(int i = 0; i + suffix.length() <= text.length(); i++)
{
int indexOfOcurrence = text.indexOf(suffix, i);
if (indexOfOcurrence >= 0)
{
ocurrences++;
i = indexOfOcurrence;
}
}
return ocurrences;
}
}

Replace lines in File with another string

I have a text file with the following contents:
public class MyC{
public void MyMethod()
{
System.out.println("My method has been accessed");
System.out.println("hi");
}
}
I have an array num[]= {2,3,4}; which contains the line numbers to be completely replaced with the strings from this array
String[] VALUES = new String[] {"AB","BC","CD"};
That is line 2 will be replaced with AB, line 3 with BD and ine 4 with CD.
Lines which are not in the num[]array have to be written to a new file along with the changes made.
I have this so far.I tried several kind of loops but still it does not work.
public class ReadFileandReplace {
/**
* #param args
*/
public static void main(String[] args) {
try {
int num[] = {3,4,5};
String[] VALUES = new String[] {"AB","BC","CD"};
int l = num.length;
FileInputStream fs= new FileInputStream("C:\\Users\\Antish\\Desktop\\Test_File.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
LineNumberReader reader = new LineNumberReader(br);
FileWriter writer1 = new FileWriter("C:\\Users\\Antish\\Desktop\\Test_File1.txt");
String line;
int count =0;
line = br.readLine();
count++;
while(line!=null){
System.out.println(count+": "+line);
line = br.readLine();
count++;
int i=0;
if(count==num[i]){
int j=0;;
System.out.println(count);
String newtext = line.replace(line, VALUES[j]) + System.lineSeparator();
j++;
writer1.write(newtext);
}
i++;
writer1.append(line);
}
writer1.close();
}
catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}
The expected output should look like this:
public class MyC{
AB
BC
CD
Sys.out.println("hi");
}
}
When I run the code, all lines appear on the same line.
You've done almost, I've updated your code with a map. Check this
int num[] = {3, 4, 5};
String[] values = new String[]{"AB", "BC", "CD"};
HashMap<Integer,String> lineValueMap = new HashMap();
for(int i=0 ;i<num.length ; i++) {
lineValueMap.put(num[i],values[i]);
}
FileInputStream fs = new FileInputStream("test.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
FileWriter writer1 = new FileWriter("test1.txt");
int count = 1;
String line = br.readLine();
while (line != null) {
String replaceValue = lineValueMap.get(count);
if(replaceValue != null) {
writer1.write(replaceValue);
} else {
writer1.write(line);
}
writer1.write(System.getProperty("line.separator"));
line = br.readLine();
count++;
}
writer1.flush();
You're appending each line to the same string. You should add the line separator character at the end of each line as well. (You can do this robustly using System.getProperty("line.separator"))
you have not appended end line character.
writer1.append(line); is appending the data in line without endline character. Thus it is showing in one line. You might need to change it to:
writer1.append(line).append("\n");
Try This
package src;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;
public class MainTest {
static int i ;
public static void main(String[] arg)
{
try {
int num[] = {3,4,5};
String[] VALUES = new String[] {"AB","BC","CD"};
FileInputStream fs= new FileInputStream("C:\\Test\\ren.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
FileWriter writer1 = new FileWriter("C:\\Test\\ren1.txt");
String line;
Integer count =0;
line = br.readLine();
count++;
while(line!=null){
for(int index =0;index<num.length;index++){
if(count == num[index]){
line = VALUES[index];
}
}
writer1.write(line+System.getProperty("line.separator"));
line = br.readLine();
count++;
}
writer1.close();
}
catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}

Categories