So I'm trying to look at an input, and count words that fit a certain criteria (or rather, excluding words that I don't want to count). The error is in the following code:
BufferedReader br;
BufferedWriter bw;
String line;
int identifiers = 0;
boolean count = false;
try
{
br = new BufferedReader(new FileReader("A1.input"));
line = br.readLine();
while(line != null)
{
StringTokenizer t = new StringTokenizer(line);
String word;
System.out.println(t.countTokens()); //for testing, keeps printing 6
for(int c = 0; c < t.countTokens(); c++)
{
word = t.nextToken();
count = true;
if(Character.isDigit(word.charAt(0))) //if word begins with a number
{
count = false; //do not count it
}
if(count == true)
{
for(String s : keywords)
{
if(s.equals(word)) //if the selected word is a keyword
{
count = false; //do not count it
}
}
}
System.out.println(word); //testing purposes
}
word = t.nextToken();
}
Here is the input file:
INT f2(INT x, INT y )
BEGIN
z := x*x - y*y;
RETURN z;
END
INT MAIN f1()
BEGIN
INT x;
READ(x, "A41.input");
INT y;
READ(y, "A42.input");
INT z;
z := f2(x,y) + f2(y,x);
WRITE (z, "A4.output");
END
As stated in the comments in the code above, the first println statement prints 6 repeatedly (indicating to me that the while loop is endlessly repeating). The second "testing purposes" println statement continuously prints INT f2(INT x repeatedly.
It looks like you're never actually reading the next line of the file. Change this bit:
try
{
br = new BufferedReader(new FileReader("A1.input"));
line = br.readLine();
while(line != null)
{
to this:
try
{
br = new BufferedReader(new FileReader("A1.input"));
while((line = br.readLine()) != null)
{
Your use of while() is evaluating the current line only; thus, it's never null. Change it to if().
Related
I have a problem with my java program. I have to read lines from a file, the form of these lines is:
1#the^cat#the^dog#the^bird#^fish#bear
2#the^cat#the^dog#the^bird#^fish#bear
and print all, accept the "#" and "^" at textfields in my GUI. The "^" must appear in case there in not article. For exaple ^fish, i have to print it as ^fish but the^dog i have to print the dog.
As far i can read and print the lines in the textfields but i can't find a way to skip the "^" between the words.
Here is my code:
try {
FileReader file = new FileReader("C:\\Guide.txt");
BufferedReader BR = new BufferedReader(file);
boolean eof = false;
int i=0;
while (!eof) {
String line = BR.readLine();
if (line == null)
eof = true;
else {
i++;
System.out.println("Parsing line "+i+" <"+line+">");
String[] words = line.split("#");
if (words.length != 7) continue;
number=words[0];
onomastiki=words[1];
geniki=words[2];
aitiatiki=words[3];
klitiki=words[4];
genos=words[5];
Region=words[6];
E = new CityEntry(number,onomastiki,geniki,
aitiatiki,klitiki,
genos,Region);
Cities.add(E);
}
You can try something like this.
FileReader file = new FileReader("C:\\\\Users\\\\aq104e\\\\Desktop\\\\text");
BufferedReader BR = new BufferedReader(file);
boolean eof = false;
int i = 0;
while (!eof) {
String line = BR.readLine();
if (line == null)
eof = true;
else {
i++;
System.out.println("Parsing line " + i + " <" + line + ">");
String[] words = line.split("#");
for (int j = 0; j < words.length; j++) {
if(words[j].contains("^")) {
if(words[j].indexOf("^") == 0) {
// write your code here
//This is case for ^fish
}else {
// split using ^ and do further manipulations
}
}
}
}
}
Let me know if this works for you.
That is gonna work, but it is not best way)
foreach(String word : words){
if(word.contains"the"){
word.replace("^"," ");
}
}
Is there a way in Java to know the number of lines of a file chosen?
The method chooser.getSelectedFile().length() is the only method I've seen so far but I can't find out how to find the number of lines in a file (or even the number of characters)
Any help is appreciated, thank you.
--update--
long totLength = fc.getSelectedFile().length(); // total bytes = 284
double percentuale = 100.0 / totLength; // 0.352112676056338
int read = 0;
String line = br.readLine();
read += line.length();
Object[] s = new Object[4];
while ((line = br.readLine()) != null)
{
s[0] = line;
read += line.length();
line = br.readLine();
s[1] = line;
read += line.length();
line = br.readLine();
s[2] = line;
read += line.length();
line = br.readLine();
s[3] = line;
read += line.length();
}
this is what I tried, but the number of the variable read at the end is < of the totLength and I don't know what File.length() returns in bytes other than the content of the file.. As you can see, here i'm trying to read characters though.
Down and dirty:
long count = Files.lines(Paths.get(chooser.getSelectedFile())).count();
You may find this little method handy. It gives you the option to ignore counting blank lines in a file:
public long fileLinesCount(final String filePath, boolean... ignoreBlankLines) {
boolean ignoreBlanks = false;
long count = 0;
if (ignoreBlankLines.length > 0) {
ignoreBlanks = ignoreBlankLines[0];
}
try {
if (ignoreBlanks) {
count = Files.lines(Paths.get(filePath)).filter(line -> line.length() > 0).count();
}
else {
count = Files.lines(Paths.get(filePath)).count();
}
}
catch (IOException ex) {
ex.printStackTrace();
}
return count;
}
You could use the JFileChooser to select a file, than open the file using a file reader and as you iterate over the file just increment a counter, like this...
while (file.hasNextLine()) {
count++;
file.nextLine();
}
I'm trying to make a compressor for TextFiles and I get stuck at replacing characters.
This is my code:
compress.setOnAction(event ->
{
String line;
try(BufferedReader reader = new BufferedReader(new FileReader(newFile)))
{
while ((line = reader.readLine()) != null)
{
int length = line.length();
String newLine = "";
for (int i = 1; i < length; i++)
{
int c = line.charAt(i);
if (c == line.charAt(i - 1))
{
}
}
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
});
So what I want to do is: I want to find all the words where two characters are equal, if they are aside (Like 'Took'). When the if statement is true, I want to replace the first letter of the two equals characters, so it would look like: 'T2ok'.
I've tried a lot of things and I get an ArrayOutOfbounds, StringOutOfbounds, and so on, all the time...
Hope someone has a great answer :-)
Regards
Create a method that compress one String as follows:
Loop throu every character using a while loop. Count the duplicates in another nested while loop that increments the current index while duplicates are found and skips them from being written to output. Additionally this counts their occurence.
public String compress(String input){
int length = input.length(); // length of input
int ix = 0; // actual index in input
char c; // actual read character
int ccounter; // occurrence counter of actual character
StringBuilder output = // the output
new StringBuilder(length);
// loop over every character in input
while(ix < length){
// read character at actual index then inc index
c = input.charAt(ix++);
// we count one occurrence of this character here
ccounter = 1;
// while not reached end of line and next character
// is the same as previously read
while(ix < length && input.charAt(ix) == c){
// inc index means skip this character
ix++;
// and inc character occurence counter
ccounter++;
}
// if more than one character occurence is counted
if(ccounter > 1){
// print the character count
output.append(ccounter);
}
// print the actual character
output.append(c);
}
// return the full compressed output
return output.toString();
}
Now you can use this method to create a file input to output stream using java8 techniques.
// create input stream that reads line by line, create output writer
try (Stream<String> input = Files.lines(Paths.get("input.txt"));
PrintWriter output = new PrintWriter("output.txt", "UTF-8")){
// compress each input stream line, and print to output
input.map(s -> compress(s)).forEachOrdered(output::println);
} catch (IOException e) {
e.printStackTrace();
}
If you really want to. You can remove the input file and rename the output file afterwards with
Files.move(Paths.get("output.txt"), Paths.get("input.txt"),StandardCopyOption.REPLACE_EXISTING);
I think this is the most efficient way to do what you want.
try this:
StringBuilder sb = new StringBuilder();
String line;
try(BufferedReader reader = new BufferedReader(new FileReader(newFile)))
{
while ((line = reader.readLine()) != null)
{
if (!line.isEmpty()) {
//clear states
boolean matchedPreviously = false;
char last = line.charAt(0);
sb.setLength(0);
sb.append(last);
for (int i = 1; i < line.length(); i++) {
char c = line.charAt(i);
if (!matchedPreviously && c == last) {
sb.setLength(sb.length()-1);
sb.append(2);
matchedPreviously = true;
} else matchedPreviously = false;
sb.append(last = c);
}
System.out.println(sb.toString());
}
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
This solution uses only a single loop, but can only find occurrences of length 2
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)
I have a DB that usually generates a file with 3000 lines, actually I want to count the number of LAYERID(s)
My DB file is like this :
CREATE TRMD=GFT,LAYID=LY_00,USFGN=DISABLED;
CREATE BUTYP=ACB8T,RAAT=FALSE,GBPATH=AAP4,GTXT=12;
CREATE TRMD=GFT,LAYID=LY_00,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_01,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_01,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_02,USFGN=DISABLED;
CREATE BUTYP=ACB9T,RAAT=TRUE,GBPATH=AAP4,GTXT=32;
CREATE TRMD=GFT,LAYID=LY_00,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_01,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_02,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_03,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_03,USFGN=DISABLED;
CREATE BUTYP=ACB2T,RAAT=TRUE,GBPATH=AAP4,GTXT=1;
CREATE TRMD=GFT,LAYID=LY_00,USFGN=DISABLED;
CREATE BUTYP=ACB8T,RAAT=FALSE,GBPATH=AAP4,GTXT=2;
CREATE TRMD=GFT,LAYID=LY_00,USFGN=DISABLED;
CREATE BUTYP=ACB8T,RAAT=TRUE,GBPATH=AAP4,GTXT=3;
if we just have "LAYID=LY_00" (like the first line) we must ignore it, but if under the "LAYID=LY_00" be "LAYID=LY_01 and ..." (like the third line) we must count "LAYID=LY_00" and others layerids,for example in line 3 till line 6 we have 4 Layeids
LAYID=LY_00
LAYID=LY_01
LAYID=LY_01
LAYID=LY_02
So count is 4 and if we want to count all of them we have 9, As I said before, if we just have
LAYID=LY_00 simillar line 1 we ignore it.
Also I wrote this method for read line by line :
public void execToken(File f) throws Exception {
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
while ((line = br.readLine()) != null) {
StringTokenizer strt = new StringTokenizer(line, ";");
while (strt.hasMoreTokens()) {
String token = strt.nextToken();
layerSupport(token);
}
}
}
and, I know the below method is not true and complete yet, but it's maybe useful for you
public void layerSupport(String token){
if(token.startsWith("CREATE TRMD") && !token.contains("LAYID=LY_00"))
System.out.println(token) ;
}
many thanks for your help ...
public int execToken(File f) throws Exception
{
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
int count = 0;
Pattern layID = Pattern.compile("LAYID=LY_\\d+");
Matcher matcher = null;
boolean isSingle = true;
while ((line = br.readLine()) != null)
{
if(line.contains("LAYID=LY_00"))
{
isSingle = false;
continue;
}
matcher = layID.matcher(line);
if(matcher.find())
{
count++;
if(!isSingle)
count++;
}
isSingle = true;
}
return count;
}
try this.it remembers if previous line contains LAYID=LY_00 and increments count twice in next iteration, if LAYID=LY_<digits> was found and isSingle is false.
Something like that:
public int execToken(File f) throws Exception {
BufferedReader br = new BufferedReader(new FileReader(f));
int count = 0;
String line;
String previousLine = "";
while ((line = br.readLine()) != null) {
if (line.startsWith("CREATE TRMD")) {
if (!previousLine.isEmpty()) {
count += (previousLine.contains("LAYID=LY_00") ? 2 : 1);
}
previousLine = line;
} else {
previousLine = "";
}
}
return count;
}
Not tested.