Pretty much I'm trying to write a program that counts the words in a text file AND count how many lines as well but I keep getting the no line error.
import java.util.*;
import java.io.*;
public class input {
public static void main(String[] args) throws FileNotFoundException {
String name;
int lineCount = 0;
int wordCount = 0;
File input = new File("C:\\Users\\Ceri\\workspace1\\inputoutput\\src\\inputoutput\\lab1task3.txt");
Scanner in = new Scanner(input);
while(in.hasNextLine()){
while(in.hasNext()){
wordCount++;
in.next();
}
lineCount++;
in.nextLine();
}
System.out.println(lineCount);
System.out.println(wordCount);
in.close();
}
}
The issue lays withing the while(in.hasnextline()) loop.
That is because your inner while loop exhasts all the input characters from your scanner. in.hasNext() does not stop at new line characters.
You are incorrectly implementing hasNextLine() and hasNext() such that you have read through all the tokens in your scanner within your inner while. An easier way to read every word and line would be to implement something like this:
int words = 0;
int lines = 0;
while(in.hasNextLine()) {
lines++;
String line = in.nextLine()
words += new StringTokenizer(line, " ,").countTokens();
}
You are reaching end of the file while looping through the inner loop. Once, it reaches the end of file, it will come out of inner loop. lineCount will be incremented and then, in.nextLine() will be executed. Buffer for Scanner's object is not having any value inside of it, hence you are getting this result.
Try this:
while(in.hasNextLine()){
String line = in.nextLine();
lineCount++;
String[] words = line.split(" ");
wordCount += words.length;
}
Do this
while(in.hasNextLine())
{
Scanner ins=new Scanner(in.nextLine());
while(ins.hasNext())
{
wordCount++;
ins.next();
}
lineCount++;
}
Related
I have the below code that is not reading or infinitely looping when a user inputs text using System.in. If I hard code the text into the Scanner variable it works fine so I am not sure what is wrong with the System.in portion of this code. Any help is appreciated.
import java.util.Scanner; // needed to use the Scanner class
public class HW2 {
static Scanner in = new Scanner(System.in);
public static void main(String [] args) {
System.out.println("Enter your line here");
int the =0;
int and =0;
int is = 0;
int was =0;
int noword =0;
while (in.hasNext()){
String word = in.next();
if (word.equals("the")){
the++;
}
else if( word.equals("and")){
and ++;
}
else if (word.equals("is")){
is++;
}
else if (word.equals("was")){
was++;
}
else noword++;
}
System.out.println("The number of occurrences of the was"+ the);
System.out.println("The number of occurrences of and was"+ and);
System.out.println("The number of occurrences of is was"+ is);
System.out.println("The number of occurrences of was was"+ was);
}
}
As has been mentioned, a Scanner attached to System.in will block while looking for more input. One way to approach this would be to read a single line in from the scanner, tokenize it, and then loop through the words that way. That would look something like this:
//...
String line = in.nextLine(); // Scanner will block waiting for user to hit enter
for (String word : line.split(" ")){
if (word.equals("the")) {
the++;
}
//...
You can always substitute one loop structure (for, while, do-while) for another. They all do the same thing, just with different syntax to make one a bit simpler to use than others depending on the circumstances. So if you want to use a while loop, you can do something like this:
// ...
String line = in.nextLine();
String[] tokens = line.split(" ");
int i = 0;
while (i < tokens.length){
String word = tokens[i];
if (word.equals("the")) {
the++;
}
// ...
i++;
} // end of the while loop
However, I'm of the opinion that a for loop is cleaner in the case of looping over a known set of data. While loops are better when you have an unknown dataset, but a known exit condition.
As System.in is always available while the program is running unless you close it. It will never exit the while loop. So you could add else if (word.equals("exit")) { break; }. This way, whenever you type 'exit' it will close the while loop and execute the code AFTER the while loop.
Depends, do you want to just read 1 line of text and then count the words individually?
Because is you want only one line you could take the input string using the Scanner library and split the string into individual words and apply the if-statement then. Something like:
public static void main(String [] args) {
System.out.println("Enter your line here");
int the =0;
int and =0;
int is = 0;
int was =0;
int noword =0;
String input = in.nextLine();
String words[] = input.split(" ");
for (String s : words) {
if (s.equals("the")){
the++;
} else if( s.equals("and")){
and++;
} else if (s.equals("is")){
is++;
} else if (s.equals("was")){
was++;
} else {
noword++;
}
}
System.out.println("The number of occurrences of the was: "+ the);
System.out.println("The number of occurrences of and was: "+ and);
System.out.println("The number of occurrences of is was: "+ is);
System.out.println("The number of occurrences of was was: "+ was);
}
This way you won't need a while loop at all. So it's more processor and memory efficient.
In this program, I am supposed to check if each word in the file "Paper" is in the file "dictionary". If the word is not in the file dictionary, it prints out ("Line #" "the word"). The problem in this code is the loop. I don't know to make the loop reset.
EX: a dictionary file has two words big and small
a paper file has a sentence his foot is small
The program will print
Line: 1: his
Line: 1: foot
Line: 1: is
import java.util.Scanner;
import java.io.*;
public class SpellCheck{
public static void main(String[] arg) throws FileNotFoundException{
Scanner readfile = new Scanner(new File("paper"));
String word = "";
int count = 0;
while(readfile.hasNextLine()){
String line = readfile.nextLine();
Scanner linescan = new Scanner(line);
String Scannedword = linescan.next();
word = Scannedword;
count++;
}
Scanner openDictionary = new Scanner(new File("Dictionary"));
String wordInDictionary = openDictionary.next();
if(word.equals(wordInDictionary)){
}else{
System.out.println("Line " + count + ": " + word);
openDictionary.close();
}
}
}
I would rather preprocess dictionary file.
while(readfile.hasNextLine()){
String line = readfile.nextLine();
Scanner linescan = new Scanner(line);
String Scannedword = linescan.next();
word = Scannedword;
count++;
}
Just like you have written here, make a hashset or whatever the container you'd like and copy over words in dictionary file. And, using another loop to do your task (check if the container contains the word you just read.) In this way, two loop are not nested so it will run O(n).
I have a simple code to understand which reads a file (input2.txt) and displays it.
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args ) throws Exception {
Scanner scanner = new Scanner(new File(args[0]) );
scanner.useDelimiter("\n\n");
String[] grid = scanner.next().split("\n");
scanner.close();
for(int row = 0; row < grid.length; row++) {
for(int col = 0; col < grid[row].length(); col++) {
System.out.print(grid[row].charAt(col) + " ");
}
System.out.println();
}
}
}
input.txt is
java Test input.txt is
What I don't understand is
scanner.useDelimiter("\n\n");
Why does it use two "\n\n" instead of one "\n"?
FYI, If I use scanner.useDelimiter("\n");
it doesn't work properly. This just read the first line from a file.
Your file contains newlines (\n) so setting delimiter to a single newline will cause next() to return the first line.
Since your files doesn't contain any blank lines, i.e. has no double newlines, next() will return the first token, which is the entire file content.
As to why someone chose \n\n? Who knows.
Also be aware that this won't work on Windows, where lines are separated by \r\n.
Setting the delimiter to \n\n will cause scanner.next() to return the entire file as one string, since there are no double new lines found. Setting the delimiter to anything that is never found would give the same behavior.
Next that string is split using split("\n") and the array will contain one entry per row from the file.
This can be written more cleanly like this
try (Scanner scanner = new Scanner(new File(args[0]))) {
while (scanner.hasNextLine()) {
String row = scanner.nextLine();
for (int col = 0; col < row.length(); col++) {
System.out.print(row.charAt(col) + " ");
}
System.out.println();
}
}
I don't understand why you are using split with a Scanner. The second makes what the first should.
Instead, use \n as a delimiter for your Scanner, but since you are using next(), this means you should iterate on the Scanner until there are no more to scan for.
The split is really making you lose all the interest of using a Scanner. You are just reading the whole file once and splitting it when it's all in-memory. This could cause memory exceptions with large files.
Untested but something like this should work:
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args ) throws Exception {
Scanner scanner = new Scanner(new File(args[0]) );
scanner.useDelimiter("\n");
while (scanner.hasNext()) {
String row = scanner.next();
for(int col = 0; col < row.length(); col++) {
System.out.print(row.charAt(col) + " ");
}
System.out.println();
}
scanner.close();
}
}
Case 1 : You use scanner.useDelimiter("\n\n");
"\n\n" is a delimiter which was not found in the file so the first scanner.next() will give you the whole file !
And when you use .split("\n") on the whole file it will give you a array of elements found in the file splitted by "\n" this somehow made you think that your code is working.
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args ) throws Exception {
Scanner scanner = new Scanner(new File(args[0]) );
scanner.useDelimiter("\n\n");
String[] grid = scanner.next().split("\n");
scanner.close();
for(int row = 0; row < grid.length; row++) {
for(int col = 0; col < grid[row].length(); col++) {
System.out.print(grid[row].charAt(col) + " ");
}
System.out.println();
}
}
}
Case 2: When you use scanner.useDelimiter("\n") scanner.next() returns you the first line as scanner has found a delimiter and is giving you the data line by line.
Now when you use scanner.next().split("\n"); the regex "\n" didn't match and again you got back the whole String that is the first row,which made you think your code isn't working.
If you want to read the file you should use scanner.hasNext() in a while loop as specified in some answer already.
By using the delimiter '\n\n' you tell the scanner to split tokens there. My assumption is that the input file is a Uninx style file (so line break is \n) which has two line breaks at the end or an empty line somewhere.
So the scanner.next() will basically return you a sting token up the the end (or empty line) and then splitt that by by line.
So a better way to do this would probably be:
Scanner scanner = new Scanner(new File(args[0]) );
scanner.useDelimiter("\n");
List<String> grid = new ArrayList<>();
while (scanner.hasNext()) {
grid(scanner.next());
}
scanner.close();
Your code will only handle the content of the file up to the point where there are two '\n\n'.
I have a program that reads a file. The file will be split into lines with the nextLine() method of scanner.
My file looks like this:
*#* lalala lalala lalaa lalala lalal la
x,v,m,k
221312, stringgg, pwd
...
*#* baba bababaa babababa
I want to go into a while loop when reading *#*, then the while should break when reaching the next *#*.
How can this be done?
Are you sure while should break? This will cause while to stop entirely. I think continue is better option, since it will just skip to next while iteration, i.e. it will skip current line.
while(...) {
String line = scanner.nextLine();
if(line.startsWith("#")) {
continue; // or break, if you're sure it's what you want
}
// your code
}
I hope this will help you
/* If I see the string first time I increase the variable n by one.
* If I see the string second time again I increase n by one, now
* n will be 2, If n is 2 I break the for loop ABC
*/
public static void main(String []args){
int n = 0;
String str;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String line = scanner.nextLine();
// System.out.println(line);
int count = line.length();
// System.out.print(count);
ABC:
for(int i=0; i<line.length()-2;i++){
str =line.substring(i, i+3);
if(str.equals("*#*")){
n++;
System.out.println(n);
while(n==2){
break ABC;
}
}
System.out.println(str);
}
}
I am trying to search the File for characters in Java language. For that I am using Scanner to scan the file.
Well to check the Heirarchy work, I am using System.out.print("Worked till here!"); so that I can check whether it is executed or not. I was able to execute the code till the last stage, but then I found that the essential boolean variable wasn't altered, which was under the condition to check whether there is a character match or not.
The file contents are as
Ok, here is some text!
Actually this file is created to test the validity of the java application
Java is my favourite programming language.
And I think I can score even more :)
Wish me luck!
However, no matter what I search it always prompts me to be false.
Here is the code I am using
public static void main (String[] args) throws IOException {
// Only write the output here!!!
System.out.print("Write the character to be found in the File: ");
Scanner sc = new Scanner(System.in);
String character = sc.next();
// Find the character
System.out.println("Searching now...");
getCharacterLocation(character);
// Close the resource!
sc.close();
}
The method call executed and the method is as
public static void getCharacterLocation (String character) throws IOException {
System.out.println("File found...");
File file = new File("res/File.txt");
Scanner sc = new Scanner(file);
int lineNumber = 0;
int totalLines = 0;
boolean found = false;
// First get the total number of lines
while(sc.hasNextLine()) {
totalLines++;
sc.nextLine();
System.out.println("Line looping! For Total Lines variable.");
}
int[] lineNumbers = new int[totalLines];
int lineIndex = 0;
System.out.println("Searching in each line...");
while(sc.hasNextLine()) {
// Until the end
/* Get each of the character, I mean string from
* each of the line... */
while(sc.hasNext()) {
// Until the end of line
String characterInLine = sc.next();
if(sc.findInLine(character) != null) {
found = true;
}
}
System.out.print(sc.nextLine() + "\n");
lineNumber++;
sc.nextLine();
}
System.out.println("Searching complete, showing results...");
// All done! Now post that.
if(found) {
// Something found! :D
System.out.print("Something was found!");
} else {
// Nope didn't found a fuck!
System.out.println("Sorry, '" + character +
"' didn't match any character in file.");
}
sc.close();
}
Never mind the extra usage of variables, and arrays. I would use it in further coding if I can get the character and set the value to true.
Here is the output of this program.
Initial Stage
This is the initial stage for that. I wrote Ok in the input field, you can see Ok is the very first character in the File too.
Final Stage
This is the result after the execution.
Any help in this?
You count lines and don't restart the scanner.
boolean found = false;
// First get the total number of lines
while(sc.hasNextLine()) {
totalLines++;
sc.nextLine();
System.out.println("Line looping! For Total Lines variable.");
}
int[] lineNumbers = new int[totalLines];
int lineIndex = 0;
System.out.println("Searching in each line..."); // <------
while(sc.hasNextLine()) {
add e.g.
UPDATED from the comment
sc.close();
sc = new Scanner(file);
before the next while(sc.hasNextLine())
You need to implement a way to string your characters together and check them against your input. It appears that you don't currently have a way to do this in your code.
Try building an array of characters with your scanner, and moving through and doing a check of your input vs the indexes. Or maybe there is a way to implement the tonkenizer class achieve this.
Put remember, what you are looking for is not a character, it is a string, and you need to keep this in mind when writing your code.
When you count your lines you use while(sc.hasNextLine()).
After this loop, your scanner is behind the last line, so when you go to your next loop while(sc.hasNextLine()) { it is never executed.
There are multiple problems with your code:
You Iterated through your scanner here:
while(sc.hasNextLine()) {
totalLines++;
sc.nextLine();
System.out.println("Line looping! For Total Lines variable.");
}
So after this you have to reset it again to read for further processing.
While searching for character you are having two loops:
while(sc.hasNextLine()) {
// Until the end
/* Get each of the character, I mean string from
* each of the line... */
while(sc.hasNext()) {
// Until the end of line
String characterInLine = sc.next();
if(sc.findInLine(character) != null) {
found = true;
}
}
Here you just need a single loop like:
while(sc.hasNextLine()) {
String characterInLine = sc.nextLine();
if(characterInLine.indexOf(character) != -1) {
found = true;
break;
}
}