Counting number of lines in .txt file Java - java

Hey I have problem with this simple program:
package werd;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
public class Werd {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream("ikso.txt"), "UTF-8"));
String line;
String[] tmp = null;
int slowa = 0;
int lines = 0;
while ((line = in.readLine())!= null){
lines++;
tmp = line.split("\\s");
System.out.println(line);
//System.out.println(line);
for(String s : tmp){
slowa++;
}
}
in.close();
System.out.println("Liczba wierszy to " +line+" a liczba slow w tekscie to " + slowa)
}
}
Problem is that the variable counting is not increasing. Moreover Netbeans telling me that variable limits is not used. I had glanced at similar questions as min on this page. Way of solving counting number of lines was similar to mine. I don't understand why it doesn't work...
Thanks

From the code you provided it seems you're printing line instead of lines.
The counting code looks correct.

Related

java - read user input and print line if it is a duplicate

So I'm learning about reading text files in java and I'm trying to write a program that reads user input one line at a time and outputs the current line if and only if it is a duplicate of some previous line. This is the part of code I'm struggling with and was wondering if I could get a push in the right direction. Right now it currently asks for user input, and when I write a line and press enter, the program ends without printing anything.
public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
Set<String> s = new HashSet<String>();
while(true) {
String line = r.readLine();
if(s.contains(line)) {
s.add(line);
}else {
break;
}
}
for (String text : s) {
w.println(text);
}
}
You can keep two mutable states, one for all the lines and one for duplicate lines.
Example below. (You can exit program on :q).
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
public class CheckDupes {
public static void main(String[] args) throws IOException {
Set<String> lines = new HashSet<String>();
Set<String> duplicateLines = new HashSet<String>();
BufferedReader stdReader =
new BufferedReader(new InputStreamReader(System.in));
String line = null;
while (!(line = stdReader.readLine()).equals(":q")) {
if (lines.contains(line)) {
duplicateLines.add(line);
} else {
lines.add(line);
}
}
duplicateLines.forEach(l -> System.out.println(l));
}
}
Input/ Output
love is great
weather is good
software is version 4
weather is good
love is great
:q
weather is good
love is great

Cannot get out the input from console after a new line character in BufferedReader

Following is the coding I currently have:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class DictionarySearch{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = "";
List<String> dicts = new ArrayList<>();
line = br.readLine();
while (line != null && !(line.trim().isEmpty())) {
dicts.add(line);
line = br.readLine();
}
System.out.println("Done adding");
String partial = br.readLine();
System.out.println("Partial: " + partial);
}
}
When I run my test, I place following values into console:
A
B
C
When I debug the code, dicts successfully contains String A and String B, but I cannot make partial equals to C. Is it means I using the wrong class to read the input from the console?

Read a line and push into a line-stack until the end of file

I have to do a program and unfortunately I have no idea where to start. It's like we were doing very basic coding and then my teacher went on maternity leave and our substitute thinks we are further along then we actually are. I know how to ready from a file, but I do not know how to put the line into a stack from there.
These are the instructions
1) Read a line and push into a line-stack until the end of file 2) While line_stack is not empty a. Pop one element out and process the following i. Split elements in this line (i.e. numbers) using StringTokenzier ii. Push all numbers into number-stack iii. While number_stack is not empty 1. Pop a number 2. Print a character using that ascii number
If I understand the problem correctly you need to:
Represent a line as a java.lang.String.
Then using java.util.Stack create a Stack< String> and put all the lines there.
Use java.util.StringTokenizer to split each line into multiple parts. Each part will be a String itself.
Turn each part of the line into a number using Integer.valueOf(String)
Put all the numbers into a Stack< Integer>.
Print the right character for each number by casting integer value to char.
I think this may be the solution for your problem:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Stack;
import java.util.StringTokenizer;
public class LinesProcessor {
private static Stack<String> readLinesFromFile(String fileName) throws IOException {
Stack<String> lines = new Stack<>();
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)))) {
String line = null;
while ((line = br.readLine()) != null) {
lines.push(line);
}
}
return lines;
}
private static void processNumbers(Stack<Integer> stackOfNumbers) {
while (!stackOfNumbers.empty()) {
Integer number = stackOfNumbers.pop();
System.out.print((char) number.intValue());
}
}
private static void processLine(String line) {
StringTokenizer tokenizer = new StringTokenizer(line, " ");
Stack<Integer> stackOfNumbers = new Stack<>();
while (tokenizer.hasMoreTokens()) {
Integer number = Integer.valueOf(tokenizer.nextToken());
stackOfNumbers.push(number);
}
processNumbers(stackOfNumbers);
}
private static void processLines(Stack<String> stackOfLines) {
while (!stackOfLines.empty()) {
String currentLine = stackOfLines.pop();
processLine(currentLine);
}
}
public static void main(String[] args) throws IOException {
if (args.length < 1) {
System.out.println("Name of file missing");
System.exit(1);
}
String fileName = args[0];
Stack<String> stackOfLines = readLinesFromFile(fileName);
processLines(stackOfLines);
}
}

how to calculate difference bewteen each line number like excel in javascript or java

I have a given list of data, which contains the following records, the records are for give fiscal year, from jan-decemebr
Date order
1/1/10 787668
1/2/10 787789
1/3/10 788031
1/4/10 788240
.............
.............
.............
12/29/10 839832
12/30/10 839965
12/31/10 840238
In excel it's easy to get the difference between two given consecutive, date create a formula and drag it and it will display the difference
I have to the same thing in Node.js or Java, is there any Java API or java script, node_module present so that i can just the input as orders and the output will be the difference between two consecutive data, the sample example
Order diff
787668 119
787787 161
787948 32
787980 114
788094 30
i have written the following for the Java API
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.LinkedList;
import java.util.List;
public class DiffrenceCalculator {
public static void main(String[] args) throws Exception {
FileReader fileReader = new FileReader(new File("date_column"));
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> ls = new LinkedList<String>();
String line;
StringBuilder builder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
ls.add(line);
}
for (int i = 0; i < ls.size(); i++) {
int k = i + 1;
if (k >= ls.size()) {
break;
}
System.out.println(Integer.valueOf(ls.get(k))
- Integer.valueOf(ls.get(i)));
}
}
}

Java: deleting text in an csv which starts with --

I am loading a csv file and kept alive without closing BufferReader. Now I want to delete all lines which starts with -- and save that csv in a temp CSV. Anybody have an idea how I can do this find only c# code.
I tried to fix with regular expression but I failed.
An example of the csv:
-- DDL- "T453453 "."BMG"
-- DDL- "T423342 "."BMG234"
CREATE TABLE "T453453 "."BMG"
-- DDL- "T42234234 "."BMG236"
So it works but i have the last problem how i can add \n (Newline) cause if i debug this code i get the text in one line.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
public class CsV {
public static String Read() throws IOException{
return new String(Files.readAllBytes(Paths.get("C://Users//myd//Desktop//BW//BWFormated.csv")));
}
public static void main(String[] args) throws IOException {
File inputFile = new File("C://Users//myd//Desktop//BW//BWtest.csv");
File tempFile = new File("C://Users//myd//Desktop//BW//BWFormated.csv");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = "--";
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.startsWith(lineToRemove)) continue;
writer.write(currentLine);
}
writer.close();
boolean successful = tempFile.renameTo(inputFile);
System.out.println(Read());
}
}
You can check each line, if it begins with -- using String.startsWith() method.
If so, read the next line and if the line has content you want to make other things with, you can put it into a list. Maybe like this:
String line;
List<String> list = new ArrayList<String>();
while((line = reader.readLine()) != null)
{
if(line.startsWith("--"))
continue;
list.add(line);
}
for(int i = 0; i < list.length; i++)
{
line = list.get(i);
// use regular expressions to extract the data you want to convert into CSV format
}
Hint: I didn't check my syntax, so it could be, that it won't be compiled ;-)
Use the Pattern class for regular expressions and maybe this tutorial will help you.
Good luck!
EDIT
Extend your while-loop to the following, which allows you to add new lines, too:
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.startsWith(lineToRemove))
continue;
writer.write(currentLine);
writer.newLine(); // Writes a line separator.
}
Read the docs to the newLine() method.

Categories