I am very new to programming, my only experience this far is doing class assignments, but I want to learn how to write and read from files so I can store data.
This code is very simple and should just be printing out the contents of two txt files named "stringList" and "intlist". However, when running the code, I receive these errors:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Main.main(Main.java:14)
When experimenting earlier, I was able to make everything work fine and the txt files were reachable to the program, but for some reason it stopped working.
Here is the main method code:
import java.io.File; // Importing file class
import java.io.FileNotFoundException; // Importing ___ to throw exception from file directory
import java.util.*; // Importing java utilities
public class Main{ // Class header
public static void main(String[] args) throws FileNotFoundException { // Method header
File stringList = new File("C:\\Users\\Administrator\\eclipse-workspace\\LearningFiles\\stringList.txt"); // Creating new File object "stringList" with stringList.txt as directory
File intList = new File("C:\\Users\\Administrator\\eclipse-workspace\\LearningFiles\\intList.txt"); // Creating new File object "intList" with intList.txt as directory
Scanner s = new Scanner(stringList); // Scanner reads stringList file
Scanner s1 = new Scanner(intList); // Scanner reads intList file
System.out.println(s.next()); // Printing first word
System.out.println(s.next()); // Printing second word
System.out.println(s.next()); // Printing third word
System.out.println(s.nextLine());
System.out.println(s.nextLine()); // Printing entire second line
int num1 = s1.nextInt(); // Saving first number as integer variable
int num2 = s1.nextInt(); // Saving second number as integer variable
System.out.println(num1 + " + " + num2 + " = " + (num1+num2)); // Printing out result of integers added
} // End of public void main
} // End of main method
I've looked over many solutions in other threads but were unable to find any solutions that worked for me. I will list the solutions I have attempted:
- txt files are not named "intList.txt", so the total file is not "intList.txt.txt".
- Creating the txt files within the project folder itself.
- The txt documents are on the same plane as the scr, not in a subfolder.
- Including the direct folder path directory.
Help would be very appreciated!