Store 100 strings and search file i/o java - java

In this program I am trying write a program that reads the first 100 strings from a set of text files and then counts how many times those strings appear in the whole of each file. Well I keep getting a crazy output and I asked this question earlier but butchered it. One thing has changed but now my output is null = 0. for 100 times
my output: http://i.imgur.com/WVZJnTp.png
package program6;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Program6 {
public static final String INPUT_FILE_NAME = "myths.txt";
public static final String INPUT_FILE_NAME2 = "pnp.txt";
public static final String INPUT_FILE_NAME3 = "tsawyer.txt";
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Scanner in = null;
Scanner fin = null;
Scanner fin2 = null;
Scanner fin3 = null;
String[] character = new String[100];
int[] counter = new int[100];
try {
fin = new Scanner(new File(INPUT_FILE_NAME));
} catch (FileNotFoundException e) {
System.err.println("Error opening the file " + INPUT_FILE_NAME);
System.exit(1);
}
try {
fin2 = new Scanner(new File(INPUT_FILE_NAME2));
} catch (FileNotFoundException e) {
System.err.println("Error opening the file " + INPUT_FILE_NAME2);
System.exit(1);
}
try {
fin3 = new Scanner(new File(INPUT_FILE_NAME3));
} catch (FileNotFoundException e) {
System.err.println("Error opening the file " + INPUT_FILE_NAME3);
System.exit(1);
}
for (int i = 0; i < character.length; i++) {
}
System.out.println("Word: Count:");
for (int i = 0; i < 100; i++) {
System.out.println(character[i] + " " + counter[i]);
}
}
}

Simply replace
System.out.println(character + " " + counter);
by
System.out.println(character[i] + " " + counter[i]);

On this line System.out.println(character + " " + counter);
It should be:
System.out.println(character[i] + " " + counter[i]);

Related

NumberFormatException with File IO

I keep getting a NumberFormatException, which I understand arises due to a string conversion. I am converting st.nexttoken to a double with Double.parseDouble.
Any help would be much appreciated!
import java.io.*;
import java.util.*;
public class FileIO {
public static void main(String[] args) throws Exception {
double sum = 0, next ;
int ctr = 0;
String line;
String filename = "numbers.txt";
StringTokenizer st;
PrintWriter outFile = new PrintWriter("output.txt");
outFile.println("Output File");
try{
Scanner inFile = new Scanner(new FileReader (filename));
while (inFile.hasNext())
{
line = inFile.nextLine();
st = new StringTokenizer(line);
while (st.hasMoreTokens()){
next = Double.parseDouble(st.nextToken());
sum += next;
ctr++;
System.out.println(next);
outFile.println(next);
}
}
System.out.println("number of doubles read is " + ctr);
System.out.println("average is " + sum/(double)ctr);
outFile.println("number of doubles read is " + ctr);
outFile.println("average is " + sum/(double)ctr);
outFile.close();
}
catch(FileNotFoundException e){
System.out.println("The file numbers.txt was not found");
}
catch(NumberFormatException e){
System.out.println("sorry - number format error");
System.out.println(e);
}
}
}
The error from NetBeans reads sorry - number format error
java.lang.NumberFormatException: For input string: "Output"
numbers.txt has some integers as well as doubles with decimal points.
output.txt is blank, but saved in the same file path as numbers.txt
Here is the body of numbers.txt as requested.
13 12 15 3
74.4 67.3 43.8 77.7 233.4 678.9
public static void main(String[] args) throws Exception {
double sum = 0, next ;
int ctr = 0;
String line;
String filename = "numbers.txt";
StringTokenizer st;
PrintWriter outFile = new PrintWriter("output.txt");
outFile.println("Output File");
try{
Scanner inFile = new Scanner(new FileReader(filename));
while (inFile.hasNext())
{
line = inFile.nextLine();
st = new StringTokenizer(line);
while (st.hasMoreTokens()){
next = Double.parseDouble(st.nextToken());
sum += next;
ctr++;
System.out.println(next);
outFile.println(next);
}
}
System.out.println("number of doubles read is " + ctr);
System.out.println("average is " + sum/(double)ctr);
outFile.println("number of doubles read is " + ctr);
outFile.println("average is " + sum/(double)ctr);
outFile.flush();
inFile.close();
outFile.close();
}
catch(FileNotFoundException e){
System.out.println("The file numbers.txt was not found");
}
catch(NumberFormatException e){
System.out.println("sorry - number format error");
System.out.println(e);
}
}
Above is modified version of your code and it works fine with the below given number.txt.
You need use the flush() write it to the final destination.
Here is the number.txt
12 12.0 12
12 32 56
34
34.0

Possible to write what would be output into a HTML file?

What I want to do is make it so that when the program runs it will run the ordinary way but if the user selects that they want the display to be in html then it will run what the ordinary program would do but rather than display it in the console it will write what was going to appear in the console into a html file that the user specifies. Is this possible? I have code to accept the user input and have them specify what format they want it in as well as open the browser but I'm not sure if this could work. The code I have already is below:
import java.awt.Desktop;
import java.io.*;
import java.util.*;
public class reader {
static int validresults = 0;
static int invalidresults = 0;
// Used to count the number of invalid and valid matches
public static boolean verifyFormat(String[] words) {
boolean valid = true;
if (words.length != 4) {
valid = false;
} else if (words[0].isEmpty() || words[0].matches("\\s+")) {
valid = false;
} else if ( words[1].isEmpty() || words[1].matches("\\s+")) {
valid = false;
}
return valid && isInteger(words[2]) && isInteger(words[3]);}
// Checks to see that the number of items in the file are equal to the four needed and the last 2 are integers
// Also checks to make sure that there are no results that are just whitespace
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
}
catch (Exception e) {
return false;
}
}
// Checks to make sure that the data is an integer
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
while (true) { // Runs until it is specified to break
Scanner scanner = new Scanner(System.in);
System.out.println("Enter filename");
String UserFile = sc.nextLine();
File file = new File(UserFile);
if (!file.exists()) {
continue;
}
if (UserFile != null && !UserFile.isEmpty()){
System.out.println("Do you want to generate plain (T)ext or (H)TML");
String input = scanner.nextLine();
if (input.equalsIgnoreCase("H")) {
Desktop.getDesktop().browse(file.toURI());
} else if (input.equalsIgnoreCase("T")) {
processFile(UserFile);
} else {
System.out.println("Do you want to generate plain (T)ext or (H)TML");
}
}
}
}
// Checks how the user wants the file to be displayed
private static void processFile(String UserFile) throws FileNotFoundException {
String hteam;
String ateam;
int hscore;
int ascore;
int totgoals = 0;
Scanner s = new Scanner(new BufferedReader(
new FileReader(UserFile))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");
while (s.hasNext()) {
String line = s.nextLine();
String[] words = line.split("\\s*:\\s*");
// Splits the file at colons
if(verifyFormat(words)) {
hteam = words[0]; // read the home team
ateam = words[1]; // read the away team
hscore = Integer.parseInt(words[2]); //read the home team score
totgoals = totgoals + hscore;
ascore = Integer.parseInt(words[3]); //read the away team score
totgoals = totgoals + ascore;
validresults = validresults + 1;
System.out.println(hteam + " " + "[" + hscore + "]" + " " + "|" + " " + ateam + " " + "[" + ascore + "]");
// Output the data from the file in the format requested
}
else{
invalidresults = invalidresults + 1;
}
}
System.out.println("Total number of goals scored was " + totgoals);
// Displays the total number of goals
System.out.println("Valid number of games is " + validresults);
System.out.println("Invalid number of games is " + invalidresults);
System.out.println("EOF");
}
}
//This is where we'll write the HTML to if the user's chooses so
private static final String OUTPUT_FILENAME = "output.html";
public static void main(String[] args) throws IOException
{
final Scanner scanner = new Scanner(System.in);
final String content = "Foobar";
final boolean toHtml;
String input;
//Get the user's input
do
{
System.out.print("Do you want messages "
+ "written to (P)lain text, or (H)TML? ");
input = scanner.nextLine();
} while (!(input.equalsIgnoreCase("p")
|| input.equalsIgnoreCase("h")));
toHtml = input.equalsIgnoreCase("h");
if (toHtml)
{
//Redirect the standard output stream to the HTML file
final FileOutputStream fileOut //False indicates we're not appending
= new FileOutputStream(OUTPUT_FILENAME, false);
final PrintStream outStream = new PrintStream(fileOut);
System.setOut(outStream);
}
System.out.println(toHtml
? String.format("<p>%s</p>", content) //Write HTML to file
: content); //We're not writing to an HTML file: plain text
}

IOException Loop

I need help figuring out how to loop my IOException (in where I ask for a filename until a valid one is entered). I need a loop that somehow recognizes that an invalid file was entered and am unsure how to do this.
import java.util.*;
import java.io.*;
public class JavaGradedLab {
public static void main(String[] args) throws IOException {
Scanner inScan, fScan = null;
int [] A = new int[5];
inScan = new Scanner(System.in);
System.out.println("Please enter the file to read from: ");
try{
String fName = inScan.nextLine();
fScan = new Scanner(new File(fName));
}
catch (FileNotFoundException ex)
{
System.out.println("Your file is invalid -- please re-enter");
}
String nextItem;
int nextInt = 0;
int i = 0;
while (fScan.hasNextLine())
{
nextItem = fScan.nextLine();
nextInt = Integer.parseInt(nextItem);
A[i] = nextInt;
i++;
}
System.out.println("Here are your " + i + " items:");
for (int j = 0; j < i; j++)
{
System.out.println(A[j] + " ");
}
}
}
Well, there's sure to be someone explaining how to make your code better via best practices etc., but as a very basic answer which in itself can probably be improved (assuming that your code works when the input is valid):
while(true) {
try{
String fName = inScan.nextLine();
fScan = new Scanner(new File(fName));
break;
}
catch (FileNotFoundException ex)
{
System.out.println("Your file is invalid -- please re-enter");
}
}

Main method input file keeps giving me IndexOutOfBoundsException (even with right arguments)

I'm trying to use args[0] as an input file, but when I run the program, I keep getting an IndexOutOfBoundsException, although I'm quite sure that args[0] is the correct argument. I ran into this problem with my last program as well, but I can't figure out what I'm doing wrong.
Code:
import java.io.*;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class SortTest {
public static void main(String args[]) throws FileNotFoundException {
try {
Scanner read = new Scanner(new File(args[0]));
while (read.hasNextLine()) {
String name = read.nextLine();
read.nextLine();
String line1 = read.nextLine();
int sh = Integer.parseInt(line1.substring(0,2));
int sm = Integer.parseInt(line1.substring(3));
read.nextLine();
String line2 = read.nextLine();
int fh = Integer.parseInt(line2.substring(0,2));
int fm = Integer.parseInt(line2.substring(3));
if (fh<sh) {
System.out.println("Times not in correct order.");
return;
} else if (fh==sh) {
if (fm<sm) {
System.out.println("Times not in correct order.");
return;
}
} else {
System.out.println(name + "\n" + sh + ":" + sm + "\n" + fh + ":" + fm);
}
}
read.close();
}
catch (FileNotFoundException e) {
System.out.println("Invalid file path.");
}
catch (NoSuchElementException n) {
System.out.println("No readable text in file.");
}
catch (IndexOutOfBoundsException x) {
System.out.println("Proper format is java LectureSortTest <input>");
}
catch (NumberFormatException num) {
System.out.println("File contents not formatted correctly");
}
}
}

Java-Greatest number of friends (from .txt file)

I'm trying to create a program that reads in a .txt file with multiple lines containing lists of names. A sample of the test file is below:
Joe Sue Meg Ry Luke
Kay Trey Phil George
I have three classes(also below). Everything works fine, but I would like to know which friend-set has the greatest number of friends (i.e. in the test file Joe would have the greatest number of friends)
The data isn't limited to only two friend-sets though...
import java.io.*;
//Finds the file
public class ReadFileLine {
public static void main(String[] args) throws Exception {
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in),1);
System.out.println("Hello! " + "Please enter the name of your test file: " +
"\n**Hint** for this assignment the file name is: friendsFile.txt\n");
String fileName= keyboard.readLine();
System.out.println(fileName);//
FileLine doLine = new FileLine();
doLine.readList(fileName);
}
}
Class 2:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class InStringFile {
//read the file
private BufferedReader in;
//read each line
private String nextLine;
//handle exceptions
public InStringFile(String filename) {
//line by line input
try {
in = new BufferedReader(new FileReader(filename));
nextLine = in.readLine();
}
catch (FileNotFoundException ee){
System.out.println("We're sorry,\n" +"File " + filename + " cannnot be found.");
System.exit(0);
}
catch (IOException e){
System.out.println("We're sorry,\n" +"File " + filename + " cannot be read.");
System.exit(0);
}
}
//reads the file as string
public String read() {
String current = nextLine;
try {
nextLine = in.readLine();
}
//catch exception
catch (IOException e){
System.out.println("We're sorry, this file cannot be read.");
System.exit(0);
}
return current;
}
public boolean endOfFile() {
return (nextLine == null);
}
//close the file
public void close(){
try {
in.close();
in = null;
}
//catch if file cannot be closed
catch (IOException e){
System.out.println("Problem closing file.");
System.exit(0);
}
}
}
Class 3:
import java.util.StringTokenizer;
public class FileLine {
public void readList (String fileName) throws Exception {
//opens the file and controls file reading
InStringFile reader = new InStringFile(fileName);
System.out.println("\nFile Found!" +
" Now reading from file: " + fileName + "\n");
// line by line read
String line;
do {
line = (reader.read());
//print the friend list
System.out.println("The following friend-set exists: " + line);
this.TokenizeString(line);
}while (!reader.endOfFile());
reader.close();
}
//number of friends
public void TokenizeString(String nameList){
StringTokenizer tokens = new StringTokenizer(nameList);
System.out.println("The number of friends in this friend-set is: " + tokens.countTokens());
}
}
Okay, so I modified the fileLine class to be the following:
import java.util.StringTokenizer;
public class FileLine {
public void readList (String fileName) throws Exception {
//opens the file and controls file reading
InStringFile reader = new InStringFile(fileName);
System.out.println("\nFile Found!" +
" Now reading from file: " + fileName + "\n");
// line by line read
String line;
do {
line = (reader.read());
//print the friend list
System.out.println("The following friend-set exists: " + line);
this.TokenizeString(line, line);
}while (!reader.endOfFile());
reader.close();
}
//number of friends
public void TokenizeString(String nameList, String nameByName) {
StringTokenizer tokens = new StringTokenizer(nameList);
System.out.println("The number of friends in this friend-set is: " + tokens.countTokens());
StringTokenizer st = new StringTokenizer(nameByName, " ");
String firstName = st.nextToken();
System.out.println("Friend-set Leader: " + firstName);
}
}
So now the code returns the first name in each line... I still am stuck on how to store the number of tokens. IF I could do that then I could compare and return the greatest number (right?)...
Let tokenizeString(..) return the number of friends. Then:
int maxFriends = 0;
int maxFriendsLine = 0;
int currentLine = 0;
while (..) {
int friends = tokenizeString(..);
if (friends > maxFriends) {
maxFriendsLine = currentLine;
maxFriends = friends;
}
currentLine++;
}
A few notes:
see if you can use commons-lang FileUtils.readLines(..) or guava Files.readLines(..)
prefer str.split(" ") instead of StringTokenizer
use lower-case methods - that's what the java convention prescribes.

Categories