I am trying to write a program that inputs a text file through the command line and then prints out the number of words in the text file. I've spent around 5 hours on this already. I'm taking an intro class using java.
Here is my code:
import java.util.*;
import java.io.*;
import java.nio.*;
public class WordCounter
{
private static Scanner input;
public static void main(String[] args)
{
if (0 < args.length) {
String filename = args[0];
File file = new File(filename);
}
openFile();
readRecords();
closeFile();
}
public static void openFile()
{
try
{
input = new Scanner(new File(file));
}
catch (IOException ioException)
{
System.err.println("Cannot open file.");
System.exit(1);
}
}
public static void readRecords()
{
int total = 0;
while (input.hasNext()) // while there is more to read
{
total += 1;
}
System.out.printf("The total number of word without duplication is: %d", total);
}
public static void closeFile()
{
if (input != null)
input.close();
}
}
Each way I've tried I get a different error and the most consistent one is "cannot find symbol" for the file argument in
input = new Scanner(new File(file));
I'm also still not entirely sure what the difference between java.io and java.nio is so I have tried using objects from both. I'm sure this is an obvious problem I just can't see it. I've read a lot of similar posts on here and that is where some of my code is from.
I've gotten the program to compile before but then it freezes in command prompt.
java.nio is the New and improved version of java.io. You can use either for this task. I tested the following code in the command line and it seems to work fine. The "cannot find symbol" error message is resolved in the try block. I think you were confusing the compiler by instantiating a File object named file twice. As #dammina answered, you do need to add the input.next(); to the while loop for the Scanner to proceed to the next word.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class WordCounter {
private static Scanner input;
public static void main(String[] args) {
if(args.length == 0) {
System.out.println("File name not specified.");
System.exit(1);
}
try {
File file = new File(args[0]);
input = new Scanner(file);
} catch (IOException ioException) {
System.err.println("Cannot open file.");
System.exit(1);
}
int total = 0;
while (input.hasNext()) {
total += 1;
input.next();
}
System.out.printf("The total number of words without duplication is: %d", total);
input.close();
}
}
Your code is almost correct. Thing is in the while loop you have specified the terminating condition as follows,
while (input.hasNext()) // while there is more to read
However as you are just increment the count without moving to the next word the count just increases by always counting the first word. To make it work just add input.next() into the loop to move to next word in each iteration.
while (input.hasNext()) // while there is more to read
{
total += 1;
input.next();
}
Related
Following is my code that I am working on for a school project. It does ok up until I try to read the animal.txt file. Can someone please tell me what I am doing wrong? I am attaching my compilation error as an image. Thanks in advance.
[input error image1
package finalproject;
//enabling java programs
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.io.FileInputStream;
import java.io.IOException;
public class Monitoring {
public static void choseAnimal() throws IOException{
FileInputStream file = null;
Scanner inputFile = null;
System.out.println("Here is your list of animals");
file = new FileInputStream("\\src\\finalproject\\animals.txt");
inputFile = new Scanner(file);
while(inputFile.hasNext())
{
String line = inputFile.nextLine();
System.out.println(line);
}
}
public static void choseHabit(){
System.out.println("Here is your list of habits");
}
public static void main(String[] args) throws IOException{
String mainOption = ""; //user import for choosing animal, habit or exit
String exitSwitch = "n"; // variable to allow exit of system
Scanner scnr = new Scanner(System.in); // setup to allow user imput
System.out.println("Welcome to the Zoo");
System.out.println("What would you like to monitor?");
System.out.println("An animal, habit or exit the system?");
mainOption = scnr.next();
System.out.println("you chose " + mainOption);
if (mainOption.equals("exit")){
exitSwitch = "y";
System.out.println(exitSwitch);
}
if (exitSwitch.equals( "n")){
System.out.println("Great, let's get started");
}
if (mainOption.equals("animal")){
choseAnimal();
}
if (mainOption.equals("habit")) {
choseHabit();
}
else {
System.out.println("Good bye");
}
}
}
\\src\\finalproject\\animals.txt suggests that the file is an embedded resource.
First, you should never reference src in you code, it won't exist once the program is built and package.
Secondly, you need to use Class#getResource or Class#getResourceAsStream in order to read.
Something more like...
//file = new FileInputStream("\\src\\finalproject\\animals.txt");
//inputFile = new Scanner(file);
try (Scanner inputFile = new Scanner(Monitoring.class.getResourceAsStream("/finalproject/animals.txt"), StandardCharsets.UTF_8.name()) {
//...
} catch (IOException exp) {
exp.printStackTrace();
}
for example
Now, this assumes that file animals.txt exists in the finalproject package
The error message clearly shows that it can't find the file. This means there's two possibilities:
File does not exist in the directory you want
Directory you want is not the directory you have.
I would start by creating a File object looking at "." (current directory) to and printing that to see what directory it looks by default. You may need to hard code the file path, depending on what netbeans is using for a default directory.
I am trying to count the number of times a string appears in a file. I want to find the number of times that "A, E, I, O, U" appears exactly in that order. Here is the text file:
AEIOU aeiou baeiboeu bbbaaaaaa beaeiou caeuoi ajejijoju aeioo
aeiOu ma me mi mo mu
take it OUT!
I want the method to then return how many times it is in the file. Any idea's on how I could go about doing this? The catch is I want to do this without using BufferedReader. I can simply just read the file using Scanner. Is there a way to do this?
I edited this and added the code I have so far. I don't think I am even close. I am pretty sure I need to use some nested loops to make this happen.
import java.util.*;
import java.io.*;
public class AEIOUCounter
{
public static final String DELIM = "\t";
public static void main(String[] args)
{
File filename = new File("aeiou.txt");
try
{
Scanner fileScanner = new Scanner(new File(filename));
while(fileScanner.hasNextLine())
{
System.out.println(fileScanner.nextLine());
}
}
catch(IOException e)
{
System.out.println(e);
}
catch(Exception e)
{
System.out.println(e);
}
fileScanner.close();
}
}
What you are doing now, is printing all the lines in the file.
fileScanner.hasNextLine()
fileScanner.nextLine()
But what you are looking for is filtering out separate words in the file:
Path path = Paths.get("/path/to/file");
Scanner sc = new Scanner(path);
int counter = 0;
while (sc.hasNext()) {
String word = sc.next();
if (word.equalsIgnoreCase("AEIOU")) {
counter += 1;
}
}
System.out.print("Number of words: " + counter);
Smurf's answer is great. It's worth mentioning that if you're using Java 8, you can avoid using a Scanner at all, and do this in a single expression:
long count = Files.lines(Paths.get("aeiou.txt"))
.flatMap(s -> Arrays.stream(s.split(" ")))
.filter(s -> s.equalsIgnoreCase("aeiou"))
.count();
I have got a question about a code I have written
package salescities;
import java.io.File;
import java.util.Scanner;
public class SalesCities {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
double totalSales = 0;
int count = 0;
int missingCount = 0;
String line;
File file;
Scanner input;
try {
file = new File("sales.txt");
input = new Scanner(file);
input.useDelimiter(":");
while (input.hasNextLine()) {
input.next();
line = input.nextLine();
try{
totalSales += Double.parseDouble(line);
count++;
}
catch(IllegalArgumentException e){
missingCount++;
}
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(totalSales + " " +missingCount);
}
}
And the file im trying to read is like this
New York: 23.5678
New Jersey: no reports
Rio de Janeiro: 12.3654
When i run the program however it prints out 0.0 3 like all is missing.
The problem is when i run the debugger to see whats happening to line so parseDouble isn't functioning and i saw that line is a string that has this
: 23.5678
and I don't understand why if I'm using ":" as delimeter. I expected only the number without the colon. Can someone answer me?
ps: this is an exercise from a book that's quite simple but the book uses a class TextIO that is implemented by them. just wanted to try scanner instead of their code.
Scanner#nextLine grabs the rest of the line, regardless of the delimiter.
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line. — Scanner#nextLine
I'm trying to read from a .java the methods I have on it, also the classes, I'm using taggs to identify them and stored them, the problem is that using BufferedReader sometimes just doesn't work, the buffer skips a lot of lines for a reason that I can't understand, sometimes when checking the file by myself I just put random spaces between lines, and that fixes some parts, but I can't get the Buffer read all my text without skipping anything, my code so far is like this:
public class ReadFile {
public static void main(String[] args) {
int numclas=0,numbase=0,numbaseagr=0,numbmet=0,numag=0;
String mt="//MT";
String[] nomclass2 = new String[10];
String[] nommetodo2 = new String[50];
boolean metodo=false;
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("\\Program.java"));
String read = null;
while ((read = in.readLine()) != null) {
read = in.readLine();
String[] splited = read.trim().split("\\s+");
for(int i=0;i<splited.length;i++){
System.out.println(splited[i]);
if(splited[i].equals("class")){
nomclass2[numclas]=splited[i+1];
numclas=numclas+1;
}
if (splited[i].equals(mt)){
metodo=true;
}
if (splited[i].equals("public")){
if (splited[i+1].equals("static")){
nommetodo2[numbmet]=splited[i+3];
numbmet=numbmet+1;
}
if (splited[i+1].equals("int")||splited[i+1].equals("double")||splited[i+1].equals("String")||splited[i+1].equals("boolean")){
nommetodo2[numbmet]=splited[i+2];
numbmet=numbmet+1;
}
if (splited[i].equals("int")||splited[i].equals("double")||splited[i].equals("String")||splited[i].equals("boolean")){
nommetodo2[numbmet]=splited[i+1];
numbmet=numbmet+1;
}
metodo=false;
}
if ((splited[i].equals("int")||splited[i].equals("double")||splited[i].equals("String")||splited[i].equals("boolean"))&&metodo){
nommetodo2[numbmet]=splited[i+1];
numbmet=numbmet+1;
metodo=false;
}
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
}
}
Now let me show you the .java I'm trying to read:
import java.text.DecimalFormat;
import java.io.*;
//Main file of the program 1
public class Program1 {
//MT
public static void main (String args []) {
DecimalFormat format=new DecimalFormat("##.##");
System.out.println("How many data do you want to insert?");
int num=Leer.Int();
Fila lista=new Fila();
Fila lista2=new Fila();
double x=0.0;
for(int i=0;i<num;i++){
x=Leer.Double();
lista.addNum(x);
}
double prom=0.0;
double desv=0.0;
prom=lista.getprom();
desv=lista.getdevst();
System.out.println("The mean for column 1 is: "+format.format(prom));
System.out.println("The Std.Dev for column 1 is: "+format.format(desv));
System.out.println("How many data do you want to insert?");
num=Leer.Int();
x=0.0;
for(int i=0;i<num;i++) {
x=Leer.Double();
lista2.addNum(x);
}
prom=0.0;
desv=0.0;
prom=lista2.getprom();
desv=lista2.getdevst();
System.out.println("The mean for column 2 is: "+format.format(prom));
System.out.println("The Std.Dev for column 2 is: "+format.format(desv));
}
}
And the result when I print the array
Date:
12/12/12
import
java.text.DecimalFormat;
//Main
file
of
the
program
1
//MT
DecimalFormat
format=new
DecimalFormat("##.##");
so on...
See how in the //MT the Buffer skips a lot of lines, a lot of this is happening (see how it ignores the first lines of the program), and I don't know how to fix it, because sometimes when I try to "fix it" and add some spaces in the lines, I get a nullpointer and the program ends.
Any help will be appreciated, thank you.
This is just a partial answer - at the very least your program is skipping every other line:
while ((read = in.readLine()) != null)
will read a line from the file. The line is immediately discarded because the immediately following statement:
read = in.readLine();
reads and processes the next line from the file.
(also, 'splited' should be 'splitted' along with numerous other spelling mistakes but they're not really affecting your program, just it's readability :-))
I am trying to write a plugin that reads a file line by line and then enters a command in the console with each name as separate commands. This does contain code which relies on the Bukkit API, but it should be simple enough to figure out.
I am currently using a Scanner, but is a BufferedReader would be better, let me know. Currently, the scanner prints fine without the extra Bukkit code.
Current code:
public class FixWhitelist extends JavaPlugin {
public static void main(String[] args) {
FixWhitelist scanner = new FixWhitelist();
scanner.readFile("white-list.txt");
}
public void readFile(String path) {
try {
Scanner sc = new Scanner(new File(path));
while(sc.hasNextLine()) {
String next = sc.nextLine();
//System.out.println(next);
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "whitelist add" + next);
Bukkit.getServer().getConsoleSender().sendMessage(next + "added to the whitelist.");
}
sc.close();
}
catch (FileNotFoundException ex) {
Logger.getLogger(FixWhitelist.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
So, the question is, how can I have a command entered for each line of code in a file?
Should the following line have a space after the "add":
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "whitelist add " + next);