java.util.NoSuchElementException even though input file has data - java

I have written this code to find out an output and i am running this using Runtime in a servlet. It shows java.util.NoSuchElementEception even though i have checked that input file has some data:
public class Sec1q10 {
static int fact(int n) {
int p = 1;
if (n != 1) {
p = n * fact(n - 1);
}
return p;
}
public static void main(String args[]) {
try {
System.out.println("first");
Scanner in = new Scanner(new FileReader("F:/sem5/algorithm/in.txt"));
String no = in.next();
int n = Integer.parseInt(no);
System.out.println(n);
int s = 0;
while (n != 0) {
s += fact(n);
n--;
}
System.out.println("sum=" + s);
String s1 = "" + s + "here";
PrintWriter out;
System.out.println(s1);
out = new PrintWriter("F:/sem5/algorithm/out.txt");
out.write(s1);
System.out.println(s1);
} catch (Exception ex) {
System.out.println("Exception: " + ex);
}
}
}
I even run this on cmd where it is showing the output without any exception but not writing anything in the file F:/sem5/algorithm/out.txt

To see results in output file close PrintWriter after writing in it
PrintWriter out;
System.out.println(s1);
out = new PrintWriter("F:/sem5/algorithm/out.txt");
try
{
out.write(s1);
System.out.println(s1);
}
finally
{
out.close();
}

Whenever you use the Scanner class you should actually test to ensure input is waiting for you before trying to read it using the hasNextXXXXX() methods.
try this:
String no;
while(in.hasNext())
{
no = in.next();
//.....
}
the problem isn't that your input file doesn't have any data, it's that your input file runs out of data because you continually read. If you try to read when nothing is there you will get a NoSuchElementException

All I can think of is that the Directory does not exist. Are you sure it does? If not, you should either make it manually, or use the .mkdir() function

Related

Using formulas from a text/writing to a text

So, my lecture powerpoint slides and even my book is not really doing a good job (for my understanding that is) of explaining how to use formulas from a text document, then when the code runs/compiles successfully it will create a "Results.txt" in the same folder.
These are the formulas in a notepad doc. Nothing to crazy, just a proof of concept
4 * 5 ..
3 / 4...
3 - 1..
2 + 3..
import java.io.*;
import java.util.*;
public class ReadFileLineByLine {
public static void main(String[] args) throws FileNotFoundException {
String line;
int numberOfLines = 3;
String[] textData = new String[numberOfLines];
int i;
for(i = 0; i < numberOfLines; i++){
textData[i] = textReader.readLine();
}
text.Reader.close();
return textData;
try {
File inputfile = new File(args[0]); //new File("formulas.txt")
Scanner input = new Scanner(new File("C:\Users\Frost\Documents\Question4"));
BuffredReader br = new BufferedReader(new FileReader("C:\Users\Frost\Documents\Question4"));
PrintWriter output = new PrintWriter("Results.txt");
while (input.hasNextLine()) {
line = input.nextLine();
System.out.println("read <" + line + ">"); // Display message to commandline
// Declare ArrayList of for storing tokenized formula from String line
double result = 0; // The variable to store result of the operation
// Determine the operator and calculate value of the result
System.out.println(formula.get(0) + ' ' + formula.get(1) + ' ' +
formula.get(2) + " = " + result); // Display result to command line
// Write result to file
}
// Need to close input and output files
}
catch (FileNotFoundException e) {
System.out.println("Error reading file named " + Formulas.txt);
}
}
}
Here's something to get you started. The //TODO: comments are where you need to build your logic. Be sure to change the file paths back to what you need. I changed them to a Temp location. Also change the messages printed as I just put something there as proof of concept. I tried to comment thoroughly but don't hesitate to ask questions.
import java.io.*;
import java.util.*;
public class ReadFileLineByLine {
public static void main(String[] args) throws FileNotFoundException {
String line = "";
//Declare Scanner and PrintWriter outside of try clause so they can be closed in finally clause
Scanner input = null;
PrintWriter output = null;
try {
//Instantiate input and output file
input = new Scanner(new File("C:\\Temp\\test.txt"));
output = new PrintWriter(new File("C:\\Temp\\Results.txt"));
//Loop through lines in input file
while (input.hasNextLine()) {
line = input.nextLine();
// Display message to commandline
System.out.println("read <" + line + ">");
// Populate ArrayList of tokenized formula from String line
//TODO:
// The variable to store result of the operation
double result = 0;
// Determine the operator and calculate value of the result
//TODO:
// Write result to file
output.println("Print result of " + line + " to Results.txt");
}
} catch (FileNotFoundException e) {
//Exception thrown, print message to console
System.out.println("File Not Found: " + e.getMessage());
} finally {
//close files in finally clause so it happens even if exception is thrown
//I also set to null as extra precaution
input.close();
input = null;
output.close();
output = null;
}
}
}

Find line number and content of a line and then find open same line number in another file JAVA

I got this code to open up a file and getting the line number, but if I want to open up another file where the content is not the same as the first file and find the same line number, how can I do that the best way? Where do I go from here?
I'm new to this site and to Java so please go easy on me...
public class c {
public static void main(String args[]) {
File file =new File("one.txt");
Scanner in = null;
try {
int counter = 0;
in = new Scanner(file);
while(in.hasNext()) {
counter++;
String line=in.nextLine();
if(line.contains("umbrella")) {
System.out.println(line + " line: " + counter);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You can just open the other file, and read the lines and increment a counter (counter2) until your counter2 reaches your counter-Variable (from above code-snippet). You also have to notice if the file hasn't ended.
The Code is has many similar Elements like the one you already used in your question.
The best way would depend on the context at which you are developing. You could just create additional instances of File and Scanner classes to operate on a different file as you already done in your code and mentioned in comment already.
Another method would be to create a class that would process this for you. In this case you could use this class for an unlimited number of files that you need to accomplish the same.
public class FileLineCounter {
public FileLineCounter( String filename)
{
try
{
f = new File(filename);
s = new Scanner(f);
}
catch(FileNotFoundException ex)
{
ex.printStackTrace();
}
}
public int getLineNumber( String item)
{
counter = 0;
while( s.hasNext())
{
counter++;
String line = s.nextLine();
if (line.contains(item))
{
break;
}
}
return counter;
}
private File f;
private Scanner s;
private int counter;
};
package FileUtil;
import FileUtil.FileLineCounter;
public class Main {
public static void main(String[] args)
{
String file1 = "one.txt";
String file2 = "two.txt";
FileLineCounter f1 = new FileLineCounter(file1);
FileLineCounter f2 = new FileLineCounter(file2);
System.out.println( file1 + " line : " + f1.getLineNumber("umbrella"));
System.out.println( file2 + " line : " + f2.getLineNumber("umbrella"));
}
}

How to write more than one object result to one output text file in Java?

I have more than one objects with different output, and I want to print all results in one text file, with each object's result on one line without overwriting any values.
I have written the following code; however, the output text file only saves the values of the last object (Object2). I want the output file save the result as following:
Q = 1
Q = 2
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class Output {
public static int Q;
public static void main(String[] args) {
Object1();
Object2();
}
public static void Object1() {
Q = 1;
Print();
}
public static void Object2() {
Q = 2;
Print();
}
public static void Print() {
PrintWriter writer;
try {
writer = new PrintWriter("C:\\Users\\My Document\\Desktop\\Out.txt");
if (Q == 1) {
writer.println("Q =" + 1);
}
if (Q == 2) {
writer.println("Q = " + 2);
}
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
A FileWriter is the right way to go about this. You don't need to wrap it in anything, either.
Specifying true in the constructor enables the append mode (so be careful on subsequent runs). Since Q can't be both 1 and 2, we write a new line after we're done with the block.
Since this is a try-with-resources statement, you don't need to worry about closing out the resource when you're done, as that is taken care of for you.
try (FileWriter writer = new FileWriter("test.txt", true)) {
if (Q == 1) {
writer.write("Q =" + 1);
}
if (Q == 2) {
writer.write("Q = " + 2);
}
writer.write("\n");
} catch (IOException e) {
e.printStackTrace();
}
You are overwriting your Out.txt file with the new information. You need to append your data.
Replace your line with this:
writer = new PrintWriter(new BufferedWriter(new FileWriter("C:\\Users\\My Document\\Desktop\\Out.txt", true)));

Java Scanner Read from File

Let me first establish the following fact: I am new to java, so please be patient.
In my programming class, we were given an exercise to do at home using the Scanner class. The activity shows the following coding to exercise with:
import java.io.*;
import java.util.*;
public class FileReadWrite {
public static void main(String[] args) throws FileNotFoundException {
String[] strArr = new String[100];
int size = 0;
try {
Scanner scFile = new Scanner(new File("Names1.txt"));
while (scFile.hasNext()) {
strArr[size] = scFile.next();
size++;
}
scFile.close();
for (int i = 0; i < size; i++) {
System.out.print(strArr[i] + " ");
}
} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
}
}
}
The program seems to not be working correct. I use NetBeans to run the code, and when I run the code, it does not display the data in the text file, Names.txt. Why is that? The program does however Build completely without errors.
I have tried going through the Scanner class javadocs, but it's not helping me.
Please explain to me so that I can learn from the mistake made.
Thanks,
Johan
I tried your code on my mac, and it works. So I thought you might input a wrong path of Names1.txt file.
In Java, when you simply use "what_ever_file_name.txt" as the path of file, Java will only search the file in your source code folder. If nothing found, a "FILE_NOT_FOUND_EXCEPTION" will be thrown.
I agree with user2170674. I also tried your code in a Windows machine, using Eclipse, and everything went well. Maybe you are putting your file in the wrong path. Two options:
you could use the full path, like (if you're using Windows) "C:\Names1.txt";
or, a more generic solution, using JFileChooser:
// create your FileChooser
final JFileChooser chooser = new JFileChooser();
// open the FileChooser
int returnValue = chooser.showOpenDialog(null);
// if you select a file
if (returnValue == JFileChooser.APPROVE_OPTION) {
// get the file and do what you need
File file = chooser.getSelectedFile();
} else {
// throw an exception or just a message in the log...
}
Your code looks good.
Debug with a few messages.
At end, add a System.out.println() or System.out.flush().
Move exception block location to just after file use (minimise try block size) and move close() within finally block.
Make sure you view Netbeans output window (Window -> Output -> Output)
public class FileReadWrite {
public static void main(String[] args) throws FileNotFoundException {
System.out.println("##### Starting main method...");
String[] strArr = new String[100];
int size = 0;
try {
Scanner scFile = new Scanner(new File("Names1.txt"));
while (scFile.hasNext()) {
strArr[size] = scFile.next();
size++;
}
System.out.println("##### Finished scan. Found %d tokens.", size);
} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
e.printStackTrace();
} finally {
if (scFile != null) {
scFile.close();
System.out.println("##### Closed scanner.");
}
}
System.out.println("##### Printing tokens...");
for (int i = 0; i < size; i++) {
System.out.print(strArr[i] + " ");
}
System.out.println("");
System.out.println("##### Exiting main.");
}
}
Here's a working example. Perhaps try using a BufferedReader.
import java.io.*;
import java.util.Scanner;
public class ScanXan {
public static void main(String[] args) throws IOException {
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));
while (s.hasNext()) {
System.out.println(s.next());
}
} finally {
if (s != null) {
s.close();
}
}
}
}
From http://docs.oracle.com/javase/tutorial/essential/io/scanning.html

BufferedReader.readLine() Returns null at beginning rather than end of file

I'm creating a true/false test for a Java course that stores both an answer key and each user's respective array of answers as BitSets. These BitSets are then serialized into persistent sequential binary files so that they may be scored later by another application.
Everything works perfectly with the strange exception of my first call to request.readLine(), which is my system.in inputstreamreader that retrieves the user's answer. For some reason, it's setting the first answer to null regardless of what's entered, as if it had hit EOF.
CreateTest.java (reads/displays questions from txt file, collects user answers, stores them in .bin file)
public class CreateTest
{
private static BufferedReader request;
private static BufferedReader response;
private static String answers, userName;
private static ObjectOutputStream result;
public static void main(String[] args)
{
response = new BufferedReader(new InputStreamReader(System.in));
try
{
request = new BufferedReader(new FileReader("test.txt"));
}
catch(FileNotFoundException fnfe)
{
System.out.println("Test.txt was not found. Please fix your crappy file system.");
System.exit(1);
}
System.out.println("Welcome to THE TEST\n\n" +
"Please respond with only \"t\" for true or \"f\" for false.\n" +
"This application is case-insensitive.\n" +
"DON'T GET EATEN BY THE GRUE!");
System.out.println("\nPlease enter your name: ");
try
{
userName = response.readLine().replaceAll("\\s", "");
System.out.println("\n\n");
result = new ObjectOutputStream(new FileOutputStream(userName + "TestAnswers.bin"));
}
catch(IOException e1) { e1.printStackTrace(); }
try {
for(int i=0; i<24; i++)
{
System.out.println(request.readLine());
recordResponse();
}
System.out.println("Thank you for attempting THE TEST. You probably failed.");
result.writeObject(new BitMap(answers));
close();
} catch (IOException e) { e.printStackTrace(); }
}
public static void recordResponse() throws IOException
{
String currentAnswer = response.readLine();
//diagnostic
System.out.println("Answer: " + answers);
if(currentAnswer.equals("t")||
currentAnswer.equals("T")||
currentAnswer.equals("f")||
currentAnswer.equals("F"))
{ answers += currentAnswer + " -- "; }
else
{
System.out.println("What, you can't read or somethin'?. Enter(case-insenstive) T or F only pal." +
"Try it again.");
close();
System.exit(1);
}
}
public static void close() throws IOException
{
request.close();
response.close();
}
Pertinent constructor from BitMap.java (parses passed arguments into BitSets, provides bitwise operations)
public BitMap(String s) throws IndexOutOfBoundsException,ArithmeticException
{
try
{
if(s.length() > 25) { throw new IndexOutOfBoundsException(); }
StringTokenizer answers = new StringTokenizer(s);
for(int i=0; i<bitString.size(); i++)
{
String currentToken = answers.nextToken();
if(currentToken.equals("t") || currentToken.equals("T")) { bitString.set(i); }
else if(currentToken.equals("f") || currentToken.equals("F")) { bitString.clear(i); }
}
}
catch(IndexOutOfBoundsException ioob){System.out.println("Sorry bub, too many answers.");}
}
I apologize for the mass of code, but I figure more info's better than not enough.
You didn't initialize answers, so it will start out as null. In recordResponse you print out answers before the update, so after the first answer is entered you print null, and then you have "nullt/f -- t/f ...".
So, you want
private static String answers = "", userName;
and the diagnostic, in order to be relevant, should most likely go after the update:
if(currentAnswer.equals("t")||
currentAnswer.equals("T")||
currentAnswer.equals("f")||
currentAnswer.equals("F"))
{
answers += currentAnswer + " -- ";
System.out.println("Answer: " + answers);
}

Categories