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
Related
I was trying to write code which would read an input file and create an output file. But when I tried to add a try until a correct input file name is input, I had problems. It shows not proper filenotfound exception is in try....
public static void main(String[] args) throws FileNotFoundException
{
//prompt for the input file name
Scanner in = new Scanner(System.in);
//keep trying until there are no more exceptions
//boolean done = false;
String inputfilename = " ";
while (!done)
{
try
{
System.out.print("Input file name (from your computer): ");
inputfilename = in.next();
done = true;
}
catch (FileNotFoundException exception)
{
System.out.println("****** ERROR ******\nCannot locate the input file '" + inputfilename + "' on your computer - please try again.");
}
}
//prompt for the output file name
System.out.print("What would you like to call your output file: ");
//use outputfilename variable to hold input value;
String outputfilename = in.next();
//construct the Scanner and PrintWriter objects for reading and writing
File inputfile = new File(inputfilename);
Scanner infile = new Scanner(inputfile);
PrintWriter out = new PrintWriter(outputfilename);
//read the input and write the output
out.println("Here is the class average for mstu4031:\n");
double totalgrade = 0;
double number = 0;
while (infile.hasNextDouble())
{
double grade = infile.nextDouble();
out.println("\n");
out.printf("%.1f\n",grade);
number++;
totalgrade = totalgrade + grade;
}
//print numbers and average in output file
out.println("\n\n");
out.printf("\nNumber of grades: %.1f",number);
//calculate average
double average = totalgrade/number;
out.println("\n\n");
out.printf("\nAverage: %.2f",average);
finally
{
in.close();
out.close();
}
}
There is no method in your try block that may throw a FileNotFoundException.
Try to instantiate your Scanner in the try block. It will throw the expected FileNotFoundException if the filename read from stdin does not exist:
String inputfilename = null;
Scanner infile = null;
while (!done)
{
try
{
System.out.print("Input file name (from your computer): ");
inputfilename = in.next();
infile = new Scanner(new File(inputfilename));
done = true;
}
catch (FileNotFoundException exception)
{
System.out.println("****** ERROR ******\nCannot locate the input file '" + inputfilename + "' on your computer - please try again.");
}
}
Wrong here. You are only receiving input without checking if the file actually exist. Every valid inputs will let you get out of the loop.
if(new File(inputfilename).exist()){
done = true;
}else{
System.out.println("****** ERROR ******\nCannot locate the input file '" + inputfilename + "' on your computer - please try again.");
}
You can only catch an exception if something in the try block may throw an exception.
However, you should test for existence of a file with File.exists(), instead of catching an exception.
File file;
do {
System.out.print("Input file name (from your computer): ");
file = new File(in.next());
} while (!file.exists());
Opening a file may throw an Exception. That's Why you need to put them inside try block. You have put only reading the input part inside try-catch block
Hope this code works properly:
//prompt for the input file name
Scanner in = new Scanner(System.in);
//keep trying until there are no more exceptions
//boolean done = false;
String inputfilename = " ";
while (!done)
{
try
{
System.out.print("Input file name (from your computer): ");
inputfilename = in.next();
done = true;
//prompt for the output file name
System.out.print("What would you like to call your output file: ");
//use outputfilename variable to hold input value;
String outputfilename = in.next();
//construct the Scanner and PrintWriter objects for reading and writing
File inputfile = new File(inputfilename);
Scanner infile = new Scanner(inputfile);
PrintWriter out = new PrintWriter(outputfilename);
//read the input and write the output
out.println("Here is the class average for mstu4031:\n");
double totalgrade = 0;
double number = 0;
while (infile.hasNextDouble())
{
double grade = infile.nextDouble();
out.println("\n");
out.printf("%.1f\n",grade);
number++;
totalgrade = totalgrade + grade;
}
//print numbers and average in output file
out.println("\n\n");
out.printf("\nNumber of grades: %.1f",number);
//calculate average
double average = totalgrade/number;
out.println("\n\n");
out.printf("\nAverage: %.2f",average);
}
catch (FileNotFoundException exception)
{
System.out.println("****** ERROR ******\nCannot locate the input file '" + inputfilename + "' on your computer - please try again.");
}
}
finally
{
in.close();
out.close();
}
I've a text file and eclipse reads that without problem. The problem is that I don't know how I can hold the numbers from the FileReader. My program is supposed to read a text from a file that file has 2 names with their school points.
For example:
Jack 30 30 30
Martin 20 20 30
How can I find the one with the greater points?
public static void main(String[] args) {
String name = null;
try {
Scanner keybord = new Scanner(System.in);
System.out.println("enter in file name");
String filename = keybord.nextLine();
Scanner file = new Scanner(new File(filename));
while (file.hasNext())
{
name = file.nextLine();
System.out.println(name);
///?? what do i have to write to compare to persons points
}
} catch(IOException e) {
System.out.println("The file does not exist");
}
}
I know, it is not an efficient method, but I solved the problem with this code:
public static void main(String[] args)
{
String name = null;
int i = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
try
{
Scanner keybord = new Scanner(System.in);
System.out.println("enter in file name");
String filename = keybord.nextLine();
Scanner file = new Scanner(new File(filename));
while (file.hasNext())
{
name = file.next();
System.out.println(name + " ");
while (file.hasNextInt())
{
i = i + file.nextInt();
}
if (i < min)
{
min = i;
}
System.out.println("min " + min);
if (i > max)
{
max = i;
}
System.out.println("max " + max);
i = 0;
}
} catch (IOException e)
{
System.out.println("File does not exist");
}
}
This probably isn't the most efficient way of solving it, but I gave it a shot. It isn't the full code for comparing multiple lines but you can just run this through a while loop until the file doesn't have next like you were already doing. Once you run this through you can store the value of each line to a variable and then compare the variables. ex: boolean xIsBigger x > y;. Then if it is true, x is the bigger number but if it is false then you know y is the bigger number. Hope this helps.
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Test {
public static void main(String[] args) throws ScriptException {
String line = "Jack 20 20 20";
line = line.replaceAll("[^0-9]", " ");
line = line.replaceFirst("^ *", "");
line = line.replaceAll(" ", "+");
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
System.out.println(engine.eval(line));
}
}
System output: 60.
This is the basis of my code. It prints students grades on the console, but how do I use a Buffereader to put all the students grade on a new file.
import java.io.*;
import java.util.InputMismatchException;
import java.lang.*;
import java.util.*;
public class WorkSpace {
private Scanner x;
public void openFile(){
try{
x = new Scanner (new File ("grades.txt"));
}
catch(Exception e){
System.out.println("could not find file");
}}
public void createFile()throws IOException {
try{
File file = new File("grades.txt");
Scanner s = new Scanner(file);
while(s.hasNext()){
{
String [] split = s.nextLine().split(", ");
String fname = split[0];
Double q1 = Double.parseDouble (split[1]);
Double q2 = Double.parseDouble (split[2]);
Double q3 = Double.parseDouble (split[3]);
Double q4 = Double.parseDouble (split[4]);
Double proji = Double.parseDouble (split[5]);
Double projii = Double.parseDouble (split[6]);
Double projiii = Double.parseDouble (split[7]);
double studentgrade = (q1 *0.1) + (q2 *0.1) +(q3 *0.1) + (q4 *0.1) +(proji*0.15) + (projii * 0.2) + (projiii *0.25);
if(studentgrade>90)
System.out.printf("%s got an A\n", fname);
else if(studentgrade>80)
System.out.printf("%s got a B\n", fname);
else if(studentgrade>70)
System.out.printf("%s got a C\n", fname);
else if(studentgrade>60)
System.out.printf("%s got a D\n", fname);
else if(studentgrade>50)
System.out.printf("%s got a F\n", fname);
}}}catch(Exception e){
e.printStackTrace();
}
}
public void closeFile(){
x.close();
}
Scanner.nextInt() returns next integer value read from source (not source length or something). You open the file and try to read integer in the beginning, but the file doesn't start with integer so you get an exception.
How you are reading your file is incorrect. The most common way to read files with scanner:
try{
File file = new File("Your/File/Path");
Scanner s = new Scanner(file);
s.useDelimiter("\n");//splits the whole file's text by "\n"
while(s.hasNext()){
String next = s.next();
//parse your stuff
}
s.close();
}catch(Exception e){}
Also, scanner.nextInt() doesn't return the file's length. That was the problem. Use file.length to get the file's length.
Your question doesn't make sense. BufferedReader doesn't write files. It, err, reads files. What you want is, err, a BufferedWriter.
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]);
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.