Java Scanner throws NoSuchElementException: No Line Found - java

I don't know why it won't work. I've double and triple checked that the file in FileWriter has text (inputted by another PrintWriter earlier in a separate program) but the while statement doesn't seem to run. The commented out lines were various tests I was running to try to figure out what was going on. What I'm trying to work out is have it iterate through the array and add a group ID to all Persons. If anyone knows what's up, it would be greatly appreciated. I'll apologize in advance for any formatting errors, any comments on how to be more easily helped would also be greatly appreciated.
public static void updateWinners(Person[] Players, int n)
throws FileNotFoundException {
// n is 2 or 4 depending on round
File fileS = new File(
"C:\\Users\\Patrick\\Desktop\\New folder\\FileWriter\\Win");
File fileP = new File(
"C:\\Users\\Patrick\\Desktop\\New folder\\Bracket\\Win");
Scanner fs = new Scanner(fileS);
PrintWriter writer = new PrintWriter(fileP);
//int q=0;
while (fs.hasNextLine()) {
//System.out.println(Players[q].toString());
for (int i = 0; i < Players.length; i++) {
if (fs.nextLine().equals(Players[i].toString())) {
Players[i].addGroup(alpha[i / n]);
System.out.println(Players[i].toString());
writer.println(Players[i].toString());
}
}
//q++;
}
writer.close();
fs.close();
}

Do it like this,
while (fs.hasNextLine()) {
String s = fs.nextLine();
//System.out.println(Players[q].toString());
for (int i = 0; i < Players.length; i++) {
if (s.equals(Players[i].toString())) {
Players[i].addGroup(alpha[i / n]);
System.out.println(Players[i].toString());
writer.println(Players[i].toString());
}
}
//q++;
}
Explanation:
When you call fs.nextLine() each time in the players loop. It reads a new line from the file. So All lines of the file are read before you complete all the players.
Scanner throws exception when you try to read and there are no more data in the file.
Source
Throws:
NoSuchElementException - if no line was found

Related

Using command-line argument for reading and writing files to a program

I am trying to use my LoadTextFile() method to read a .txt file from the command prompt in Eclipse and then use another method, SaveDocumentsToJSON, to write into a json.file (again, the name of the json file should be entered as an argument in the command prompt).
My code
public static void main(String[] args) {
// instantiate an instance of the BTextLoader class.
BTextLoader loader = new BTextLoader();
// Check if command line arguments are NOT empty and then enter the file names.
if (args.length > 0) {
{
// with hard-coded loader.LoadTextFile("TextFile.txt") the next part of the code runs as expected.
for (int x = 0; x < args.length; x++) {
if (args[x].endsWith(".txt")) {
loader.LoadTextFile(args[x]);
}
if (args[x].endsWith(".json")) {
loader.SaveDocumentsToJSON(args[0]);
}
}
}
}
else {
System.err.println("No valid file was given.");
}
}
public void LoadTextFile(String filePath) {
try {
System.out.println("Loading file...");
File inFile = new File(filePath);
BufferedReader br = new BufferedReader(new FileReader(inFile));
String line = br.readLine();
Integer counter = 0;
while (line != null)
{
if (line.trim().length() > 0) {
documents.put("doc" + counter, line);
;
counter++;
}
line = br.readLine();
}
br.close();
} catch (Exception e) {
System.out.println("File Load Failed");
}
So if I enter the outputFile.json file in the command prompt, and hard code "TextFile.txt", then the result is as expected, with the text file remaining unaltered and a new .json file being created.
However, if I try to use loader.LoadTextFile(args[0]) and enter "TextFile.txt outputFile.json" (two file names with a space) in Eclipse, then my original TextFile.txt gets rewritten with a json structure and outputFile.json is not created.
I need help with loading my .txt file and then saving it with the names as command-line arguments. How can I avoid hard coding my .txt file for this to work?
Whatever parameter matches, you will always overwrite the first given file:
for (int x = 0; x < args.length; x++) {
if (args[x].endsWith(".json")) {
loader.SaveDocumentsToJSON(args[0]);
}
}
You need to change into
loader.SaveDocumentsToJSON(args[x]);
Yet there is still an imminent problem depending on the sequence of the parameters. Check how your code behaves if you first put the json file and afterwards the txt file. Similarly there is no check if you put several txt or json files. I'm wondering whether all that is intended or unplanned side effects.

Need help fixing NumberFormatException error [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I'm trying to read in a text file which looks similar to this:
0000000000
0000100000
0001001000
0000100000
0000000000
Here is my code:
public static int[][] readBoard(String fileName) throws FileNotFoundException {
File life = new File(fileName);
Scanner s = new Scanner(life);
int row = s.nextInt();
int columns = s.nextInt();
int [][] size = new int [row][columns];
for (int i=0; i <= row; i++) {
String [] state = new String [columns];
String line = s.nextLine();
state = line.split("");
for (int j=0; i <= columns; i++) {
size[i][j] = Integer.parseInt(state[j]);
}
}
return size;
}
It keeps giving me this error. I think it's the Integer.parseInt(state[j]) that is giving me trouble, but I don't know why.
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at Project5.readBoard(Project5.java:33)
at Project5.main(Project5.java:9)
I've executed your code with the example input, and you have logical issues in the code. With the exmaple input the code doesn't even reach the parseInt() line where the asked NumberFormatException could be thwrown. I assume you have tried your code in a different input. The Exception message is staithforward, you tried to parse an empty string to number. It's a typical NumberFormatException. The parseInt() function can throw Exception, so your code must be prepared for it.
The other problem is a basic logical issue in your algorithm. Your row and column variables will be populated with the first to integer token from the text. Based on the exampe input the first integer token will be the first row 0000000000 which integer value is 0, and the second token is 0000100000 which will parsed as 100000. So you are trying to initialize an array with these dimensions which is imposible.
To calculate the row count, you have to read the file line by line. And to get the column counts you have the check the length of the lines. (It can open a new question, how do you want to handle the not properly formatted input file, because in the file the line length can be various.)
That means you can only be sure with the dimensions of the board if you have already iterated though the file content. To prevent the multiple iteration you should use dinamic collection instead of a standard array, like ArrayList.
That means while you are read the file line by line, you can process the the characters one after another in a line. In this step you should be concidered about the invalid characters and the potential empty characters in the end of the file. And during this iteration the final collection can be built.
This example shows a potention solution:
private static int processCharacter(char c) {
try {
return Integer.parseInt((Character.toString(c)));
} catch (NumberFormatException e) {
return 0;
}
}
public static List<List<Integer>> readBoard(String fileName) throws FileNotFoundException {
List<List<Integer>> board = new ArrayList<>();
File file = new File(fileName);
FileReader fr = new FileReader(file);
try (BufferedReader br = new BufferedReader(fr)) {
String line;
while ((line = br.readLine()) != null) {
line = line.trim(); // removes empty character from the line
List<Integer> lineList = new ArrayList<>();
if(line.length() > 0) {
for (int i = 0; i < line.length(); i++) {
lineList.add(Main.processCharacter(line.charAt(i)));
}
board.add(lineList);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return board;
}

Write and read txt file

I'm trying to do project which contains patient information and print them if user want. But it is currently adding only one person. I want to add infinite information and I don't how can I fix it.
public static void saveChanges(ArrayList<Human> humans) throws IOException {
File veritabani = new File("patients.txt");
System.gc();
RandomAccessFile raf = new RandomAccessFile(veritabani, "rw");
raf.close();
veritabani.delete();
int ctrWhile = 0;
for (int yazdir = 0; yazdir < humans.size(); yazdir++) {
File f = new File("patients.txt");
PrintWriter pw = new PrintWriter(new FileOutputStream(f, true));
String tName=humans.get(yazdir).getNameAndSurname();
int tID=humans.get(yazdir).getTC();
int tAge=humans.get(yazdir).getAge();
boolean tInsuance=humans.get(yazdir).isInsurance();
String tComplain=humans.get(yazdir).getComplain();
if (ctrWhile== 0) {
pw.append(tName+"-"+tID+"-"+tAge+"-"+"-"+tInsuance+"-"+tComplain+"-");
ctrWhile++;
} else {
pw.append("\n"+tName+"-"+tID+"-"+tAge+"-"+"-"+tInsuance+"-"+tComplain+"-");
}
pw.close();
}
}
Each time through your loop, you appear to create a new file, write to it, and close it. Therefore each time through your loop you will overwrite the file created before.
Create the file before entering the loop, and close it after you've completed the loop; only write to it within the loop.

How can I read lines from a inputted file and then store the most recently read lines in an array?

I am trying to create a program that takes an inputted text file and reads the lines one by one. It then needs to store the most recently read lines (the number of lines depends on the parameter lines) in an array and then I need to print the lines using PrintWriter.
I started the first part but I'm not sure if I have the right idea. If anyone can help me on the second part as well that would be very appreciated!
public void RecentLines(Reader in, Writer out, int lines) throws IOException {
BufferedReader r3ader = new BufferedReader(in);
String str;
while((str = r3ader.readLine()) != null){
String[] arr = str.split(" ");
for( int i =0; i < lines; i++){
arr[i] = r3ader.readLine();
}
}
EDIT
the full question is this:
Create a program which reads lines from IN, one line at the time until the end. Your method must maintain an internal buffer that stores the most recently read lines (this might be best done using an array). Once the method reaches the end of the file, it should print the lines stored in the internal buffer into out, probably best done by creating a PrintWriter to decorate this Writer. (Except for your debugging purposes during the development stage, this method should not print anything to System.out.)
Try this one:
public void RecentLines(Reader in, Writer out, int lines) throws IOException {
BufferedReader r3ader = new BufferedReader(in);
String str;
int i=0;
String[] lineArray = new String[lines];
while((str = r3ader.readLine()) != null){
lines[i%lines] = str;
i++;
if(!r3ader.hasNextLine()){
break;
}
}
sounds like a task for data structures. Queue seems to be the best fit for a given task.
public void RecentLines(Reader in, Writer out, int lines) throws IOException {
BufferedReader r3ader = new BufferedReader(in);
BufferedWriter wout = new BufferedWriter(out);
String str;
Queue<String> content = new LinkedList<String>();
int i = 0;
while ((str = r3ader.readLine()) != null) {
if (i >= lines) {
content.remove();
}
content.add(str);
i++;
}
wout.write(String.valueOf(content));
}

java split string[] array to multiple files

I'm having a problem figuring out how to split a string to multiple files. At the moment I should get two files both with JSON data. The code below writes to the first file but leaves the second empty. Any ideas why?
public void splitFile(List<String> results) throws IOException {
int name = 0;
for (int i=0; i<results.size(); i ++) {
write = new FileWriter("/home/tom/files/"+ name +".json");
out = new BufferedWriter(write);
out.write(results.get(i));
if (results.get(i).startsWith("}")) {
name++;
}
}
}
Edit: it splits at line starting with { because that denotes the end of a JSON document.
Enhance the cut-control
Get togher this:
write = new FileWriter("/home/tom/files/"+ name +".json");
out = new BufferedWriter(write);
and this:
name++;
Check for starting, not for end
Check for line starting with {, and execute those three lines to open the file.
Remember to close and flush
If it's not the first line (i > 0) then close the last writer (write.close();).
Close the last opened writer
if (!results.isEmpty())
out.close();
Result
It should look something like this:
public void splitFile(List<String> results) throws IOException {
int name = 0;
BufferedWriter out = null;
for (int i=0; i<results.size(); i ++) {
String line = results.get(i);
if (line.startsWith("{")) {
if (out != null) // it's not the first
out.close(); // tell buffered it's going to close, it makes it flush
FileWriter writer = new FileWriter("/home/tom/files/"+ name +".json");
out = new BufferedWriter(writer);
name++;
}
if (out == null)
throw new IllegalArgumentException("first line doesn't start with {");
out.write(line);
}
if (out != null) // there was at least one file
out.close();
}
I would close your buffered writer after each completed write sequence. i.e. after each iteration through the loop before you assign write to a new FileWriter().
Closing the BufferedWriter will close the underlying FileWriter, and consequently force a flush on the data written to the disk.
Note: If you're using a distinct FileWriter per loop then I'd scope that variable to that inner loop e.g.
FileWriter write = new FileWriter("/home/tom/files/"+ name +".json");
The same goes for the BufferedWriter. In fact you can write:
BufferedWriter outer = new BufferedWriter(new FileWriter(...
and just deal with outer.
Try the following code..
public void splitFile(List<String> results) throws IOException {
int name = 0;
for (int i = 0; i < results.size(); i++) {
write = new FileWriter("/home/tom/files/" + name + ".json");
out = new BufferedWriter(write);
out.write(results.get(i));
out.flush();
out.close(); // you have to close your stream every time in your case.
if (results.get(i).startsWith("}")) {
name++;
}
}
}

Categories