NoSuchElementException When writng to file - java

I am writing a program that read string and integers from file, then copy the data and write to another file. Data entries should be separated by a space.
My input should and output should follow the following format, the first two set of numbers are string while the others are integers:
123123 242323 09 08 06 44
I get Exception in thread "main" java.util.NoSuchElementException when I run my code, I do not know why
import java.util.Scanner;
import java.io.*;
public class Billing {
public static void main(String[] args) throws IOException {
//define the variables
String callingnumber;
String callednumber;
String line;
int startinghour;
int startingminute;
int endinghour;
int endingminute;
//open input and output files
FileReader freader = new FileReader("BillingData.txt");
BufferedReader inFile = new BufferedReader(freader);
FileWriter fwriter = new FileWriter("BillingOutput.txt");
PrintWriter outFile = new PrintWriter (fwriter);
// set space between the numbers
line=inFile.readLine();
while(line!=null)
{
//creat a scanner to use space between the numbers
Scanner space = new Scanner(line).useDelimiter(" ");
callingnumber=space.next();
callednumber=space.next();
startinghour=space.nextInt();
startingminute=space.nextInt();
endinghour=space.nextInt();
endingminute=space.nextInt();
// writing data to file
outFile.printf("%s %s %d %d %d %d", callingnumber, callednumber,startinghour, startingminute, endinghour, endingminute);
line=inFile.readLine();
}//end while
//close the files
inFile.close();
outFile.close();
}//end of mine
}//end of class

I suspect that the scanner has run out of data in the line - probably because there are less than 6 values in it. To avoid the error you should do something like this:
if (space.hasNextInt()) {
startingHour = space.nextInt();
}

Your Scanner is trying to read in a token that either doesn't exist or is of the wrong type. Myself, I'd split the String, line using " " as my delimiter and then deal with the array returned.

Related

This code is supposed to get N values from the user. Then input then into a .txt file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
This code is supposed to get N values from the user. Then input the values into a .txt file. I'm having trouble getting the values to show in the .txt file. Not sure why.
// This program writes data into a file.
import java.io.*; // Needed for File I/O class.
import java.util.Scanner; // Needed for Scanner class.
public class program01
{
public static void main (String [] args) throws IOException
{
int fileName;
int num;
// Create a Scanner object for keyboard input.
Scanner input = new Scanner(System.in);
File fname = new File ("namef.txt");
Scanner inputFile = new Scanner(fname); // Create a Scanner object for keyboard input.
FileWriter outFile = new FileWriter ("namef.txt", true);
PrintWriter outputfile = new PrintWriter("/Users/******/Desktop/namef.txt");
System.out.println("Enter the number of data (N) you want to store in the file: ");
int N = input.nextInt(); // numbers from the user through keyboard.
System.out.println("Enter " + N + " numbers below: ");
for ( int i = 1; i <= N; i++)
{
// Enter the numbers into the file.
input.nextInt();
outputfile.print(N);
}
System.out.println("Data entered into the file.");
inputFile.close(); // Close the file.
}
} // End of class
In your program you seemed to have thrown everything and hoping that it works. To find out what class you should use you should search it in Javadoc of you Java version.
Javadoc of Java 12
PrintWriter:
Prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.
FileWriter:
Writes text to character files using a default buffer size. Encoding from characters to bytes uses either a specified charset or the platform's default charset.
Scanner (File source):
Constructs a new Scanner that produces values scanned from the specified file. Bytes from the file are converted into characters using the underlying platform's default charset.
Now you can see what each class is for. Both PrintWriter and FileWriter are used to write file however PrintWriter offer more formatting options and Scanner(File source) is for reading files not writing files.
Since there is already an answer with PrintWriter. I am writing this using FileWriter.
public static void main(String[] args) throws Exception {
// Create a Scanner object for keyboard input.
Scanner input = new Scanner(System.in);
// You can provide file object or just file name either would work.
// If you are going for file name there is no need to create file object
FileWriter outputfile = new FileWriter("namef.txt");
System.out.print("Enter the number of data (N) you want to store in the file: ");
int N = input.nextInt(); // numbers from the user through keyboard.
System.out.println("Enter " + N + " numbers below: ");
for (int i = 1; i <= N; i++) {
System.out.print("Enter the number into the file: ");
// Writing the value that nextInt() returned.
// Doc: Scans the next token of the input as an int.
outputfile.write(Integer.toString(input.nextInt()) + "\n");
}
System.out.println("Data entered into the file.");
input.close();
outputfile.close(); // Close the file.
}
Output:
Enter the number of data (N) you want to store in the file: 2
Enter 2 numbers below:
Enter the number into the file: 2
Enter the number into the file: 1
Data entered into the file.
File:
2
1
Here's a working variant of what you want to achieve:
import java.io.*; // Needed for File I/O class.
import java.util.Scanner; // Needed for Scanner class.
public class program01
{
public static void main (String [] args) throws IOException
{
int fileName;
int num;
// Create a Scanner object for keyboard input.
Scanner input = new Scanner(System.in);
File fname = new File ("path/to/your/file/namef.txt");
PrintWriter outputfile = new PrintWriter(fname);
System.out.println("Enter the number of data (N) you want to store in the file: ");
int N = input.nextInt(); // numbers from the user through keyboard.
System.out.println("Enter " + N + " numbers below: ");
for (int i = 1; i <= N; i++)
{
// Enter the numbers into the file.
int tmp = input.nextInt();
outputfile.print(tmp);
}
System.out.println("Data entered into the file.");
outputfile.close(); // Close the file.
}
}
Several comments on above:
1) Got rid of redundant rows:
Scanner inputFile = new Scanner(fname); // Create a Scanner object for keyboard input.
FileWriter outFile = new FileWriter ("namef.txt", true);
You actually didn't use them at all.
2) In PrintWriter we pass File object, not String.
3) In for loop there was a logic mistake - on every iteration you should have written N instead of actual number which user entered on console.
4) Another mistake was in closing wrong file in the last line.
EDIT: adding according to comment.
in point 2) there's an alternative way - you can skip creating File object and pass as a String a path to even non-existing file directly in PrintWriter, like this:
PrintWriter outputfile = new PrintWriter("path/to/your/file/namef.txt");

Getting null value from bufferedreader

I am not able to understand why I am getting null from bufferedreader in following code (2nd line of output), while it worked fine at some places (1st line of output).
I have used several system.out.println's just for debugging purpose.
Although the BufferedReader.readLine() returns null only when the end of the stream is reached, the input is being provided (as shown in input below the program). Please help me in getting the reason of getting null and suggest a solution.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
import java.lang.Integer;
import java.io.*;
class TestClass {
public static void main(String args[] ) throws Exception {
//* Read input from stdin and provide input before running
List a2=new ArrayList();
String[] a1=new String[2];
int count=0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
/*for (String retval: line.split(" "))
a2.add(retval);*/
a1=line.split(" ");
//System.out.println("here 0"+a1[0]+" "+a1[1]);
/*int N = Integer.parseInt((a2.get(0)).toString());
int Q= Integer.parseInt((a2.get(1)).toString());*/
int N = Integer.parseInt(a1[0].toString());
int Q= Integer.parseInt(a1[1].toString());
System.out.println("here xxxxxxxx" + N +" " +Q);
String[] names=new String[N];
for(int i=0;i<N;i++){
//names[i] = (new BufferedReader(new InputStreamReader(System.in))).readLine();
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
names[i] = br1.readLine();
/*Scanner sc=new Scanner(System.in);
names[i]=sc.nextLine();*/
}
System.out.println("here 111" + names[0]);
for(int i=0;i<Q;i++) {
br = new BufferedReader(new InputStreamReader(System.in));
String line1 = br.readLine();
try{
System.out.println("here 1" + line1);
int M = Integer.parseInt(line1);
System.out.println("here 2");
if(M<=20){
System.out.println("here 3");
count++;
}
}
catch(Exception e){
System.out.println("here 4");
if(!((Arrays.asList(names)).contains(line))){
System.out.println("here 5");
count++;
}
}
}
System.out.println(count);
}
}
Input
First line of the input will contain two space separated integers denoting N and Q.
Next N lines will contain strings
Next Q lines will contain either an integer or a string denoting the name of a person. Different logics have to be implemented depending on whether it is aString or an Integer.
enter code here
Inputs and outputs are as follows:
Input:
2 4
pranjul
sachin
21
19
pranjul
vipul
Output:
here xxxxxxxx2 4
here 111null
here 1null
here 4
here 5
here 1null
here 4
here 5
here 1null
here 4
here 5
here 1null
here 4
here 5
4
You are trying to open more than one reader on the same input stream.
When you read the contents in your first br.readLine(), here is what happens:
The BufferedReader has an internal buffer it needs to fill up. It calls the read method from the underlying InputStreamReader in order to fill it.
The InputStreamReader, in order to convert the bytes in the input stream into characters, uses a StreamDecoder. So it calls that StreamDecoder's read method. Internally, it also has a buffer, and it reads as many bytes as it can from the underlying stream into that buffer.
This means that as soon as you read one line, you also read several characters beyond that line. The default size is of the StreamDecoder byte buffer is 8K, so it reads 8K bytes from System.in if they are available.
If you use System.in in interactive mode, each read only fills the buffer with as many bytes as are available right then. So it fills just one line up to the point where the user pressed Enter and so, when you open your other BufferedReader instances, they will get the next input the user enters.
But if System.in is redirected from a file or other stream where it is not blocking on end-of-line, it will read the entire file (assuming the file is smaller than 8K) on the first call to readLine. That data waits in that BufferedReader's buffer or the underlying StreamDecoder's buffer.
So when you open a new BufferedReader on System.in, there is no more data in that stream - it has already been read by the first BufferedReader. That's why it's not recommended to open more than one reader on a single stream.
first of all you dont need the first two rows if you use the io.*;
secondly why did you use so many streams, if 1 is enough
import java.util.*;
import java.lang.Integer;
import java.io.*;
class TestClass {
public static void main(String args[] ) throws Exception {
List a2=new ArrayList();
int count=0;
Scanner br = new Scanner(System.in);
String line = br.nextLine();
String[] a1=line.split(" ");
int N = Integer.parseInt(a1[0]);
int Q= Integer.parseInt(a1[1]);
System.out.println("here xxxxxxxx" + N +" " +Q);
String[] names=new String[N];
for(int i=0;i<N;i++){
names[i]=br.nextLine();
}
System.out.println("here 111" + names[0]);
for(int i=0;i<Q;i++) {
String line1 = br.nextLine();
try{
System.out.println("here 1" + line1);
int M = Integer.parseInt(line1);
System.out.println("here 2");
if(M<=20){
System.out.println("here 3");
count++;
}
}
catch(Exception e){
System.out.println("here 4");
if(!((Arrays.asList(names)).contains(line))){
System.out.println("here 5");
count++; } } }
System.out.println(count);
br.close();}}
i didnt test the code but it should work
i did it with scanner but you can use bufferedreader aswell

Reading text files in Java and using data

I am required to evaluate the contents of a .txt file, the file includes 5 numbers, all spaced apart by one (ex: 5555 55 45 47 85) on one line.
The problem isn't reading the file, but actually using each number in the file.
Question: How can I grab the 5 numbers and store each into a unique variable?
Code so far:
import java.io.FileReader;
import java.io.BufferedReader;
public class PassFail {
public static void main(String[] args) {
try{
FileReader file = new FileReader("C:\\new_java\\Final_Project\\src\\student.txt");
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
reader.close();
System.out.println(line);
} catch(Exception e) {System.out.println("Error:"+ e);}
}
}
You need to read the file line by line, which you already did. Then you can split the string on space character and iterate over the fields and parse them to Integer
s= reader.readline()
String tokens[]= s.split(" ");
int nums[] = new int[tokens.length];
for(int i=0; i<tokens.lenght; i++) {
nums[i] = Integer.parseInt(tokens[i]);
}
Hope this helps.

Read specific characters from specific line of text in java

I am working on a program that involves me having to search a specific line in a .txt file and convert the string inside of it into something else.
For example, the string is actually made of numbers which I suppose I can convert into ints. The main thing is that for example, on line 2, there are 5 digits for zip code stored. I need to convert that into certain outputs, depending on the numbers. In other words, I need variables from digits 0-9 and depending on each digit, output a specific output.
Right now here is the code I have to prompt the user for information that is stored in the file, and can read and print all of the information that was just typed, but I'm unsure how to go about the rest.
import java.io.*;
import java.util.*;
import java.io.FileReader;
import java.io.IOException;
public class ObjectTest2 {
public static void main(String [] args) throws FileNotFoundException, IOException {
// The name of the file to open.
String fileName = "information.txt";
Scanner myScanner = new Scanner(System.in);
try {
// Assume default encoding.
FileWriter fileWriter =
new FileWriter(fileName);
// Always wrap FileWriter in BufferedWriter.
BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);
// append a newline character.
//This shit here prompts the user for information and stores it in seperate lines to be
//called on by the later section.
System.out.print("What is your name? ");
bufferedWriter.write(myScanner.nextLine());
bufferedWriter.newLine();
System.out.print("What is your 5 digit zip code?");
bufferedWriter.write(myScanner.nextLine());
bufferedWriter.newLine();
System.out.print("What is your +4 digit zip? ");
bufferedWriter.write(myScanner.nextLine());
bufferedWriter.newLine();
System.out.print("What is your address? ");
bufferedWriter.write(myScanner.nextLine());
// Always close files.
bufferedWriter.close();
//reads the information file and prints what is typed
BufferedReader reader = new BufferedReader(new FileReader("information.txt")); {
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
}
}
catch(IOException ex) {
System.out.println(
"Error writing to file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
You are left with no choice but to iterate over each line of the file and search for the String. If you want to get a line of string from the file based on line number, consider creating a method. If the operation is required to be performed several times on the same file and if the contents of the file do not change, use a map to cache the file contents based on the line number.

Reading in a file and processing data

I am a noobie at programming and I can't seem to figure out what to do.
I am to write a Java program that reads in any number of lines from a file and generate a report with:
the count of the number of values read
the total sum
the average score (to 2 decimal places)
the maximum value along with the corresponding name.
the minimum value along with the corresponding name.
The input file looks like this:
55527 levaaj01
57508 levaaj02
58537 schrsd01
59552 waterj01
60552 boersm01
61552 kercvj01
62552 buttkp02
64552 duncdj01
65552 beingm01
I program runs fine, but when I add in
score = input.nextInt(); and
player = input.next();
The program stops working and the keyboard input seems to stop working for the filename.
I am trying to read each line with the int and name separately so that I can process the data and complete my assignment. I don't really know what to do next.
Here is my code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
public class Program1 {
private Scanner input = new Scanner(System.in);
private static int fileRead = 0;
private String fileName = "";
private int count = 0;
private int score = 0;
private String player = "";
public static void main(String[] args) {
Program1 p1 = new Program1();
p1.getFirstDecision();
p1.readIn();
}
public void getFirstDecision() { //*************************************
System.out.println("What is the name of the input file?");
fileName = input.nextLine(); // gcgc_dat.txt
}
public void readIn(){ //*********************************************
try {
FileReader fr = new FileReader(fileName + ".txt");
fileRead = 1;
BufferedReader br = new BufferedReader(fr);
String str;
int line = 0;
while((str = br.readLine()) != null){
score = input.nextInt();
player = input.next();
System.out.println(str);
line++;
score = score + score;
count++;
}
System.out.println(count);
System.out.println(score);
br.close();
}
catch (Exception ex){
System.out.println("There is no shop named: " + fileName);
}
}
}
The way you used BufferReader with Scanner is totally wrong .
Note: you can use BufferReader in Scanner constructor.
For example :
try( Scanner input = new Scanner( new BufferedReader(new FileReader("your file path goes here")))){
}catch(IOException e){
}
Note: your file reading process or other processes must be in try block because in catch block you cannot do anything because your connection is closed. It is called try catch block with resources.
Note:
A BufferedReader will create a buffer. This should result in faster
reading from the file. Why? Because the buffer gets filled with the
contents of the file. So, you put a bigger chunk of the file in RAM
(if you are dealing with small files, the buffer can contain the whole
file). Now if the Scanner wants to read two bytes, it can read two
bytes from the buffer, instead of having to ask for two bytes to the
hard drive.
Generally speaking, it is much faster to read 10 times 4096 bytes
instead of 4096 times 10 bytes.
Source BufferedReader in Scanner's constructor
Suggestion: you can just read each line of your file by using BufferReader and do your parsing by yourself, or you can use Scanner class that gives you ability to do parsing tokens.
difference between Scanner and BufferReader
As a hint you can use this sample for your parsing goal
Code:
String input = "Kick 20";
String[] inputSplited = input.split(" ");
System.out.println("My splited name is " + inputSplited[0]);
System.out.println("Next year I am " + (Integer.parseInt(inputSplited[1])+1));
Output:
My splited name is Kick
Next year I am 21
Hope you can fixed your program by given hints.

Categories