Not able to find out the number of Sentences in a File - java

I am writing a code to find out the number of sentences in a file.
My code is as :
try{
int count =0;
FileInputStream f1i = new FileInputStream(s);
Scanner sc = new Scanner(f1i);
while(sc.hasNextLine()){
String g = sc.nextLine();
if(g.indexOf(".")!= -1)
count++;
sc.nextLine();
}
System.out.println("The number of sentences are :"+count);
}
catch(Exception e) {
System.out.println(e);
}
I guess my logic is right to check for the number of periods. I wrote the above code which i think is right but it displays a javautilNoElementfound : No line foundexception . I tried some other logics but this one was the best understandable. But i am stuck here. I used google on that exception and it says that it is thrown when we iterate over something that has no element.But my file contains data. Is there some way this exception could have made way?? Or is there some other error? Hints are appreciated ! Thanks

You are calling sc.nextLine() two times inside the while loop that is why the error occurs.
Also your logic doesn't account for cases when there are 2 sentences on the same line.
You can try something like this:
int sentencesPerLine = g.split(".").length;
The loop should be:
while(sc.hasNextLine()){
String g = sc.nextLine();
if(g.indexOf('.')!= -1){//check if the line contains a '.' character
count += g.split("\\.").length; // split the line into an array of Strings using '.' as a delimiter
}
}
In the split(...) method I'm using "\\." instead of "." because . is a regex element and needs to be escaped.

Related

Input multiple lines using hasNextLine() is not working in the way that I expected it to

I'm trying to input multiple lines in java by using hasNextline() in the while loop.
Scanner sc = new Scanner(System.in);
ArrayList<String> lines = new ArrayList<>();
while (sc.hasNextLine()) {
lines.add(sc.nextLine());
System.out.println(lines)
}
The code is inside the main method. But the print method in thewhile loop doesn't print the last line of my input. Also, while loop doesn't seem to break.
What should I do to print whole lines of input and finally break the while loop and end the program?
Since an answer that explains why hasNextLine() might be giving "unexpected" result has been linked / given in a comment, instead of repeating the answer, I'm giving you two examples that might give you "expected" result. Whether any of them suits your needs really depends on what kind of input you need the program to deal with.
Assuming you want the loop to be broken by an empty line:
while (true) {
String curLine = sc.nextLine();
if (curLine.isEmpty())
break;
lines.add(curLine);
System.out.println(curLine);
}
Assuming you want the loop to be broken by two consecutive empty lines:
while (true) {
String curLine = sc.nextLine();
int curSize = lines.size();
String LastLine = curSize > 0 ? lines.get(curSize-1) : "";
if (curLine.isEmpty() && LastLine.isEmpty())
break;
lines.add(curLine);
System.out.println(curLine);
}
// lines.removeIf(e -> e.isEmpty());

print even words from string input?

I am in a beginners course but am having difficulty with the approach for the following question: Write a program that asks the user to enter a line of input. The program should then display a line containing only the even numbered words.
For example, if the user entered
I had a dream that Jake ate a blue frog,
The output should be
had dream Jake a frog
I am not sure what method to use to solve this. I began with the following, but I know that will simply return the entire input:
import java.util.Scanner;
public class HW2Q1
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a sentence");
String sentence = keyboard.next();
System.out.println();
System.out.println(sentence);
}
}
I dont want to give away the answer to the question (for the test, not here), but I suggest you look into
String.Split()
From there you would need to iterate through the results and combine in another string for output. Hope that helps.
While there will be more simpler and easier way to do this, I'll use the basic structure- for loop, if block and a while loop to achieve it. I hope you will be able to crack the code. Try running it and let me know if there is an error.
String newsent;
int i;
//declare these 2 variables
sentence.trim(); //this is important as our program runs on space
for(i=0;i<sentence.length;i++) //to skip the odd words
{
if(sentence.charAt(i)=" " && sentence.charAt(i+1)!=" ") //enters when a space is encountered after every odd word
{
i++;
while(i<sentence.length && sentence.charAt(i)!=" ") //adds the even word to the string newsent letter by letter unless a space is encountered
{
newsent=newsent + sentence.charAt(i);
i++;
}
newsent=newsent+" "; //add space at the end of even word added to the newsent
}
}
System.out.println(newsent.trim());
// removes the extra space at the end and prints newsent
you should use sentence.split(regex) the regular expression is going to describe what separate your worlds , in your case it is white space (' ') so the regex is going to be like this:
regex="[ ]+";
the [ ] means that a space will separate your words the + means that it can be a single or multiple successive white space (ie one space or more)
your code might look like this
Scanner sc= new Scanner(System.in);
String line=sc.nextLine();
String[] chunks=line.split("[ ]+");
String finalresult="";
int l=chunks.length/2;
for(int i=0;i<=l;i++){
finalresult+=chunks[i*2]+" ";//means finalresult= finalresult+chunks[i*2]+" "
}
System.out.println(finalresult);
Since you said you are a beginner, I'm going to try and use simple methods.
You could use the indexOf() method to find the indices of spaces. Then, using a while loop for the length of the sentence, go through the sentence adding every even word. To determine an even word, create an integer and add 1 to it for every iteration of the while loop. Use (integer you made)%2==0 to determine whether you are on an even or odd iteration. Concatenate the word on every even iteration (using an if statement).
If you get something like Index out of range -1, manipulate the input string by adding a space to the end.
Remember to structure the loop such that, regardless of the whether it is an even or odd iteration, the counter increases by 1.
You could alternatively remove the odd words instead of concatenation the even words, but that would be more difficult.
Not sure how you want to handle things like multiple spaces between words or weird non-alphabetically characters in the entry but this should take care of the main use case:
import java.util.Scanner;
public class HW2Q1 {
public static void main(String[] args)
{
System.out.println("Enter a sentence");
// get input and convert it to a list
Scanner keyboard = new Scanner(System.in);
String sentence = keyboard.nextLine();
String[] sentenceList = sentence.split(" ");
// iterate through the list and write elements with odd indices to a String
String returnVal = new String();
for (int i = 1; i < sentenceList.length; i+=2) {
returnVal += sentenceList[i] + " ";
}
// print the string to the console, and remove trailing whitespace.
System.out.println(returnVal.trim());
}
}

using split to get rid of regexp from an Arraylist

I am trying to create a spell checker, but before I can do so I must read in two separate files. The first (the dictionary), I did file. The second is a novel for which I must spell check. Problem is, I need to remove all special characters that are not letters (regexp?) from the novel. I am trying to use the string.split, but am having no luck. I am testing this one a small section of the novel, test2.
This is the section of code I have...
public static void readFileBook() {
File f = new File("test2.txt");
ArrayList<String> list2 = new ArrayList<String>();
try {
Scanner input = new Scanner(f);
int i = 0;
while (input.hasNext()) {
String oliver = input.next();
list2.add(oliver);
String[] oliverArray = oliver.split("[.#]");
System.out.println(list2.get(i));
i++;
}
} catch (IOException e) { //opening failed
e.printStackTrace();
}
}`enter code here`
I started small with the '.' and '#' symbols. The System.out is just to check if things are working (they aren't), but output still has symbols.
I know there is probably a more elegant way of doing this, but the instructor a specific thing in find.
Any help would be appreciated.
so in you code
String oliver = input.next();
list2.add(oliver);
String[] oliverArray = oliver.split("[.#]");
System.out.println(list2.get(i));
you are (line by line)
reading input into String oliver
adding oliver to a list
splitting oliver into oliverArray which never gets used
printing the string in the list at position i
How would you know if this is working or not?

Using Scanner count elements on line

If I am using Scanner in Java, how do I count the elements on the line so I know not to process the input if it doesn't have the required elements or continue to next line? All are integers. This is not homework.
Example input:
1 <-- ignore
1 2 3 <-- use this
1 2 <-- ignore
A Little bit late but alternatively, you can also use Scanner#findInLine to implement desired behavior here is a sample i wrote to test your input
Scanner s = new Scanner(new File("text"));
Pattern p = Pattern.compile("^(\\d+) (\\d+) (\\d+)$", Pattern.MULTILINE);
while(s.hasNextLine()){
if(s.findInLine(p)!=null){
//just printing the result. you can do needful here.
MatchResult result = s.match();
System.out.println("full line:" + result.group(0));
System.out.println("individuals");
for (int i=1; i<=result.groupCount(); i++)
System.out.println(result.group(i));
}
s.nextLine();
}
Hope this help someone :)
Read a line at a time, and split it into elements yourself.
while(scanner.hasNextLine())
String line = scanner.nextLine();
String[] elements = line.split(" ");
if(elements.length ==3) {
process(elements);
} else {
// deal with it somehow
}
}
... or with slightly different logic (since it returns null when it's done), you could use a BufferedReader.readLine()

How to grab a number from a text file, while ignoring the word in front of it?

So I have a .txt file with only this as the contents:
pizza 4
bowling 2
sleepover 1
What I'm trying to do is, for example in the first line, ignore the "pizza" part but save the 4 as an integer.
Here is the little bit of code I have so far.
public static void addToNumber() {
PrintWriter writer;
Int pizzaVotes, bowlingVotes, sleepOverVotes;
try {
writer = new PrintWriter(new FileWriter("TotalValue.txt"));
}
catch (IOException error) {
return;
}
// something like if (stringFound)
// ignore it, skip to after the space, then put the number
// into a variable of type int
// for the first line the int could be called pizzaVotes
// pizzaVotes++;
// then replace the number 4 in the txt file with pizzaVote's value
// which is now 5.
// writer.print(pizzaVotes); but this just overwrites the whole file.
// All this will also be done for the other two lines, with bowlingVotes
// and sleepoverVotes.
writer.close();
} // end of method
I am a beginner. As you can see my actual, functioning code is very short and I don't know to proceed. If anyone would be so kind as to point me in the right direction, even if you just give me a link to a site, it would be extremely helpful...
EDIT: I stupidly thought PrintWriter could read a file
It's pretty simple actually. All you need is a Scanner, and it's function nextInt()
// The name of the file which we will read from
String filename = "TotalValue.txt";
// Prepare to read from the file, using a Scanner object
File file = new File(filename);
Scanner in = new Scanner(file);
int value = 0;
while(in.hasNextLine()){
in.next();
value = in.nextInt();
//Do something with the value here, maybe store it into an ArrayList.
}
I have not tested this code, but it should work, but the value in the while loop is going to be the current value of the current line.
I don't fully understand your question, so comment if you want some clearer advice
Here is a common pattern you'll use in Java:
Scanner sc=new Scanner(new File(.....));
while(sc.hasNextLine(){
String[] line=sc.nextLine().split("\\s");//split the string up by writespace
//....parse tokens
}
// now do something
In your case, it seems like you want to do something like:
Scanner sc=new Scanner(new File(.....));
FrequencyCloud<String> votesPerActivity=new FrequencyCloud<String>()
while(sc.hasNextLine(){
String[] line=sc.nextLine().split("\\s");//split the string up by writespace
//if you know the second token is a number, 1st is a category you can do
String activity=line[0];
int votes=Integer.parseInt(line[1]);
while(votes>0){
votesPerActivity.incremendCloud(activity);//no function in the FrequencyCloud for mass insert, yet
votes--;
}
}
///...do whatever you wanted to do,
//votesPerActivity.getCount(activity) gets the # of votes for the activity
/// for(String activity:votesPerActivity.keySet()) may be a useful line too
FrequencyCloud: http://jdmaguire.ca/Code/JDMUtil/FrequencyCloud.java
String num = input.replaceAll("[^0-9]", " ").trim();
For sake of diversity this uses regular expressions.

Categories

Resources