What would be the problem with this code?
import java.io.*; import java.util.Scanner; /** * Write a description of class capital here. * * @author (your name) * @version (a version number or a date) */ public class capital {public static void main(String[] args) throws FileNotFoundException { // ask the user for the search string Scanner keyboard = new Scanner(System.in); System.out.print("Please enter part of the country name: "); String searchString = keyboard.next().trim().toLowerCase(); // open the data file File countryFile = new File("CountryData.csv"); // create a scanner from the file Scanner countryInput = new Scanner(countryFile); // set up the scanner to use "," as the delimiter countryInput.useDelimiter("[\\r,]"); // read one line of data at a time, processing each line while(countryInput.hasNext()) { // read the 3 parts of the line // first the country and capital String country = countryInput.next(); String capital = countryInput.next(); // then the population info int population = countryInput.nextInt(); // print out the info if the country name contains the input search string if(country.toLowerCase().contains(searchString)) { System.out.println(country + "\t" + capital + "\t" + population); } // be polite and close the file countryInput.close(); } } }
where I get this error:
java.lang.IllegalStateException: Scanner closed
at java.util.Scanner.ensureOpen(Scanner.java:1115)
at java.util.Scanner.hasNext(Scanner.java:1379)
at capital.main(capital.java:28)
It doesnt seem to read the file, which was working before.
And would anyone tell me how I can get a message to appear if there is no match from the file? If I use an else statement, the message appears on every line, causing the same message to appear 5 times.
Basically the program is meant to read the file, user inputs part of the name, it shows user the information. If it cannot find it, it needs to show a helpful message.
--- Update ---
I really need help. Its due tomorrow, this is really stressful.