while loop won't read file, or print out line java - java

I have a with the hentAntall method in my code below. It's supposed to find the search word inside a txt file. I don't get any sort of error. It just won't print out any of the two possible lines.
This method has to access a constructor first to get the search word, and then it has to find that search word in the txt file and add to count. The constructor gets the search word from another class. Like this new lolz("searchword").hentAntall();
(I apologize for the stupid naming in this program, but it's just a copy of one of my programs, and I'm just trying to correct it without screwing up the original.)
import java.io.File;
import java.util.Scanner;
public class lolz {
private String sokeord=null;
private int antall = 0;
// Constructor
lolz(String searchword) throws Exception{
this.sokeord = searchword;
}
//toString method, to print in the same format.
#Override
public String toString(){
return "\nSokeordet er: " + sokeord+ "\n";
}
// Gets the ammount of the searchword
public int hentAntall() throws Exception{
File file = new File("Hvorfor.txt");
Scanner readfile = new Scanner(file);
while (readfile.hasNextLine()){
String nextline = readfile.nextLine();
if (nextline.equalsIgnoreCase(sokeord)) {
antall ++;
System.out.println("Antallet av:" + sokeord + "er " + antall);
}
else {System.out.println("Error no such search word in the given text");}
}
return antall;
}
// void methode to increase the count of a searcheword.
void oekAntall() {
antall++;
}
}
This is the other class that calls on this method, and also give information to the constructor.
public class Main {
public static void main(String[] args) throws Exception {
new lolz("fungerer").hentAntall();
}}
Also tried some of the suggestions and they did not work, I only get a the message Process finished with exit code 0.

Your Issue:
You are trying to compare a Scanner variable with a String Variable?!!!
Explanation:
you try to compare content of Scanner which is
java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match
valid=true][need input=false][source
closed=false][skipped=false][group separator=\,][decimal
separator=.][positive prefix=][negative prefix=\Q-\E][positive
suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]
with content of a String variable.
You do not read the each line with following
if (readfile.equals(sokeord)) {
You Should have
if (readfile.nextLine().equals(sokeord)) {

Instead of:
readfile.equals(sokeord)
Which is comparing an instance of type Scanner with a String (never going to be true). You need to read a line and compare that.
String line = readfile.nextLine();
if(line.equals(sokeord)){

Add a main method to your class:
public static void main(String[] args)
{
hentAntall();
}
You will have to make hentAntall() static or create an instance of lolz class and call it that way.
Also change:
while (readfile.hasNext()){
if (readfile.nextLine().contains(sokeord)) {
You need to actually read the input and then check if sokeord exists in the line or not.

Your hentAntall method should be like this:
public int hentAntall() throws Exception {
File file = new File("Hvorfor.txt");
Scanner readfile = new Scanner(file);
while (readfile.hasNextLine()) {
String word = readfile.next();
if (word.contains(sokeord)) {
antall++;
System.out.println("Antallet av:" + sokeord + "er " + antall);
} else {
System.out
.println("Error no such search word in the given text: ");
}
}
readfile.close();
return antall;
}
Don't forget to close the Scanner resource to avoid leaks.

Related

Need to get a line from a file onto queue and not the whole file text

I'm having trouble properly getting one line of text at a time from a file onto a queue without taking the whole file into the queue. For example, I'd like only Write a program that reads a Java source file as an argument and produces an index of all identifiers in the file. For each identifier, print all lines in which it occurs. For simplicity, we will consider each string consisting only of letters, numbers, and underscores an identifier.
Declare a Scanner in for reading from the source file and call in.useDelimiter("[^A-Za-z0-9_]+") Then each call to next returns an identifier.
public class Main { to get added to the queue but instead the whole file text is put into the queue instead of a line at a time. Sorry if my question is unclear
// Write a program that reads a Java source file as an argument and produces an index of all
// identifiers in the file. For each identifier, print all lines in which it occurs. For simplicity,
// we will consider each string consisting only of letters, numbers, and underscores an identifier.
// Declare a Scanner in for reading from the source file and call in.useDelimiter("[^A-Za-z0-9_]+").
// Then each call to next returns an identifier.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class E_15 {
public static void main(String[] args) throws FileNotFoundException
{
// get scanner input from file
Scanner fileInput = new Scanner(new File ("C:/Users/ramir/IdeaProjects/PA_7/src/Main.java"));
Queue<String> test = new LinkedList<String>();
ArrayList<String> phrase = new ArrayList<String>();
/*
List<String> result = new ArrayList<String>();
Scanner s = new Scanner(is);
s.useDelimiter(delimiter);
*/
// Iterates till end of file
while (fileInput.hasNextLine())
{
// Here is the issue. Data will end up
// containing the whole file instead of only that line
String data = fileInput.nextLine();
Scanner in = new Scanner(data);
in.useDelimiter("[^A-Za-z0-9_]+");
// I believe around here or before is the issue that I'm having.
// It adds all the file instead of only that line
// Also trying to figure out how to display each line that it's displayed on
// What the first one should look like for example
// 0: public occurs in:
// public class Main {
// public static void main(String[] args) {
//System.out.println(data);
test.add(data);
while(in.hasNext())
{
// Getting each phrase/word into ArrayList
String token = in.next();
phrase.add(token);
}
in.close();
}
int index = 0;
// This part works fine
for(String num : phrase)
{
// printing the key
System.out.println(index + ": " + num + " occurs in:");
// printing the values
// This to print out what
for(String line : test)
{
System.out.println(line);
}
System.out.println();
++index;
}
}
}
// Just java class get file front
// This is fine
public class Main {
public static void main(String[] args) {
int a_1 = 100;
System.out.println(a_1);``
}
}
I'd like it to only show System.out.println(a_1) because the line that's it's on See This
. I'm also have trouble printing it in all the lines that occur.
import java.io.*;
import java.util.Scanner;
public class ReadLineByLineExample2
{
public static void main(String args[])
{
try
{
//the file to be opened for reading
FileInputStream fis=new FileInputStream("Demo.txt");
Scanner sc=new Scanner(fis); //file to be scanned
//returns true if there is another line to read
while(sc.hasNextLine())
{
System.out.println(sc.nextLine()); //returns the line that was skipped
}
sc.close(); //closes the scanner
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Try studying the above code. I hope it will help. Otherwise, you might need to open this link for more detail.

Running multiple replaceAll statements in Java

This is probably a stupidly easy question but it's been a long day.
I'm trying to remove the comments from a java program. To do this i'm trying to use replaceAll, but I'm not sure how to run all 3 of the statements on the file at the same time. Is there a way besides regex that I should be using here? Or is there an easy fix? Here is my code:
import java.io.*;
import java.util.*;
public class Ex13Ch6 {
public static void main(String args[]) throws FileNotFoundException {
File file = new File("killComment.txt");
Scanner s = new Scanner(file);
stripComments(s);
}
public static void stripComments(Scanner s) {
while(s.hasNext()) {
String input = s.nextLine();
String regex = "/*";
// Removes /* from the file
String change = input.replaceAll("/\\*", "");
// Removes */ from the file
String change2 = input.replaceAll("\\*/", "");
// Removes // from the file
String change3 = input.replaceAll("//", "");
System.out.println(change2);
}
}
}
Here is the text file:
// Name: Conner Murowchick
// Email: conner.murowchick#bellevuecollege.edu
// Program description:
/*
Write a method called flipLines that accepts a Scanner for an input
file and writes to the console the same file's contents with each
pair of lines reversed in order. If the file contains an odd number
of lines, leave the last line unmodified.
*/
// importing file and Scanner
import java.io.*;
import java.util.*;
import java.io.FileNotFoundException;
public class Ex7Ch6 {
public static void main(String[] args) throws FileNotFoundException{
// Calling the flipLines method
flipLines();
}
public static void flipLines() throws FileNotFoundException {
// Calls a new file, "jabberwocky.txt"
File file = new File("jabberwocky.txt");
// Scans the file "jabberwocky.txt" and creates a Scanner s to read it.
Scanner s = new Scanner(file);
// creates a new variable "noOfLines" that is an integer equal to 0
int noOfLines = 0;
// A while loop that checks if there is another line to scan.
while(s.hasNextLine()) {
// If there is another line to scan, the scanner goes to the next line
s.nextLine();
// The variable noOfLines increments while this loop runs.
noOfLines++;
}
// Creates a new scanner called s2 that reads the file "jabberwocky.txt"
Scanner s2 = new Scanner(file);
// A for loop that runs when i is less than half of the variable noOflines
for (int i=0; i < (noOfLines / 2); i++) {
// String called line1 that equals scanner s2 reading the next line of text
String line1 = s2.nextLine();
// String called line2 that equals scanner s2 reading the next line of text
String line2 = s2.nextLine();
// Prints the Second line first
System.out.println(line2);
// Prints the First line second
System.out.println(line1);
}
}
}
Your solution cannot work because it's losing the changes everytime.
Try:
// Removes /* from the file
String change = input.replaceAll("/\\*", "");
// Removes */ from the file
String change2 = change.replaceAll("\\*/", "");
// Removes // from the file
String change3 = change2.replaceAll("//", "");
You can even concat in one statement:
String change = input.replaceAll("/\\*", "").replaceAll("\\*/", "").replaceAll("//", "");
Anyway, this won't remove the comments, it will just "uncomment" some comments. As user202729 is suggesting, you need a parser to remove the multi line comments. As for the commented single lines, you need a regular expression more specific, like:
"/^[\s]*[/]+.*/"

How to parse int or double values from text file in java application

i want to copy specific value from text file to Arraylist in Java Application. This is my text file( which is stored in my desktop as test.text)
String name = carrot;
double unit_price = 200;
int unit = 10;
This value i want to store in Arraylist, which is present in my main application as follow:
package com.main;
import com.collection.Ingridient;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class FileReaderApp {
public static void main(String[] args) throws FileNotFoundException, IOException {
Ingridient i_one = new Ingridient();
ArrayList<Ingridient> db = new ArrayList<Ingridient>();
FileReader fin = new FileReader("/home/yati/Desktop/test");
Scanner src = new Scanner(fin);
// Read the ingridient from text file.
while (src.hasNext()) {
if (src.hasNext()) {
i_one.setName(src.next());
System.out.println("Name: " +src.next());
} else
if(src.hasNextDouble()) {
i_one.setUnit_price(src.nextDouble());
System.out.println("Unit Price: " +src.nextDouble());
}
else if (src.hasNextInt()) {
i_one.setUnit(src.nextInt());
System.out.println("Unit: " +src.nextInt());
} else {
System.out.println("File format error.");
return;
}
db.add(i_one);
}
fin.close();
}
}
Her, Ingridient class has following code:
package com.collection;
public class Ingridient {
String name;
Double unit_price;
int unit;
public Ingridient() {
name = null;
unit_price = null;
unit = 0;
}
public void setName(String name) {
this.name = name;
}
public void setUnit_price(Double unit_price) {
this.unit_price = unit_price;
}
public void setUnit(int unit) {
this.unit = unit;
}
}
My problem is that my application can store only name in Ingridient object and it cannot store any value in unit and unit_price. Obtained output is:
I know i am mistaking somewhere but i cannot solve this issue. Any Suggestion?
This should do it:
public static void main(String[] args) throws IOException {
String content = "String name = carrot;\ndouble unit_price = 200;\nint unit = 10;";
try (Scanner sc = new Scanner(content)) {
sc.useDelimiter("(;*\n*.+ .+ = )|;");
List<Incredient> incredients = new ArrayList<>();
while (true) {
Incrediend incredient = new Incredient();
if (sc.hasNext()) {
String name = sc.next();
incredient.setName(name);
System.out.println("Name: " + name);
} else {
break;
}
if (sc.hasNextDouble()) {
double unitPrice = sc.nextDouble();
incredient.setUnit_price(unitPrice);
System.out.println("Unit Price: " + unitPrice);
} else {
break;
}
if (sc.hasNextInt()) {
int unit = sc.nextInt();
incredient.setUnit(unit);
System.out.println("Unit: " + unit);
} else {
break;
}
incredients.add(incredient);
}
} catch (Exception e) {
e.printStackTrace();
}
}
This works because of the delimiter I've used (;*\n*.+ .+ = )|;.
This pice of regex just removes all the parts of the text file that you're not interested in saving.
There are a couple of problems with your approach, for example this:
i_one.setName(src.next());
System.out.println("Name: " +src.next());
Here, you're reading 2 tokens from the scanner because there are 2 calls to next(), if you want to use the same token for multiple things you should create a new variable to store it in (ex: String name = sc.next()).
The default delimiter that the Scanner is using is a single space and because of that, in your code, hasNextDouble() and hasNextInt() will never be true, all the numbers in the text file end with ;.
I'm not sure what you're trying to do here, it is kind of unusual to parse java code from a text file. If you can change the format of the text file, you should chose one that is easier to parse (CSV for example).
src.hasNext() selects every line you've got in your file, so it will never jump into one of the if/else conditions
I would also recommend using json as an input format ;)
while (src.hasNext()) {
if (src.hasNext()) {
it always true and another else {} sections inacessible
The structure of your text file is not very good for parsing the desired values.
If you're able to you should change it to something like
carrot,200,10
thus having all values of your desired ingredient at one line. Splitting this line at "," will give you all the values you need to instantiate your objects.
If you're not able to change the text format (because it's part of the task), you should read whole lines of the text file and interpret triples of them to get your objects. So you also can be sure that all the values you need are there.
your first if condition is wrong to get the output you need...
if (src.hasNext())
this condition will always satisfy as there will be a next object and your following else if conditions never execute. this can be seen in the output always printing the data from the sysout in the first if condition.
i have changed the code to work with startsWith method given by the string class. Hope it helps...
NOTE: before you parse it make sure you remove out those special characters if any. (Semi -colons etc.)
while (src.hasNext()) {
String input = src.next();
if (input.startsWith("name")) {
i_one.setName(input);
System.out.println("Name: " + input);
} else if (input.startsWith("unit_price")) {
i_one.setUnit_price(Double.parseDouble(input));
System.out.println("Unit Price: " + input);
} else if (input.startsWith("unit")) {
i_one.setUnit(Integer.parseInt(input));
System.out.println("Unit : " + input);
} else {
System.out.println("File format error.");
return;
}
db.add(i_one);
}
If the structure of the text file is always the same you can use the contains method of the string class. Example:
public class FileReaderApp {
public static void main(String[] args) throws FileNotFoundException, IOException {
Ingridient i_one = new Ingridient();
ArrayList<Ingridient> db = new ArrayList<Ingridient>();
try(BufferedReader br = new BufferedReader(new FileReader("/home/yati/Desktop/test.txt"))) {
String line ;
while ((line = br.readLine())!=null) {
String [] splited;
if(line.contains("String name")){
splited= line.split(" ");
i_one.setName(splited[splited.length-1].replace(";", ""));
System.out.println(i_one.name);
}
else if(line.contains("double unit_price")){
splited= line.split(" ");
i_one.setUnit_price(Double.parseDouble(splited[splited.length-1].replace(";", "")));
System.out.println(i_one.unit_price);
}
else if(line.contains("int unit")){
splited= line.split(" ");
i_one.setUnit(Integer.parseInt(splited[splited.length-1].replace(";", "")));
System.out.println(i_one.unit);
}
}
}
db.add(i_one);
}
}

How to search a word in file in java

I am trying to search a string in a file in java and this is what, I tried . In the below program I am getting output as No Data Found and I am sure that the file has the word which I am searching
import java.io.*;
import java.util.Scanner;
public class readfile {
static String[] list;
static String sear = "CREATE";
public void search() {
Scanner scannedFile = new Scanner("file.txt");
while (scannedFile.hasNext()) {
String search = scannedFile.next();
System.out.println("SEARCH CONTENT:"+search);
if (search.equalsIgnoreCase(sear)) {
System.out.println("Found: " +search);
}
else {
System.out.println("No data found.");
}
}
}
public static void main (String [] args) throws IOException {
readfile read = new readfile();
read.search();
}
}
Don't do:
search.equalsIgnoreCase(sear)
Try:
search.toUpperCase().contains(sear)
I think the search is the whole String of the File, so you never would become true with equals.
Use nextLine() instead of next() and then use split. Like this :
What's the difference between next() and nextLine() methods from Scanner class?
Difference :
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
Use following code :
String search = scannedFile.nextLine();
String[] pieces = data.split("\\s+");
for(int i=0; i<pieces.length(); i++)
{
if(pieces[i].equalsIgnoreCase(sear))
{
System.out.println("Found: " +search);
}
else
{
System.out.println("No data found.");
}
}
Ok, here is my understanding of your program.
You search in the file file.txt the word CREATE.
To do so, you read each word in the file and if it is CREATE you print Found create.
The issue here is that for every word in the file, if it isn't CREATE you print No data found.
Instead you should wait for the end of the file and then if you haven't found it you will print the error message.
Try this :
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class readfile {
static String[] list;
static String sear = "CREATE";
public void search() throws IOException {
List<String> saveAllLinesForRewriting = new ArrayList<String>();
// Need to read file line by line
BufferedReader bufferedReader = new BufferedReader(new FileReader("file.txt"));
String saveLine;
while ((saveLine = bufferedReader.readLine()) != null) {
saveAllLinesForRewriting.add(saveLine);
}
bufferedReader.close();
// Check if your word exists
if (saveAllLinesForRewriting.toString().contains(sear)) {
System.out.println("Found: " + sear);
} else {
System.out.println("No data found.");
}
}
public static void main(String[] args) throws IOException {
readfile read = new readfile();
read.search();
}
}
Instead of reading file using scanner, first create a file resource to read by adding the below line
File file = new File("Full Path of file location");
before
Scannner scannedfile = new Scanner("file.txt");
and change the above line to
Scanner scannedfile = new Scanner(file);
rest your code is working fine.
The problem is that the scanner is scanning the String "file.txt" and not the file.
To fix this you have to do what amit28 says. Your finally code is as follows
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class readfile {
static String[] list;
static String sear = "CREATE";
public void search() {
File f = new File("file.txt");
Scanner scannedFile;
try {
scannedFile = new Scanner(f);
while (scannedFile.hasNext()) {
String search = scannedFile.next();
System.out.println("SEARCH CONTENT:"+search);
if (search.equalsIgnoreCase(sear)) {
System.out.println("Found: " +search);
}
else {
System.out.println("No data found.");
}
}
} catch (FileNotFoundException e) {
// FIXME Auto-generated catch block
e.printStackTrace();
}
}
public static void main (String [] args) throws IOException {
readfile read = new readfile();
read.search();
}
}

Java not detecting file contents

I'm having difficulty figuring out why this isn't working. Java simply isn't executing the while loop, file apparently does not have a next line.
fileName = getFileName(keyboard);
file = new Scanner (new File (fileName));
pass = true;
String currentLine;
while (file.hasNextLine()) {
currentLine = file.nextLine();
System.out.println(reverse(currentLine));
}
Here is the file I am testing this with. I got it to work with the first few paragraphs but it seems to simply stop working...:
Jabberwocky
'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.
"Beware the Jabberwock, my son!
The jaws that bite, the claws that catch!
Beware the Jubjub bird, and shun
The frumious Bandersnatch!"
He took his vorpal sword in hand:
Long time the manxome foe he soughtó
So rested he by the Tumtum tree,
And stood awhile in thought.
And as in uffish thought he stood,
The Jabberwock, with eyes of flame,
Came whiffling through the tulgey wood,
And burbled as it came!
One, two! One, two! and through and through
The vorpal blade went snicker-snack!
He left it dead, and with its head
He went galumphing back.
"And hast thou slain the Jabberwock?
Come to my arms, my beamish boy!
O frabjous day! Callooh! Callay!"
He chortled in his joy.
'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.
——from Through the Looking-Glass, and What Alice Found There (1872).
/*
* Lab13a.java
*
* A program that prompts the user for an input file name and, if that file exists,
* displays each line of that file in reverse order.
* Used to practice simple File I/O and breaking code up into methods as well as a first
* step to implementing Lab13b.java - reversing the entire file and Lab13c.java writing
* output to a separate output file.
*
* #author Benjamin Meyer
*
*/
package osu.cse1223;
import java.io.*;
import java.util.*;
public class Lab13a {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String fileName = "";
Scanner file;
boolean pass = false;
while (!pass) {
try {
fileName = getFileName(keyboard);
file = new Scanner (new File (fileName));
pass = true;
String currentLine;
while (file.hasNextLine()) {
currentLine = file.nextLine();
System.out.println(reverse(currentLine));
}
}
catch (FileNotFoundException e) {
System.out.println("There was a problem reading from " + fileName);
System.out.println("Goodbye.");
return;
}
}
}
// Given a Scanner as input prompts the user to enter a file name. If given an
// empty line, respond with an error message until the user enters a non-empty line.
// Return the string to the calling program. Note that this method should NOT try
// to determine whether the file name is an actual file - it should just get a
// valid string from the user.
private static String getFileName(Scanner inScanner) {
boolean pass = true;
String fileName = "";
while (pass) {
System.out.print("Enter an input name: ");
fileName = inScanner.nextLine();
if (fileName.length()!=0) {
pass = false;
}
else {
System.out.println("You cannot enter an empty string.");
}
}
return fileName;
}
// Given a String as input return the reverse of that String to the calling program.
private static String reverse(String inString) {
if (inString.length()==0) {
return "";
}
String reversed = "" + inString.charAt(inString.length()-1);
for (int x = inString.length()-2; x>=0; x--) {
reversed = reversed + inString.charAt(x);
}
return reversed;
}
}
The issue might lie in your implementation of your functions getFilename() or reverse(). Since you have stated that you got it to work with a few of the paragraphs I doubt that your program is failing due to your file handling. It might be in the logic you are using to reverse the strings in the file that is causing the issue.

Categories

Resources