I want to ask you if is it possible to change/decompose my code to 2-3 classes, add constructors (if possible not empty) and/or add more methods. If need program can have more functions.
public class Testing {
public static void main(String args[]) throws Exception {
Scanner input = new Scanner(System.in);
System.out.println("Select word from list:");
System.out.println();
try {
FileReader fr = new FileReader("src/lt/kvk/i3_2/test/List.txt"); // this is list of words, everything all right here
BufferedReader br = new BufferedReader(fr);
String s;
while((s = br.readLine()) != null) {
System.out.println(s);
}
fr.close();
String stilius = input.nextLine(); // eneter word which I want to count in File.txt
BufferedReader bf = new BufferedReader(new FileReader("src/lt/kvk/i3_2/test/File.txt")); // from this file I need to count word which I entered before
int counter = 0;
String line;
System.out.println("Looking for information");
ArrayList<String> resultList = new ArrayList<String>();
String name = null;
while (( line = bf.readLine()) != null){
if (line.trim().length() == 0) name = null;
else if (name == null) name = line;
int indexfound = line.indexOf(stilius);
if (indexfound > -1) {
counter++;
resultList.add(name);
}
}
if (counter > 0) {
System.out.println("Word are repeated "+ counter + "times");}
else {
System.out.println("Error...");
}
bf.close();
}
catch (IOException e) {
System.out.println("Error:" + e.toString());
}
}
}
Program counting words (entered by keyboard) from file.txt and elect who repeated this word for ex.: if I enter word: One It shows:
Word One repeated 3 times by John, Elisa, Albert
file.txt looks like:
John //first line - name
One
Three
Four
Peter //first line - name
Two
Three
Elisa //first line - name
One
Three
Albert //first line - name
One
Three
Four
Nicole //first line - name
Two
Four
I don't know really if is possible to decompose this code to 2-3 classes. If someone could help me, thank you very much.
I would start by defining two classes:
WordFile
WordFileEntry
A WordFile-object should consist of a list of WordFileEntry-objects. A WordFileEntry consists of String name and List<String> words.
The counting of repetitions could be done by a WordFile-object itself. The logic of reading a file could be written in the WordFile-class or a separate class.
Related
I was just wondering if there is a way to loop through a text file until a particular string is found.
For example, say you have a text file with the following in it:
banana
apple
grapes
melon
orange
cherries
strawberry chocolate vanilla
I basically want to write a program that loops through the input file until it gets to a particular string the user specifies and then stores the next line in an array list. So, basically say if I imputed cherries I want it to store strawberry, chocolate, vanilla in an array list. For the life of me I cannot figure out how to do this though, so anything would be appreciated. What I have so far is below.
public static void main(String[] args) throws IOException {
String line;
ArrayList<String> names = new ArrayList<>();
Scanner in = new Scanner(System.in);
System.out.print("Enter the input file: ");
String input = in.next();
FileReader file = new FileReader(input);
BufferedReader reader = new BufferedReader(file);
System.out.print("What fruit do you want: ");
String fruit = in.next();
line = reader.readLine();
while ((line != null)) {
if(line.equals(fruit){
}
}
Just loop through the input until the searched line is encountered and store every line found afterwards in the list.
String line;
while((line = reader.readLine()) != null)
if(line.equals(fruit))
break;
ArrayList<String> lines = new ArrayList<>();
while((line = reader.readLine()) != null)
lines.add(line);
if I understand your question correctly, I have an idea that you can start from
Scanner scanner = new Scanner(file);
List<String> list = new ArrayList<String>();
while (scanner.hasNextLine()) { // read the entire file into list but it consumes time especially if the file is big (not perfect choice)
list.add(scanner.nextLine());
}
now what you can do
// add boolean to announce the occurrance of the word
boolean found = false;
for(String word: list){ // then you have a greater control over it to search
if(word.equals(fruit)){
found = true;
}
if (found) {
// start taking the rest of the array into a new array or whatever you want to do
}
}
You could use a boolean to indicate when the value is found and when it is true you can add the line in the List :
boolean isFound = false;
String line;
while ((line=reader.readLine())!= null) {
if(!isFound && line.equals(fruit){
isFound = true;
}
else if (isFound){
names.add(line);
}
}
Create flag isFound. Set it to true when you find the string.
It will then process on the next loop and set to false like so.
bool isFound=false;
while ((line != null)) {
if(isFound==true){
names.add(string)
isFound=false;
}
if(line.equals(fruit){
isFound=true;
}
}
check it out:
public static void main(String[] args) throws IOException {
String line;
List<String> names = new ArrayList<>();
Scanner in = new Scanner(System.in);
System.out.print("Enter the input file: ");
String input = in.next();
FileReader file = new FileReader(input);
BufferedReader reader = new BufferedReader(file);
System.out.print("What fruit do you want: ");
String fruit = in.next();
boolean found=false;
while ((line = reader.readLine()) != null){
if (line.equals(fruit) || found) {
names.add(line);
found=true;
}
}
}
So I am doing this past sample final exam where the question asks to read input from a file and then process them into words. The end of a sentence is marked by any word that ends with one of the three characters . ? !
I was able to write a code for this however I can only split them into sentences using scanner class and using use.Delimiter. I want to process them into words and see if a word ends in the above sentence separator then I will just stop adding words into the sentence class.
Any help would be appreciated as I am learning this on my own and this is what I came up with. My code is here.
File file = new File("finalq4.txt");
Scanner scanner = new Scanner(file);
scanner.useDelimiter("[.?!]");
while(scanner.hasNext()){
sentCount++;
line = scanner.next();
line = line.replaceAll("\\r?\\n", " ");
line = line.trim();
StringTokenizer tokenizer = new StringTokenizer(line, " ");
wordsCount += tokenizer.countTokens();
sentences.add(new Sentence(line,wordsCount));
for(int i = 0; i < line.replaceAll(",|\\s+|'|-","").length(); i++){
currentChar = line.charAt(i);
if (Character.isDigit(currentChar)) {
}else{
lettersCount++;
}
}
}
What I am doing in this code is that I am splitting the input into sentences using the Delimiter method and then counting the words, letters of the entire file and storing the sentences in a sentence class.
If I want to split this into words, how can I do that without using the scanner class.
Some of the input from the file that I have to process is here:
Text that follows is based on the Wikipedia page on cryptography!
Cryptography is the practice and study of hiding information. In modern times,
cryptography is considered to be a branch of both mathematics and computer
science, and is affiliated closely with information theory, computer security, and
engineering. Cryptography is used in applications present in technologically
advanced societies; examples include the security of ATM cards, computer
passwords, and electronic commerce, which all depend on cryptography.....
I can further elaborate on this question if it needs explanation.
What I want to be able to do is to keep adding words to the sentence class and stop if the word ends in one of the above sentence separator. And then read another word and keep adding the words until I hit another separator.
The snippet below shall work
public static void main(String[] args) throws FileNotFoundException {
File file = new File("final.txt");
Scanner scanner = new Scanner(file);
scanner.useDelimiter("[.?!]");
int sentCount;
List<Sentence> sentences = new ArrayList<Sentence>();
while (scanner.hasNext()) {
String line = scanner.next();
if (!line.equals("")) { /// for the ... in the end
int wordsCount = 0;
String[] wordsOfLine = line.split(" ");
for (int i = 0; i < wordsOfLine.length; i++) {
wordsCount++;
}
Sentence sentence = new Sentence(line, wordsCount);
sentences.add(sentence);
}
}
}
public class Sentence {
String line = "";
int wordsCount = 0;
public Sentence(String line, int wordsCount) {
this.line = line;
this.wordsCount=wordsCount;
}
You can use a buffered reader to read every line of the file. Then split every line into a sentence with the split method and finally to get the words just split the sentence with the same method. In the end it would look something like this:
BufferedReader br;
try{
br = new BufferedReader(new File(fileName));
}catch (IOException e) {e.printStackTrace();}
StringBuilder sb = new StringBuilder();
String line;
while((line = br.readLine()) != null){
sb.append(line);
}
String[] sentences = sb.toString().split("\\.");
for(String sentence:sentences){
String word = sentence.split(" ");
//Add word to sentence...
}
try{
br.close();
}catch(IOException e){
e.printStackTrace();
}
Okay so i have been solving this question through several techniques and one of the approach was above. however i was able to solve this with another approach as well which does not involve using Scanner class. This one was much more accurate and it gave me the exact output whereas in the above i was off by a few words and letters.
try {
input = new BufferedReader(new FileReader("file.txt"));
strLine = input.readLine();
while(strLine!= null){
String[] tokens = strLine.split("\\s+");
for (int i = 0; i < tokens.length; i++) {
if(strLine.isEmpty()){
continue;
}
String s = tokens[i];
wordsJoin += tokens[i] + " ";
wordCount += i;
int len = s.length();
String charString = s.replaceAll("[^a-zA-Z ]", "");
for(int k =0; k<charString.length(); k++){
currentChar = charString.charAt(k);
if(Character.isLetter(currentChar)){
lettersCount++;
}
}
if (s.charAt(len - 1) == '.' || s.charAt(len - 1) == '?' || s.charAt(len - 1) == '!') {
sentences.add(new Sentence(wordsJoin, wordCount));
sentCount++;
numOfWords += countWords(wordsJoin);
wordsJoin = "";
wordCount = 0;
}
}
strLine = input.readLine();
}
This might be useful for anyone doing the same problem or just need an idea of how to count letters, words and sentences from a text file.
I am new at Java so please bear with me.
I need help for one of my assignments again. Now it involves FileI/O.
The task that I have to do is:
I have to read a .csv file. The values that's inside the file are:
Christopher Lee,54.0
Stanley Wright,90.5
Oliver Stewart,75.8
Jessica Chang,34.65
As the task said, I must store the contents on the file into two arrays. One for the names, and one for the test marks. I should read the file at least twice, once to check how many names are in the file and a couple more times to actually read the file (to get the names and marks). So basically, I should have an array to store the names as Strings, and an array to store the marks of the student as real numbers.
I should line up the arrays (e.g.students[0] should store the name of the first student and marks[0] should store the mark of the first student
After I stored the contents of the .csv file into an array I have to display a following menu to the user. If the user pressed 1, it should prompt the user to enter the name of a student. If the user pressed 2, the program should exit. If the name exists, it should display the test mark for the student entered. If the student does not exist then I must output a message indicating so to the user, yet the program should not end but return to the above menu.
This is my code so far:
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String fileName = "file:///Documents/Java/marks_file.csv"; // Opens the file
String[] arrayString = new String[6]; // String length inside the file
int numLines, selection = 0;
double[] arrayReal = new double[6]; // Number length inside the file
numLines = getNumLines(fileName); // Gets the length of the file
readFile(arrayString, arrayReal, fileName);
// Selection menu
do
{
System.out.println("Select an option:");
System.out.println("1. Display mark");
System.out.println("2. Exit");
selection = sc.nextInt();
if (selection == 1)
{
System.out.println("Enter your full name");
{
// Do something
}
}
else if (selection == 2)
{
System.out.println("Goodbye");
}
}
while (selection == 1);
//System.out.println("Number of arrays: " + numLines);
}
// Method to get the length of the .csv file
public static int getNumLines(String fileName)
{
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String line;
int lineNum = 0;
try
{
fileStrm = new FileInputStream(fileName);
rdr = new InputStreamReader(fileStrm);
bufRdr = new BufferedReader(rdr);
line = bufRdr.readLine();
while (line != null)
{
lineNum = lineNum + 1;
line = bufRdr.readLine();
}
fileStrm.close();
}
catch (IOException e)
{
try
{
if (fileStrm != null)
{
fileStrm.close();
}
}
catch (IOException ex2)
{
// Nothing to do
}
System.out.println("Error in file processing: " + e.getMessage());
}
return lineNum;
}
// Method to store the values to arrays
public static void readFile(String[] arrayString, double[] arrayReal, String fileName)
{
Scanner sc = new Scanner(System.in);
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String line;
try
{
fileStrm = new FileInputStream(fileName);
rdr = new InputStreamReader(fileStrm);
bufRdr = new BufferedReader(rdr);
for (int i = 0; i < arrayString.length; i++)
{
line = bufRdr.readLine();
arrayString[i] = processString(line);
arrayReal[i] = processReal(line);
}
}
catch (IOException e)
{
try
{
if (fileStrm != null)
{
fileStrm.close();
}
}
catch (IOException ex2)
{
// Nothing to do
}
System.out.println("Error in file processing: " + e.getMessage());
}
}
// Stores the String lines to array
public static String processString(String line)
{
String string;
String[] lineArray = line.split(",");
return string = lineArray[0];
}
// Stores real number lines to array
public static double processReal(String line)
{
double real;
String[] lineArray = line.split(",");
return real = Double.parseDouble(lineArray[1]);
}
So far, I finished the "reading the file" part and processing the contents from a .csv file to an array.
I am not too sure how to prompt a user to search a string array from a .csv file. I tried looking at other sources, even at this website but I have no luck at all. I tried the Scanner.next() method but that doesn't work at all. Maybe I just missed something. Also, I am not sure if I did the "reading the file twice" right.
Am I on the right track? I am need of some guidance here
First of all I want to say that I'd use a Map instead of two arrays but I'll show you a solution using two arrays.
You were close to the solution. One of you problems is that scanner.next() only reads the input until the first whitespace. That's why you need to use scanner.nextLine(). This method reads the complete line. And the code could look something like that:
Solution with two arrays
Scanner sc = new Scanner(System.in);
System.out.print("Please enter name of student: ");
String name = sc.nextLine();
for(int i = 0; i < arrayString.length; i++){
if(name.equals(arrayString[i])) {
System.out.println(arrayReal[i]);
}
}
Solution with a HashMap
Initialize HashMap
HashMap<String, Double> hm = new HashMap<String, Double>();
Fill HashMap
hm.put("Christopher Lee", 54.0);
Print double value of student
System.out.print("Please enter name of student: ");
String name = sc.nextLine();
System.out.println(hm.get(name));
Instead of storing into arrays, I would rather tell you to pass the data to data into generic arraylist and then query the result using get() method.
You are making simple thing difficult.
Just use a HashMap with name as the keys and test-score as the values.
You open file
You read each line and translate each line to an entry of hash map
When a text is input to the console, you just get it from hash map, if existed return the value, if not then back to number 3
I'm writing a code that uses an input file called InvetoryReport.txt in a program I am supposed to create that is supposed to take this file, and then multiply two pieces of data within the file and then create a new file with this data. Also at the beginning of the program it is supposed to ask you for the name of the input file. You get three chances then it is to inform you that it cannot find it and will now exit, then stop executing.
My input file is this
Bill 40.95 10
Hammer 1.99 6
Screw 2.88 2
Milk .03 988
(The program is supposed to multiply the two numbers in the column and create a new column with the sum, and then under print another line like this
" Inventory Report
Bill 40.95 10 409.5
Hammer 1.99 6 11.94
Screw 2.88 2 5.76
Milk .03 988 29.64
Total INVENTORY value $ 456.84"
and my program I have so far is this
package textfiles;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.IOException;
public class LookOut{
double total = 0.0;
String getFileName(){
System.out.printIn("Type in file name here.");
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
out.println(str + "\n");
}
br.close();
} catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
return str;
}
void updateTotal(double d){
total = total + d;
}
double getLineNumber(int String_line){
String [] invRep = line.split(" ");
Double x = double.parseDouble(invRep[1]);
Double y = double.parseDouble(invRep[2]);
return x * y;
}
void printNewData(String = newData) {
PrintWriter pW = new PrintWriter ("newData");
pw.print(newData);
pw.close;
}
public static void main(String[] args){
String str = ("Get file name");
String str = NewData("InventoryReport/n");
File file = new File(str);
Scanner s = new Scanner(file);
while(s.hasNextLine()) {
String line = s.nextLine();
double data = getLineNumber(line);
update total(data);
NewData += line + " " + data + "/n";
Print NewData(NewData);
}
}
}
I'm getting multiple error codes that I just cant seem to figure out.
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
br.close();
} catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
Despite your best intentions you are in fact missing a '}'. Note that you haven't escaped the Try block before the catch. I imagine this is because you confused the closing } for the while statement as the closing } for the try block. Do this instead:
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
br.close();
}
}
catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
Also, your indentation is ALL OVER THE PLACE. This should be a lesson to you in why you should format your code properly! It is so easy to miss simple syntax errors like that if you're not formatting properly. It's also hard for others to read your code and figure out what's wrong with it.
I was playing around with such data structures in Java i figure out how to sort items on an Array or to an object. I want some words to be in spesific order I m able to use Bufferedreader HashMap, ArrayList. What i want to do is at any point after reading the first 42 lines, if some line is blank (i.e., a string of length 0) then output the line that occured 42 lines prior to that one. Also how can change this program to read the entire input one line at a time and then output the even numbered lines (starting with the first line, line 0) followed by the odd-numbered lines..I posted the code that i have so far.
public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
ArrayList<String> s= new ArrayList<String>();
String line;
int n = 0;
while ((line = r.readLine()) != null) {
s.add(line);
n++;
}
Collections.sort(s);
Iterator<String> i = s.iterator();
while (i.hasNext()) {
w.println(i.next());
}
}
public static void main(String[] args) {
try {
BufferedReader r;
PrintWriter w;
if (args.length == 0) {
r = new BufferedReader(new InputStreamReader(System.in));
w = new PrintWriter(System.out);
} else if (args.length == 1) {
r = new BufferedReader(new FileReader(args[0]));
w = new PrintWriter(System.out);
} else {
r = new BufferedReader(new FileReader(args[0]));
w = new PrintWriter(new FileWriter(args[1]));
}
long start = System.nanoTime();
doIt(r, w);
w.flush();
long stop = System.nanoTime();
System.out.println("Execution time: " + 10e-9 * (stop-start));
} catch (IOException e) {
System.err.println(e);
System.exit(-1);
}
}
I'm not sure I understand your question correctly, but I hope this can help:
for printing the line that occurred 42 lines before an empty line, you can just keep a counter and once you find a line with zero length, output the line which have the index counter - 42 ( I might have an off by one error here )
int n = 0;
while ((line = r.readLine()) != null) {
if (n > 42 && s.length == 0)
System.out.println(s[n-42]);
s.add(line);
n++;
}
and for printing the even lines first then the odd ones, you can try reading two lines at a time, save the first line into an ArrayList, and the second line into a different one.
at the end, one will have the odd lines and one will have the even lines.
and one more last note, instead of using this:
Iterator<String> i = s.iterator();
while (i.hasNext()) {
w.println(i.next());
}
you can simply use this:
for( String line : s)
System.out.println(line)