Hi I'm writing a program that will analyse a block of text, specifically reading a file and counting the number of lines, words and numbers inside that file.
I have tried count the number of lines in a separate class within a method and then tried to call that method in the main class to print the total number of lines in the file, however this does not work as I expected and causes the program to hang when I have tried to call the line count method. Any help is greatly appreciated!
Main Class:
package cw;
import java.util.Scanner;
public class TextAnalyser {
public static void main(String[] args) {
LineCounter object = new LineCounter();
Scanner sc = new Scanner(TextAnalyser.class.getResourceAsStream("test.txt"));
int totalNumbers = 0;
int totalDigits = 0;
int totalWordCount = 0;
int totalLines = 0;
while (sc.hasNext()) {
totalWordCount++;
if (sc.hasNextInt()) {
totalDigits += sc.nextInt();
totalNumbers++;
}
else {
sc.next();
}
}
System.out.println("The total of all digits added = " + totalDigits);
System.out.println("The total number of digits in the file = " + totalNumbers);
System.out.println("The total number of words in the file = " + totalWordCount);
object.TotalLines();
}
}
Line counting class:
package cw;
import java.util.Scanner;
//Class that counts the lines in a file.
public class LineCounter {
public static void TotalLines() {
Scanner sc = new Scanner(TextAnalyser.class.getResourceAsStream("test.txt"));
System.out.println("hi");
int linetotal = 0;
while (sc.hasNextLine()) {
linetotal++;
}
System.out.println(linetotal);
}
}
hasNextLine() does only tell you IF there is a next line - it does not read it. So you are standing at the beginning and asking "is there a next line?" again and again and again... You should try actually reading it via nextLine();
just add this line of code :
while(sc.hasNextLine()){
String sentence = sc.nextLine();
linetotal++;
}
in your public static void TotalLines(){ method...
this way you actually get the next line, not only asking whether there exists another line in your while (which always returns true and you never exit the while loop!)
Related
I'm trying to write a class that will take in numbers from a file, but I keep running into this error when I run:
Java.util.NoSuchElementException: Null(in java.util.Scanner)
This is my code:
import java.util.*;
import java.io.*;
public class finalMain
{
public static void main (String args[]) throws IOException
{
int lineNumber = 0;
Scanner sc = new Scanner (new File ("Prog349f.txt"));
System.out.println("Student Quiz 1 Quiz2 MidTerm Final Final % Grade");
while(sc.hasNextLine())
{
lineNumber++;
sc.nextLine();
}
for(int i = 1; i <= 1; i++)
{
int quizOne = sc.nextInt();
int quizTwo = sc.nextInt();
int midterm = sc.nextInt();
int finalTest = sc.nextInt();
finalGrade studentNext = new finalGrade(sc.nextInt(),sc.nextInt(), sc.nextInt(),sc.nextInt(), i);
System.out.println(studentNext);
}
sc.close();
}
}
I'm thinking maybe I need to create two scanner objects, one for each line or something but I don't know how I would go about doing that.
You have misunderstood the usage of Scanner methods : sc.nextLine(); consumes and returns the line.
That means that you're currently reading the whole file with sc.nextLine();, discarding the result, and only then you try to read 4 ints, that can't be read since the Scanner is at the end of the file.
You should instead use one of these two methods :
If you're positive that each line of your file contains 4 ints separated by space (or any other specific character), and nothing more, you can then scan 4 ints while the scanner has a next line.
If there might be variations, or useless data, you should keep your hasNextLine() and nextLine() calls as they are, then use regex, split+indexing or another Scanner to retrieve the 4 ints from the line.
I have some problem when I ask the user to input some numbers and then I want to process them. Look at the code below please.
To make this program works properly I need to input two commas at the end and then it's ok. If I dont put 2 commas at the and then program doesnt want to finish or I get an error.
Can anyone help me with this? What should I do not to input those commas at the end
package com.kurs;
import java.util.Scanner;
public class NumberFromUser {
public static void main(String[] args) {
String gd = "4,5, 6, 85";
Scanner s = new Scanner(System.in).useDelimiter(", *");
System.out.println("Input some numbers");
System.out.println("delimiter to; " + s.delimiter());
int sum = 0;
while (s.hasNextInt()) {
int d = s.nextInt();
sum = sum + d;
}
System.out.println(sum);
s.close();
System.exit(0);
}
}
Your program hangs in s.hasNextInt().
From the documentation of Scanner class:
The next() and hasNext() methods and their primitive-type companion
methods (such as nextInt() and hasNextInt()) first skip any input that
matches the delimiter pattern, and then attempt to return the next
token. Both hasNext and next methods may block waiting for further
input.
In a few words, scanner is simply waiting for more input after the last integer, cause it needs to find your delimiter in the form of the regular expression ", *" to decide that the last integer is fully typed.
You can read more about your problem in this discussion:
Link to the discussion on stackoverflow
To solve such problem, you may change your program to read the whole input string and then split it with String.split() method. Try to use something like this:
import java.util.Scanner;
public class NumberFromUser {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] tokens = sc.nextLine().split(", *");
int sum = 0;
for (String token : tokens) {
sum += Integer.valueOf(token);
}
System.out.println(sum);
}
}
Try allowing end of line to be a delimiter too:
Scanner s = new Scanner(System.in).useDelimiter(", *|[\r\n]+");
I changed your solution a bit and probably mine isn't the best one, but it seems to work:
Scanner s = new Scanner(System.in);
System.out.println("Input some numbers");
int sum = 0;
if (s.hasNextLine()) {
// Remove all blank spaces
final String line = s.nextLine().replaceAll("\\s","");
// split into a list
final List<String> listNumbers = Arrays.asList(line.split(","));
for (String str : listNumbers) {
if (str != null && !str.equals("")) {
final Integer number = Integer.parseInt(str);
sum = sum + number;
}
}
}
System.out.println(sum);
look you can do some thing like this mmm.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Input some numbers");
System.out.println("When did you to finish and get the total sum enter ,, and go");
boolean flag = true;
int sum = 0;
while (s.hasNextInt() && flag) {
int d = s.nextInt();
sum = sum + d;
}
System.out.println(sum);
}
I'm new to Java & I don't even know if what I'm trying to do is actually doable in cmd but I want to know if there's a way to ask the user for an input while displaying something at the right of the input, something like:
enter weight: _ kg
specifying the unit I want the weight in for example
here is the code sample I have so far
import java.util.*;
public class ScannerPrompt {
public static void main(String[] args) {
int[] listOfIntegers = new int[10];
Scanner s = new Scanner(System.in);
for (int i = 0; i < 10; i++) {
System.out.print("Enter num: ");
int num = s.nextInt();
listOfIntegers[i] = num;
}
}
}
We can use \r in a tricky way:
import java.util.Scanner;
public class JavaApplication2 {
public static void main(String[] args) {
int i=0;
Scanner s = new Scanner(System.in);
System.out.print("Enter num: __kg\r");
System.out.print("Enter num: ");
i = s.nextInt();
System.out.println("\n"+i);
}
}
How it works:
we print Enter num: __kg and \r to make cursor at the begining of the line
Now if we print something, it will overwrite the fist message because cursor is in fist position, so we overwrite with same letters but just the part that will make the cursor at the desired position. Hence we print Enter num:
Dont use println because it insert \n at the end, and dont test in an IDE but use the console of your system.
You could use carriage return \r to relocate the cursor to the start of line
System.out.printf("%20skg\rEnter num: ", " ");
My output for the number of words and char keeps giving me zero. If anyone could help me find the
error in my code that would be great. The code enclosed by the stars is the code given by our teacher
and we are required to put this in our program.
Thank you!
** Our teacher told us not to use the buffered method. Also if I changes the lineNum method would it still override other methods?
Part of the assignment is to use at least two methods in our program****
** I edited my code based on everyones advice** It is now printing the correct numbers! How can I implement my two methods within this? A suggestion was that I use the for loop for the wordCount method.
I also need help with counting number of paragraphs
A good starting point?
import java.util.*;
import java.io.*;
public class WordStats1 {
public static void main(String[] args) {
try {
Scanner input = new Scanner(new FileReader("data.txt"));
//int totalLines = lineNum(input);
//int wordCount = wordCount(input);
//int countChar = countChar(input);
PrintWriter output = new PrintWriter(new FileOutputStream(
"newfile.txt"));
int lineNum = 0;
int wordCount = 1;
int charCount = 0;
while (input.hasNextLine()) {
String line;
line = input.nextLine();
//output.println(lineNum + ": " + line);
lineNum++;
String str [] = line.split((" "));
for ( int i = 0; i <str.length ; i ++) {
if (str [i].length() > 0) {
wordCount ++;
}
}
charCount += (line.length());
}
System.out.println(lineNum);
System.out.println(wordCount);
System.out.println(charCount);
input.close();
output.close();
System.out.print("File written.");
}
catch (FileNotFoundException e) {
System.out.println("There was an error opening one of the files.");
}
}
}
The issue is that, once you've called lineNum(), you are at the end of the file. When wordCount() and countChar() call hasNextLine(), this returns false and the functions return zero.
For some ideas on how to rewind a Scanner, see Java Scanner "rewind".
You need to do your linecount, word count and character count all inside a single loop. By having 3 functions, the very first function call to lineNum iterates over your scanner object, then the other two function calls return 0 because the scanner object has already read the file and as it is at the end of the file there is nothing left to read.
I would suggest you edit your teachers code, in particular the while loop. Remove the 3 functions and the corresponding function calls and have the program do all of your counting inside the loop inside the main() function.
int lineCount = 0;
int wordCount = 0;
int charCount = 0;
while (input.hasNextLine()) {
// read a line from the input file
String line = input.nextLine();
// increment line count
lineCount++;
// split line into words and increment word count
String str [] = line.split((" "));
for ( int i = 0; i <str.length ; i ++) {
if (str [i].length() > 0) {
wordCount ++;
}
}
// increment char count
charCount += (line.length());
}
EDIT
Given that you have said you need to use 2 methods, heres what I suggest:
Move the word counting code above (the for loop) into a function of its own, it takes a String argument (the current line) and returns an integer. You can keep calling this from inside the loop.
wordCount += countWordsInString(line);
The lineNum() method essentially 'consumes' the file, so input.hasNextLine() always returns false in the wordCount() and countChar() methods, hence you get zero in those two cases.
Either combine all three methods in one uber-counter and process the file once, or load the file into some temporary variable such as a string and pass that into the three methods.
I am creating a simple program that counts the number of words, lines and total characters (not including whitespace) in a paper. It is a very simple program. My file compiles but when I run it I get this error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1347)
at WordCount.wordCounter(WordCount.java:30)
at WordCount.main(WordCount.java:16)
Does anyone know why this is happening?
import java.util.*;
import java.io.*;
public class WordCount {
//throws the exception
public static void main(String[] args) throws FileNotFoundException {
//calls on each counter method and prints each one
System.out.println("Number of Words: " + wordCounter());
System.out.println("Number of Lines: " + lineCounter());
System.out.println("Number of Characters: " + charCounter());
}
//static method that counts words in the text file
public static int wordCounter() throws FileNotFoundException {
//inputs the text file
Scanner input = new Scanner(new File("words.txt"));
int countWords = 0;
//while there are more lines
while (input.hasNextLine()) {
//goes to each next word
String word = input.next();
//counts each word
countWords++;
}
return countWords;
}
//static method that counts lines in the text file
public static int lineCounter() throws FileNotFoundException {
//inputs the text file
Scanner input2 = new Scanner(new File("words.txt"));
int countLines = 0;
//while there are more lines
while (input2.hasNextLine()) {
//casts each line as a string
String line = input2.nextLine();
//counts each line
countLines++;
}
return countLines;
}
//static method that counts characters in the text file
public static int charCounter() throws FileNotFoundException {
//inputs the text file
Scanner input3 = new Scanner(new File("words.txt"));
int countChar = 0;
int character = 0;
//while there are more lines
while(input3.hasNextLine()) {
//casts each line as a string
String line = input3.nextLine();
//goes through each character of the line
for(int i=0; i < line.length(); i++){
character = line.charAt(i);
//if character is not a space (gets rid of whitespace)
if (character != 32){
//counts each character
countChar++;
}
}
}
return countChar;
}
}
I can't really say the exact reason for the problem without looking at the file (Maybe even not then).
while (input.hasNextLine()) {
//goes to each next word
String word = input.next();
//counts each word
countWords++;
}
Is your problem. If you are using the input.hasNextLine() in the while conditional statement use input.nextLine(). Since you are using input.next() you should use input.hasNext() in the while loops conditional statement.
public static int wordCounter() throws FileNotFoundException
{
Scanner input = new Scanner(new File("words.txt"));
int countWords = 0;
while (input.hasNextLine()) {
if(input.hasNext()) {
String word = input.next();
countWords++;
}
}
return countWords;
}
I have just added an if condition within the while loop. Just make sure to check there are token to be parsed. I have changed only in this place. Just make sure to change wherever needed.
This link will give good info. in regard to that.
Hope it was helpful. :)