java cannot create file by 3 methods - java

I have a test.txt in my active directory.I need to create three methods:
First one has to create an output file and reverse the order of the lines.
Second the order of the words
The third the order of the lines and the words.
test.txt contains the input.
I developed every method to work on its own but somehow when I call all three at the same time it doesnt seem to work.
What am i doing wrong?
This is my main:
import java.io.*;
public class DemoReverser {
public static void main (String [] args)
throws IOException, FileNotFoundException {
Reverser r = new Reverser(new File("test.txt"));
r.completeReverse(new File("out3.txt"));
r.reverseEachLine(new File("out2.txt"));
r.reverseLines(new File("out1.txt"));
} }
and this is my class.
import java.util.*;
import java.io.*;
public class Reverser {
Scanner sc = null ;
Scanner sc2 = null;
//constructor takes input file and initialize scanner sc pointing at input
public Reverser(File file)throws FileNotFoundException, IOException{
sc = new Scanner (file);
}
//this method reverses the order of the lines in the output
//prints to output file specified in argument.
public void reverseLines(File outpr)throws FileNotFoundException, IOException{
List<String> wordsarraylist = new ArrayList<String>();
while(sc.hasNextLine()){
wordsarraylist.add(sc.nextLine());
}
Collections.reverse(wordsarraylist);
FileWriter writer = new FileWriter(outpr,true);
for(String str: wordsarraylist) {
writer.write(str+System.lineSeparator());
}
writer.flush();
writer.close();
}
//this method reverses the order of the words in each line of the input
//and prints it to output file specified in argument.
public void reverseEachLine(File outpr)throws FileNotFoundException, IOException{
while(sc.hasNextLine()){
String sentence = sc.nextLine();
String[] words = sentence.split(" ");
ArrayList<String> wordsarraylist = new ArrayList<String>(Arrays.asList(words));
Collections.reverse(wordsarraylist);
FileWriter writer = new FileWriter(outpr,true);
for(String str: wordsarraylist) {
writer.write(str + " ");
}
writer.write(System.lineSeparator());
writer.flush();
writer.close();
}
}
//this methhod reverses the order of the words in each sentence of the input
//then writes it to output file specified in argument
//then uses the output file as input and reverses the order of the sentences
//then overwrites the ouput file with the result
//the output file will contain the input sentences with their words reversed
// and the order of sentences reversed.
public void completeReverse(File outpr) throws FileNotFoundException, IOException{
while(sc.hasNextLine()){
String sentence = sc.nextLine();
String[] words = sentence.split(" ");
ArrayList<String> wordsarraylist2 = new ArrayList<String>(Arrays.asList(words));
Collections.reverse(wordsarraylist2);
FileWriter writer = new FileWriter(outpr,true);
for(String str: wordsarraylist2) {
writer.write(str + " ");
}
writer.write(System.lineSeparator());
writer.flush();
writer.close();
}
sc2 = new Scanner (outpr);
List<String> wordsarraylist = new ArrayList<String>();
while(sc2.hasNextLine()){
wordsarraylist.add(sc2.nextLine());
}
Collections.reverse(wordsarraylist);
PrintWriter erase = new PrintWriter(outpr);
erase.print("");
// erase.flush();
erase.close();
FileWriter writer = new FileWriter(outpr,true);
for(String str: wordsarraylist) {
writer.write(str+System.lineSeparator());
}
writer.flush();
writer.close();
}
}
When I run the program, out1 file gests created, which is the output file for my first method but it is empty. I don't get out2 file created by second method and out3 is fine.
What am I doing wrong? What is missed

Add writer.flush(); before writer.close(); in all three methods
And other thing - Scanner is initialized with File only once in constructor. It has to be re-initialized in other methods.
sc = new Scanner (file); // the scanner should be available in all three methods
For catching exceptions, use
try{
// your code
}catch(Exception err){
err.printStackTrace();
}
After running your code, output3.txt is generated (First method call). Later Scanner is not available since end of the file has been reached.
Fix : Scanner should be re-initialized for next two methods.
EDIT: ( Updating answer with your chat feedback)
1) Create three scanners sc1,sc2 and sc3 due to your limitations. I would suggest to re-initialize the scanner in every method with the file being worked upon.
2) String reversal in easier way without using StringBuffer reverse() API ( For learning purpose)
int length = str.length();
String reverse = "";
for ( int i = length - 1 ; i >= 0 ; i-- ){
reverse = reverse + str.charAt(i);
}

It's possible if you haven't write permission where you currently trying. So you get an error when testing.
However you have made some few mistakes in code. reverseEachLine method was not worked and you should not waste code to create completeReverse method. Please note following things.
Construct the Scanner when you need it
Remember to close the Scanner
Write processed file after closing the Scanner
Remove append if not necessary in Filewriter
Remember to flush FileWriter
Identify similarities and relationships between methods (complete reverse is a combination of line reverse and word reverse)
public class MyReverser {
private File inputFile;
public MyReverser(File file) {
this.inputFile = file;
}
public void reverseLines(File outpr) throws FileNotFoundException, IOException {
Scanner sc = new java.util.Scanner(inputFile);
List<String> wordsarraylist = new ArrayList<String>();
while (sc.hasNextLine()) {
wordsarraylist.add(sc.nextLine());
}
sc.close();
Collections.reverse(wordsarraylist);
FileWriter writer = new FileWriter(outpr, false);
for (String str : wordsarraylist) {
writer.write(str + System.lineSeparator());
}
writer.flush();
writer.close();
}
public void reverseEachLine(File outpr) throws FileNotFoundException, IOException {
Scanner sc = new Scanner(inputFile);
ArrayList<List<String>> wordsarraylist = new ArrayList<List<String>>();
while (sc.hasNextLine()) {
String sentence = sc.nextLine();
List words = Arrays.asList(sentence.split(" "));
Collections.reverse(words);
wordsarraylist.add(words);
}
FileWriter writer = new FileWriter(outpr, false);
for (List<String> list : wordsarraylist) {
for (String string : list) {
writer.append(string + " ");
}
writer.append(System.lineSeparator());
}
writer.flush();
writer.close();
}
public void completeReverse(File outpr) throws FileNotFoundException, IOException {
//reverse lines first
reverseLines(outpr);
//then reverse words
reverseEachLine(outpr);
}
}

The scenario here was the scanners were instance variables and once read in one of your operations method, it won't have more to read when you call the next method from Demo class. Have made the changes to read the sentences and store it in the instance, so that it can be reused in each method.
import java.util.*;
import java.io.*;
public class Reverser {
Scanner sc = null;
Scanner sc2 = null;
boolean hasReadFile;
List<String> fileLinesList;
// constructor takes input file and initialize scanner sc pointing at input
public Reverser(File file) throws FileNotFoundException, IOException {
sc = new Scanner(file);
hasReadFile = false;
fileLinesList = new ArrayList<>();
}
// this method reverses the order of the lines in the output
// prints to output file specified in argument.
public void reverseLines(File outpr) throws FileNotFoundException,
IOException {
List<String> wordsarraylist = new ArrayList<String>();
readFile();
for (String sentence : fileLinesList) {
wordsarraylist.add(sentence);
}
Collections.reverse(wordsarraylist);
FileWriter writer = new FileWriter(outpr, true);
for (String str : wordsarraylist) {
writer.write(str + System.lineSeparator());
}
writer.flush();
writer.close();
}
// this method reverses the order of the words in each line of the input
// and prints it to output file specified in argument.
public void reverseEachLine(File outpr) throws FileNotFoundException,
IOException {
readFile();
for (String sentence : fileLinesList) {
String[] words = sentence.split(" ");
ArrayList<String> wordsarraylist = new ArrayList<String>(
Arrays.asList(words));
Collections.reverse(wordsarraylist);
FileWriter writer = new FileWriter(outpr, true);
for (String str : wordsarraylist) {
writer.write(str + " ");
}
writer.write(System.lineSeparator());
writer.flush();
writer.close();
}
}
private void readFile() {
if (!hasReadFile) {
while (sc.hasNextLine()) {
fileLinesList.add(sc.nextLine());
}
fileLinesList = Collections.unmodifiableList(fileLinesList);
hasReadFile = true;
}
}
// this methhod reverses the order of the words in each sentence of the
// input
// then writes it to output file specified in argument
// then uses the output file as input and reverses the order of the
// sentences
// then overwrites the ouput file with the result
// the output file will contain the input sentences with their words
// reversed
// and the order of sentences reversed.
public void completeReverse(File outpr) throws FileNotFoundException,
IOException {
readFile();
for (String sentence : fileLinesList) {
String[] words = sentence.split(" ");
ArrayList<String> wordsarraylist2 = new ArrayList<String>(
Arrays.asList(words));
Collections.reverse(wordsarraylist2);
FileWriter writer = new FileWriter(outpr, true);
for (String str : wordsarraylist2) {
writer.write(str + " ");
}
writer.write(System.lineSeparator());
writer.flush();
writer.close();
}
sc2 = new Scanner(outpr);
List<String> wordsarraylist = new ArrayList<String>();
while (sc2.hasNextLine()) {
wordsarraylist.add(sc2.nextLine());
}
Collections.reverse(wordsarraylist);
PrintWriter erase = new PrintWriter(outpr);
erase.print("");
// erase.flush();
erase.close();
FileWriter writer = new FileWriter(outpr, true);
for (String str : wordsarraylist) {
writer.write(str + System.lineSeparator());
}
writer.flush();
writer.close();
}
}

Related

Is there any function to use with list to jump next line?

Trying to read text file & adding content to an array list and than writing to a new text file but its not appearing in the same format as of original file.
I want it to be in same format as of original file.
public static void main(String args[]) throws IOException
{
Scanner sc1 = new Scanner(new File("C:\\Users\\amank\\eclipse-workspace\\DataStructures\\src\\sample1-pp.txt"));
ArrayList<String> list = new ArrayList<String>();
//testing
FileWriter writer = new FileWriter ("C:\\Users\\amank\\eclipse-workspace\\DataStructures\\src\\output.txt");;
if(!sc1.hasNext())
{
System.out.println("File is empty");
}
try {
while (sc1.hasNext())
{
list.add(sc1.nextLine().trim().toLowerCase().replaceAll("\\p{P}", ""));
}
sc1.close();
//for testing
for(String str: list)
{
writer.write(str);
}
writer.close();
Expected
Pride and Prejudice
by Jane Austen
Chapter 1
It is a truth universally acknowledged, that a single man in possession of a good fortune, must be in want of a wife.
======
Actual
pride and prejudiceby jane austenchapter 1it is a truth universally acknowledged that a single man in possession of a good fortune must be in want of a wife
You need to add line seperator while writing to the file
public static void main(String args[]) throws IOException{
Scanner sc1 = new Scanner(new File("C:\\Users\\amank\\eclipse-workspace\\DataStructures\\src\\sample1-pp.txt"));
ArrayList<String> list = new ArrayList<String>();
//testing
FileWriter writer = new FileWriter ("C:\\Users\\amank\\eclipse-workspace\\DataStructures\\src\\output.txt");;
if(!sc1.hasNext())
{
System.out.println("File is empty");
}
try {
while (sc1.hasNext())
{
list.add(sc1.nextLine().trim().toLowerCase().replaceAll("\\p{P}", ""));
}
sc1.close();
//for testing
String newLine = System.getProperty("line.separator");
for(String str: list)
{
writer.write(str+newLine);
}
writer.close();
Why You read lines from files, convert them to lowercase, trimming them then add them to ArrayList...?
Just add lines to the ArrayList as is
public static void main(String args[]) {
try {
Scanner sc1 = new Scanner(new File("C:\\Users\\amank\\eclipse-workspace\\DataStructures\\src\\sample1-pp.txt"));
ArrayList<String> list = new ArrayList<String>();
//testing
FileWriter writer = new FileWriter("C:\\Users\\amank\\eclipse-workspace\\DataStructures\\src\\output.txt");;
if (!sc1.hasNext()) {
System.out.println("File is empty");
}
while (sc1.hasNext()) {
list.add(sc1.nextLine());
}
sc1.close();
//for testing
for (String str : list) {
writer.write(str);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Java: How can I read and store them in array by a new line in ArrayList?

Here is what my .txt file looks like (but more than 100 elements per line and more than 100 lines):
-0.89094 -0.86099 -0.82438 -0.78214 -0.73573 -0.68691 -0.63754
-0.42469 -0.3924 -0.36389 -0.33906 -0.31795 -0.30056 -0.28692
What I want to do is read this .txt file and store them in Arryalist. The problem is when I read and store this data, they put all of this in the same array (I want them to store in 2 arrays split by a line).
Here is my code:
public class ReadStore {
public static void main(String[] args) throws IOException {
Scanner inFile = new Scanner(new File("Untitled.txt")).useDelimiter("\\s");
ArrayList<Float> temps = new ArrayList<Float>();
while (inFile.hasNextFloat()) {
// find next line
float token = inFile.nextFloat();
temps.add(token);
}
inFile1.close();
Float [] tempsArray = temps.toArray(new Float[0]);
for (Float s : tempsArray) {
System.out.println(s);
}
}
Any suggestion for making this works?
I might go about this by just reading in each line in its entirety, and then splitting on whitespace to access each floating point number. This gets around the issue of having to distinguish spaces from line separators.
public class ReadStore {
public static void main(String[] args) throws IOException {
Scanner inFile = new Scanner(new File("Untitled.txt"));
ArrayList<Float> temps = new ArrayList<Float>();
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
String[] nums = line.trim().split("\\s+");
for (String num : nums) {
float token = Float.parseFloat(num);
temps.add(token);
}
Float [] tempsArray = temps.toArray(new Float[0]);
for (Float s : tempsArray) {
System.out.println(s);
}
}
inFile.close();
}
}
Here is a demo showing that the logic works for a single line of your input file. Note that I call String#trim() on each line before splitting it, just in case there is any leading or trailing whitespace which we don't want.
Rextester
First read line by line, then for each line read each float.
Try This :
public static void main(String[] args) throws IOException {
Scanner inFile = new Scanner(new File("Untitled.txt"));
List<List<Float>> temps = new ArrayList<>();
while (inFile.hasNextLine()) {
List<Float> data = new ArrayList<>();
Scanner inLine = new Scanner(inFile.nextLine());
while (inLine.hasNextFloat()) {
data.add(inLine.nextFloat());
}
inLine.close();
temps.add(data);
}
inFile.close();
Float[][] dataArray = new Float[temps.size()][];
for (int i = 0; i < dataArray.length; i++) {
dataArray[i] = temps.get(i).toArray(new Float[temps.get(i).size()]);
}
System.out.println(Arrays.deepToString(dataArray));
}
Output :
[[-0.89094, -0.86099, -0.82438, -0.78214, -0.73573, -0.68691, -0.63754], [-0.42469, -0.3924, -0.36389, -0.33906, -0.31795, -0.30056, -0.28692]]
You can read line by line and split it by spaces . Working and tested code:
public static void main(String[] args) throws IOException {
Scanner inFile = new Scanner(new File("C:\\Untitled.txt"));
ArrayList<String[]> temps = new ArrayList<>();
while (inFile.hasNextLine()) {
// find next line
String line = inFile.nextLine();
String[] floats = line.split("\\s+");
temps.add(floats);
}
inFile.close();
temps.forEach(arr -> {
System.out.println(Arrays.toString(arr));
});
}
You can also read float values by regex.
Scanner inFile = new Scanner(new File("C:\\Untitled.txt"));
ArrayList<Float> temps = new ArrayList<>();
while (inFile.hasNext("-\\d\\.\\d+")) {
// find next line
String line = inFile.next();
temps.add(Float.valueOf(line));
}
inFile.close();
Read the file once with Files.readAllLines method. And split it by spaces
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
String readFileContent = readFileContent(new File("Test.txt"));
ArrayList<Float> temps = new ArrayList<Float>();
String[] split = readFileContent.split("\\s+");
for (String num : split) {
float token = Float.parseFloat(num.trim());
temps.add(token);
}
Float [] tempsArray = temps.toArray(new Float[0]);
for (Float s : tempsArray) {
System.out.println(s);
}
}
private static String readFileContent(File file) {
try {
return Files.readAllLines(file.toPath()).stream().collect(Collectors.joining("\n"));
} catch (IOException e) {
System.out.println("Error while reading file " + file.getAbsolutePath());
}
return "";
}
}
Each line can be stored as an ArrayList and each ArrayList inside another ArrayList creating a 2-Dimensional ArrayList of Float type.
Read each line using java.util.Scanner.nextLine() and then parse each line for float value. I have used another scanner to parse each line for float values.
After parsing, store float values into a tmp ArrayList and add that list to the major List. Be sure to close the local scanner inside the while itself.
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class ReadStore {
public static void main(String[] args) throws IOException {
//Input File
Scanner inFile =new Scanner(new File("Untitled1.txt")).useDelimiter("\\s");
//Major List (2-D ArrayList)
ArrayList<ArrayList<Float>> list = new ArrayList<ArrayList<Float>>();
//Reading Each Line
while (inFile.hasNextLine()) {
//tmp ArrayList
ArrayList<Float> arr = new ArrayList<Float>();
String line = inFile.nextLine();
//local scanner to be used for parsing
Scanner local = new Scanner(line);
//Parsing line for flat values
while(local.hasNext()){
if(local.hasNextFloat()){
float token = local.nextFloat();
arr.add(token);
}
}
//closing local Scanner
local.close();
//Adding to major List
list.add(arr);
}
inFile.close();
//Display List values
for(ArrayList<Float> arrList:list){
for(Float f : arrList){
System.out.print(f + " ");
}
System.out.println();
}
}
}
I'm assuming that the number of floats on each line might differ from line to line. If they're all the same, I'd suggest reading them into one big list and then splitting it into sublists.
But if you want to have all the floats on a line be in a single list, it seems like the best approach is to read the file line by line. Then, split each line into tokens, convert to float, and collect the results into a list. The overall result will be a list of list of float. This is pretty easy to do with Java 8 streams:
static List<List<Float>> readData() throws IOException {
Pattern pat = Pattern.compile("\\s+");
try (Stream<String> allLines = Files.lines(Paths.get(filename))) {
return allLines.map(line -> pat.splitAsStream(line)
.map(Float::parseFloat)
.collect(Collectors.toList()))
.collect(Collectors.toList());
}
}
Note the use of Files.lines to get a stream of lines, and also note the use of try-with-resources on the resulting stream.
If you have Java 9, you can simplify this a tiny bit by using Scanner instead of Pattern.splitAsStream to parse the tokens on each line:
static List<List<Float>> readData9() throws IOException {
try (Stream<String> allLines = Files.lines(Paths.get(filename))) {
return allLines.map(Scanner::new)
.map(sc -> sc.tokens()
.map(Float::parseFloat)
.collect(Collectors.toList()))
.collect(Collectors.toList());
}
}

Write to file line by line

So my input file has some sentences, and i want to reverse the words in each sentence and keep the same order of sentences. I then need to print to a file. my problem is that my output file is only printing my last sentence, reversed.
import java.util.*;
import java.io.*;
public class Reverser { //constructor Scanner sc = null ; public
Reverser(File file)throws FileNotFoundException, IOException {
sc = new Scanner (file); }
public void reverseLines(File outpr)throws FileNotFoundException, IOExeption{
//PrintWriter pw = new PrintWriter(outpr);
while(sc.hasNextLine()){
String sentence = sc.nextLine();
String[] words = sentence.split(" ");
ArrayList<String> wordsarraylist = new ArrayList<String>(Arrays.asList(words));
Collections.reverse(wordsarraylist);
FileWriter fw = new FileWriter(outpr);
BufferedWriter bw = new BufferedWriter(fw);
for(String str: wordsarraylist) {
bw.write(str + " ");
bw.newLine();
bw.close();
}
} }
}
That's because each time you loop, you reopen the file in overwrite mode.
Open the file before you start looping instead.
Don't use the append option here, it'll just make you open/close the file needlessly.

Storing input into file

I am having an issue trying to search a text file for the exact input that a user enters. I want to output the sentence not only by direct user input but i want the program to recognize some word(s) that would signal the desired text. I got searching for the keyword part down pack and working but i am only able to search the text based on the keyword. I want to search based on the keyword and the entire inputted sentence. For example if the keyword is e-mail and the user enter's what is mars e-mail? and the text file contains "mars e-mail is mars3433#aol.com, john e-mail is anonymous" i want to output mars e-mail is ... instead of both sentences. I am completely stuck trying to figure out this issue, Can anyone help me?
public static class DicEntry {
String key;
String[] syns;
Pattern pattern;
public DicEntry(String key, String... syns) {
this.key = key;
this.syns = syns;
pattern = Pattern.compile(".*(?:"
+ Stream.concat(Stream.of(key), Stream.of(syns))
.map(x -> "\\b" + Pattern.quote(x) + "\\b")
.collect(Collectors.joining("|")) + ").*");
}
}
public static void removedata(String s) throws IOException {
File f = new File("data.txt");
File f1 = new File("data2.txt");
BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
BufferedReader br = new BufferedReader(new FileReader(f));
PrintWriter pr = new PrintWriter(f1);
String line;
while ((line = br.readLine()) != null) {
if (line.contains(s)) {
System.out.println("Enter new Text :");
String newText = input.readLine();
line = newText;
System.out.println("Thank you, Have a good Day!");
}
pr.println(line);
}
br.close();
pr.close();
input.close();
Files.move(f1.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
public static void parseFile(String s) throws IOException {
File file = new File("data.txt");
Scanner forget = new Scanner(System.in);
Scanner scanner = new Scanner(file);
int flag_found = 0;
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
System.out.println(lineFromFile);
flag_found = 1;
System.out
.println(" Would you like to update this information ? ");
String yellow = forget.nextLine();
if (yellow.equals("yes")) {
removedata(lineFromFile);
} else if (yellow.equals("no")) {
System.out.println("Have a good day");
// break;
}
}
}
if (flag_found == 0) {// input is not found in the txt file so
// flag_found remains 0
writer();
}
}
public static void writer() {
Scanner Keyboard = new Scanner(System.in);
Scanner input = new Scanner(System.in);
File file = new File("data.txt");
try (BufferedWriter wr = new BufferedWriter(new FileWriter(
file.getAbsoluteFile(), true))) { // Creates a writer object
// called wr
// file.getabsolutefile
// takes the filename and
// keeps on storing the old
System.out.println("I Do not know, Perhaps you want to teach me?"
+ "..."); // data
while ((Keyboard.hasNext())) {
String lines = Keyboard.nextLine();
System.out.print(" is this correct ? ");
String go = input.nextLine();
if (go.equals("no")) {
System.out.println("enter line again");
lines = Keyboard.nextLine();
System.out.print(" is this correct ? ");
go = input.nextLine();
}
else if (go.equals("yes")) {
wr.write(lines);
// wr.write("\n");
wr.newLine();
wr.close();
}
System.out.println("Thankk you");
break;
}
} catch (IOException e) {
System.out.println(" cannot write to file " + file.toString());
}
}
private static List<DicEntry> populateSynonymMap() {
List<DicEntry> responses = new ArrayList<>();
responses.add(new DicEntry("student", "pupil", "scholar"));
responses.add(new DicEntry("office", "post", "room"));
responses.add(new DicEntry("topics", "semester talk"));
return responses;
}
public static void getinput() throws IOException {
List<DicEntry> synonymMap = populateSynonymMap(); // populate the map
Scanner scanner = new Scanner(System.in);
String input = null;
/* End Initialization */
System.out.println("Welcome ");
System.out.println("What would you like to know?");
System.out.print("> ");
input = scanner.nextLine().toLowerCase();
String[] inputs = input.split(" ");
int flag_found = 0;
for (DicEntry entry : synonymMap) { // iterate over each word of the
// sentence.
if (entry.pattern.matcher(input).matches()) {
// System.out.println(entry.key);
parseFile(entry.key);
flag_found = 1;// Input is found
}
}
if (flag_found == 0) {// input is not found in the txt file so
// flag_found remains 0
writer();
}
}
public static void main(String args[]) throws ParseException, IOException {
/* Initialization */
getinput();
}
}
So my methods work like this, the parse file method searching the text file for the keyword in the sentence. My writer( ) writes to the file if the input is not found and my remove data ( ) erases the line and updates it with the new string upon user request. and get input is just a method to get information from the scanner.
In my opinion, additional obstacle is fact, that some word can repeat in unrelated sentences. My solution seems to be quite long for me, but it works. However when I test it, I didn't use your dicEntry. It is impossible to hard-code all synonyms, so you should reconsider this approach.
I added one class, jast as data holder for int repetition variable (see below) and particular sentence:
public class Pair {
int repetitions;
String sentence;
public Pair(int rep, String string){
repetitions = rep;
sentence = string;
}
public int getRepetitions() {
return repetitions;
}
public String getSentence() {
return sentence;
}
}
Then I wrote a method, which loop through input sentence, and file content, looking for sentence from file, in which most inputs words repeted. I pretty sure, it is not most efficient way, but I don't know another :P.
public static String getMostAppropriate(String[] input) throws IOException{
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
ArrayList<Pair> pairs = new ArrayList<>();
int repetitions = 0;
while (scanner.hasNextLine()) {
String newLine = scanner.nextLine();
String[] line = newLine.split(","); // this regex depends on your file format style,
String oneSentence = "";
for(String sentence : line){ // for sentence in file lines
for(String string : sentence.split(" ")){ // for words in these sentences
for(String word : input){ // for words from input
if(word.equals(string)){
repetitions += 1;
oneSentence = sentence;
}
}
}
pairs.add(new Pair(repetitions,oneSentence));
repetitions = 0;
}
}
return mostCommon(pairs);
}
The argument is String[] inputs form your getInput method. In return statement I called another new method, which looks for sentences with most repetitions:
public static String mostCommon(ArrayList<Pair> pairs){
Pair max = new Pair(0,"");
String result = "";
for(Pair pair : pairs){
if(pair.getRepetitions() > max.getRepetitions()){
result = pair.getSentence();
max = pair;
}else if(pair.getRepetitions()==max.getRepetitions()){
result += "; " + pair.getSentence();
}
}
return result;
}
If some sentences have same number of repetitions, it returns both(or more) connected into one sentence (sentence; sentence; etc.).
Implementation into your code I left for you, if you are interested.
As I said, I didn't use your dicEntry, still you can add it as additional loop, but chacking whole dictionary will not be too effective with my method.
Also, if I were you, I would divide some of your methods into smaller one, I mean like: read file in one, ask for additional input in another. Because it is easier to implement changes this way. You don't need to keep eye on whole method, just arguments they pass to each other.
I hope you will find something useful in my post.

How to Toggle/Switch the Case of every letter in a text file?

Ok so here is the code I created for the program to read a text file.
Now can someone tell me how to switch every letter's case from uppercase to lower and vice versa in the result? Notice that I want the program to read the file from the command line and not a string.
If possible I'd like the answer in code :| Thanks
I am very new in Java and could use some help thanks.
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
java.io.File file = new java.io.File("C:\\Users\\Lifeless\\Desktop\\123.txt");
try {
Scanner input = new Scanner(file);
while (input.hasNext()) {
String num = input.nextLine(); //grabs line
System.out.println(num);
}
}
catch (FileNotFoundException e) {
System.err.format("File does not exist \n");
I used a bufferedReader and put all lines of the file in an ArrayList.
static ArrayList<String> lines;
public static void main(String[] args) throws FileNotFoundException, IOException
{
lines = new ArrayList<>();
File f = new File(args[0]);
BufferedReader r = new BufferedReader(new FileReader(f));
String line = r.readLine ();
while(line != null)
{
lines.add(invert(line));
line = r.readLine ();
}
for(String s : lines)
{
System.out.println(s);
}
}
private static String invert(String line)
{
char[] singleChars = line.toCharArray (); //split Line into single Characters
for(int i = 0;i< singleChars.length;i++) //Iterate over every single Character
{
if(Character.isAlphabetic (singleChars[i]))
{
if(Character.isUpperCase (singleChars[i])) //swap Upper to Lower and vice versa
{
singleChars[i] = Character.toLowerCase (singleChars[i]);
}else
{
singleChars[i] = Character.toUpperCase (singleChars[i]);
}
}
}
return new String(singleChars);
}

Categories