Exception in thread "main" java.util.NoSuchElementException - no close() - java

I have this problem I need to resolve in the next 8 hours (max), I read a lot of posts with similar problems, but they always call to remove close(). I don't have it and my problem still exists.
package Kolokwium;
import java.io.*;
import java.util.Scanner;
public class Group{
int availableseats;
int occupiedseats= 0;
public Group() {
try (
PrintWriter writer = new PrintWriter("C:\\Users\\Galaxis\\Desktop\\lesson_name.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
) {
System.out.println("Lesson name: ");
String lesson_nameu = reader.readLine();
System.out.println("Available seats:");
String seats= reader.readLine();
writer.println(lesson_name + " " + seats);
availableseats= Integer.parseInt(seats);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
public void add_student() {
if (occupiedseats < availableseats) {
try (
PrintWriter writer = new PrintWriter("C:\\Users\\Galaxis\\Desktop\\lesson_name.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
) {
System.out.println("Write student's data: ");
String data = reader.readLine();
occupiedseats += 1;
writer.println(data);
}
catch (IOException ex) {
ex.printStackTrace();
}
} else {
System.out.println("No available seats!");
}
}
public void show_list() {
File path = new File("C:\\Users\\Galaxis\\Desktop\\lesson_name.txt");
String[] list;
list = path.list();
for (int i=0; i < list.length; i++)
System.out.println(list[i]);
}
public static void main(String[] args) {
Group group = new Group();
Scanner in = new Scanner(System.in);
System.out.println("MENU " + "1. Add student. " + "2. Show list. ");
int ichoice = in.nextInt();
if(ichoice == 1) {
group.add_student();
}
else if(ichoice == 2) {
group.show_list();
}
else {System.out.println("Wrong choice!");}
}
}
Eclipse give me this message when it comes to "int ichoice = in.nextInt();"
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Kolokwium.Grupa.main(Grupa.java:76)

public void pokaz_liste() {
File path = new File("C:\\Users\\Galaxis\\Desktop\\nazwa_przedmiotu.txt");
String[] list;
list = path.list();
for (int i=0; i < list.length; i++)
System.out.println(list[i]);
}
You are trying to get a list of files from a File. Javadoc states that, if the file instance does not point to a directory, it will return null.
https://docs.oracle.com/javase/7/docs/api/java/io/File.html#list()
And for God's sake, flush and close your streams!
For your exception: The scanner is exhausted. Try this
public Group() {
try (
PrintWriter writer = new PrintWriter("C:\\Users\\Galaxis\\Desktop\\lesson_name.txt");
) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Lesson name: ");
String lesson_nameu = reader.readLine();
System.out.println("Available seats:");
String seats= reader.readLine();
writer.println(lesson_name + " " + seats);
seats2 = Integer.parseInt(seats);
}
catch (IOException ex) {
ex.printStackTrace();
}
}

Related

Java error: method readFile() in class cannot be applied to given types

im a first year computer science student learning java and im trying to read a csv file line by line and convert each row to an object, then create an array out of these objects with each element separated by a comma ",". Program keeps returning unusual error: method readFile() in class cannot be applied to given types. im not sure what to do.
main class:
import java.io.*;
import java.util.*;
public class FlightOperations
{
static String fileName = "LaxData.csv";
public static void main(String[] args)
{
// Parsing a CSV file into Scanner class constructor
Scanner sc = new Scanner(System.in);
int fileLength = 0;
fileLength = getFileCount(fileName);
int again = 0;
Date[] LAXarray = new Date[fileLength];
LAXarray = readFile(fileName, fileLength);
menu(LAXarray, sc);
do
{
try
{
System.out.println("\n\nRun program? (1)YES (2)NO");
again = sc.nextInt();
if(again == 1)
{
menu(LAXarray, sc);
}
else
{
System.exit(1);
}
}
catch (InputMismatchException exception)
{
System.out.println("\nInvalid input");
sc.next();
}
}
while (again != 1 || again != 2);
sc.close(); // closes the scanner
}
readFile class:
public static Date[] readFile(String fileName)
{
FileInputStream fileStream = null;
InputStreamReader Read;
BuffferedReader bufRead;
/* int fileLength = getFileLength(fileName); */
String line;
Date[] LAXarray = new Date[getFileCOunt(fileLength)];
int LAXIndex = 0;
try
{
fileStream = new FileInputStream(fileName);
Read = new InputStreamReader(fileStream);
bufRead = new BufferedReader(Read);
line = bufRead.readLine();
for(int i = 1; i < fileLength; i++)
{
line = bufRead.readLine();
LAXarray[i] = processLine(line);
}
}
catch(IOException errorDetails)
{
if(fileStream != null)
{
try
{
fileStream.close();
}
catch(IOException ex2)
{
}
}
System.out.println("Error in fileProcessing: " + errorDetails.getMessage());
}
return LAXarray;
}

Why my output didn't appear? But when run, it doesn't have any error

package labweek10;
import java.io.*;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
public class arrayTourlist {
public static void main(String[] args) throws FileNotFoundException, IOException
{
try {
// read data from file
FileReader fr = new FileReader("touristData.txt");
BufferedReader br = new BufferedReader(fr);
// write/display data into file
FileWriter fw = new FileWriter("output.txt");
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
// object declaration
Tourist t[] = new Tourist[20];
int i = 0;
String input = null;
while ((input = br.readLine()) != null) {
// create class tokenizer
StringTokenizer st = new StringTokenizer(input, ";");
String touristName = st.nextToken();
int touristID = Integer.parseInt(st.nextToken());
String countryFrom = st.nextToken();
String countryRegion = st.nextToken();
boolean touristType = Boolean.parseBoolean(st.nextToken());
// create object to store data
t[i] = new Tourist(touristName, touristID, countryFrom, countryRegion, touristType);
t[i].toString();
// Display the information of tourists which are in Europe region
for (int d = 0; d < t.length; d++)
if (t[d].getRegion() == "Europe") {
pw.println("TOURIST DATA");
pw.println("------------");
pw.println("Tourist Name : " + touristName);
pw.println("Tourist ID : " + touristID);
pw.println("Country From : " + countryFrom);
pw.println("Country Region : " + countryRegion);
pw.println("Tourist Type : " + touristType);
}
}
// Count and display the number of individual tourists from China.
int countC = 0;
for (int x = 0; x < t.length; x++)
if (t[x].getType() == false && "China".equals(t[x].getCountry())) {
countC++;
}
pw.println("The number of individual tourist(s) from China is " + countC);
br.close();
pw.close();
}
catch (FileNotFoundException e) {
System.out.println("Problem :" + e.getMessage());
} catch (IOException ioe) {
System.out.println("Problem :" + ioe.getMessage());
} catch (NoSuchElementException nsee) {
}
catch (NullPointerException npe) {
}
}
}

BufferedRead stuck in infinite loop

I am doing a class project that is supposed to read a .txt file and have the program also replace some text. But after I run the code it just constantly runs in a loop and only reading one line of the text. Not really sure what I did wrong but I think it's the reader part of my code.
public class FormLetter
{
final static int MAX_LINES = 20;
final static int NUM_INSERTIONS = 4;
String[] formLetter = new String[MAX_LINES];
int lines = 0;
public static void main(String[] args)
{
FormLetter letter1 = new FormLetter("formLetter..txt");
FormLetter letter2 = new FormLetter("longLetter.txt");
FormLetter letter3 = new FormLetter("formLetter.txt");
letter3.generateLetter("insertions.txt");
}
public FormLetter(String formFileName)
{
Scanner formFileIn;
String line;
Path file = Paths.get("H:\\Eclipse\\Programming Project 1\\formLetter.txt");
InputStream input = null;
try
{
formFileIn = new Scanner(new FileReader(formFileName));
while (lines < MAX_LINES && formFileIn.hasNextLine())
{
input = Files.newInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
Charset.defaultCharset();
line = reader.readLine();
System.out.println(line);
}
if (formFileIn.hasNextLine())
{
System.out.println("File " + formFileName + " is too large to process.\n");
}
}
catch(FileNotFoundException fnfe)
{
System.out.println("Cannot open " + formFileName + "\n");
}
catch(IOException ioe)
{
System.out.println("Error reading from file" + formFileName);
}
}
As mentioned in the comments I was using two readers by mistake causing an infinite loop. I removed the second reader and during my loop now only put to output the next line from the file.
import java.util.Scanner;
import java.io.*;
import java.nio.file.*;
import java.nio.charset.*;
import java.nio.file.StandardOpenOption;
public class FormLetter
{
final static int MAX_LINES = 20;
final static int NUM_INSERTIONS = 4;
String[] formLetter = new String[MAX_LINES];
int lines = 0;
public static void main(String[] args)
{
FormLetter letter1 = new FormLetter("formLetter..txt");
FormLetter letter2 = new FormLetter("longLetter.txt");
FormLetter letter3 = new FormLetter("formLetter.txt");
letter3.generateLetter("insertions.txt");
}
public FormLetter(String formFileName)
{
Scanner formFileIn;
String line;
try
{
formFileIn = new Scanner(new FileReader("H:\\Eclipse\\Programming Project 1\\formLetter.txt"));
while (lines < MAX_LINES && formFileIn.hasNextLine())
{
System.out.println(formFileIn.next());
}
if (formFileIn.hasNextLine())
{
System.out.println("File " + formFileName + " is too large to process.\n");
}
}
catch(FileNotFoundException fnfe)
{
System.out.println("Cannot open " + formFileName + "\n");
}
catch(IOException ioe)
{
System.out.println("Error reading from file" + formFileName);
}
}

Increase count when reading all the files in a directory & print distinct Stack trace

Java - 1.6
I am reading a bunch of log files from a directory and printing in this manner.
Class name:- GSAItemDescriptor.java Line Number:- 7521
ConcurrentUpdateException occurence count: 249
ConcurrentUpdateException stack trace count: 1241
at
atg.adapter.gsa.GSAItemDescriptor.updateItem(GSAItemDescriptor.java:7521)
at
atg.adapter.gsa.ItemTransactionState.updateItemState(ItemTransactionState.java:984)
at
atg.adapter.gsa.GSATransaction.beforeCompletion(GSATransaction.java:452)
My Problem
1) occurence count and stack trace count starts from 1 when it reads a new log file.
2) How do I print the stack trace only once when it has already occurred and just increase the count, which works while reading the all the log files.
My Code
class demoPractice{
public void getConcurrentUpdateException(String sPath, BufferedWriter out2) {
BufferedReader br = null;
try {
File f = new File(sPath);
if (f.isFile()) {
FileInputStream fis = new FileInputStream(sPath);
DataInputStream dis = new DataInputStream(fis);
br = new BufferedReader(new InputStreamReader(dis));
String strLine;
String sPattern = "at (.*)\\.(.*)\\(([^:]*):?([\\d]*)\\)";
Pattern p = Pattern.compile(sPattern);
boolean bFlag = false;
int iCount = 0;
int totCount = 0;
int exCount = 0;
while ((strLine = br.readLine()) != null) {
if ((strLine.contains("atg.repository.ConcurrentUpdateException"))){
exCount++;
bFlag = true;
}
if (bFlag) {
if ((strLine.contains("**** Warning") || (strLine.contains("**** Error")))) {
Matcher m = p.matcher(strLine);
if (m.find()) {
totCount++;
iCount++;
if ((iCount == 1)) {
out2.append('\n');
out2.write("Class name:- " + m.group(3));
out2.append('\n');
out2.write("Line Number:- " + m.group(4));
out2.append('\n');
out2.write("ConcurrentUpdateException occurence count: " + exCount);
out2.append('\n');
out2.write("ConcurrentUpdateException stack trace count: " + totCount);
out2.append('\n');
}
if (strLine.contains("at")) {
String sTemp[] = strLine.split("\\s+at+\\s+");
strLine = sTemp[1];
strLine = "at " + strLine;
}
out2.append('\n');
out2.write(strLine);
out2.append('\n');
if (iCount == 5) {
bFlag = false;
iCount = 0;
}
}
}
}
}
}
}
catch (Exception e) {
System.out.println(e.getMessage());
}
finally {
try {
if (br != null) {
br.close();
}
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
public static void main(String args[]){
try {
File logsFolder = new File("D:\\Edu_logs\\Edu_logs\\");
demoPractice objgetExc = new demoPractice();
PrintStream out2 = null;
out2 = new PrintStream(new FileOutputStream("D:\\Edu_logs\\Edu_logs\\practice.txt"), true);
FileWriter ff = new FileWriter("D:\\Edu_logs\\Edu_logs\\practice.txt");
BufferedWriter bw = new BufferedWriter(ff);
if (logsFolder.isDirectory()) {
File[] listfiles = logsFolder.listFiles();
for (File tempFileName : listfiles) {
String sPath = tempFileName.getAbsolutePath();
objgetExc.getConcurrentUpdateException(sPath, bw);
}
System.out.println("Done Prosessing");
}
out2.close();
}
catch (Exception e) {
}
}
}

Getting InputMismatchException when reading an int from a file with Scanner

I am working on a program which imports a library from a generated file.
The file generates properly and is found by Scanner. The first line has a single int as written by
pw.println(cdarchive.getNumber());
Elsewhere in the code. This part seems to work fine.
This is the error I'm getting:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at no.hib.dat102.IO.readFile(IO.java:26)
at no.hib.dat102.Menu.start(Menu.java:34)
at no.hib.dat102.CdArchiveClient.main(CdArchiveClient.java:10)
The line it refers to is
int libSize = in.nextInt();
This is my method:
public class IO {
static final String DELIMITER = "#";
public static CdArchiveADT readFile(String filename) {
Scanner in = null;
CdArchiveADT cda = null;
try
{
File f = new File(filename+".txt");
in = new Scanner(f);
System.out.println(f);
in.useDelimiter(DELIMITER);
int libSize = in.nextInt();
System.out.println("libSize" + libSize);
cda = new CdArchive(libSize);
for (int i=0; i<libSize;i++) {
int inId = in.nextInt();
String inTitle= in.next();
String inArtist = in.next();
String inLabel = in.next();
String inGenre = in.next();
int inYear = in.nextInt();
in.nextLine();
cda.addCd(new CD(inId, inArtist, inTitle, inYear, inGenre, inLabel));
System.out.println("Closing Scanner (input)");
in.close();
}
}
catch (FileNotFoundException e){
System.out.println("Config file not found!");
e.printStackTrace();
}
return cda;
}
EDIT:
This is the method that writes to the file:
public static void writeFile(CdArchiveADT cdarchive, String filename) throws IOException {
PrintWriter pw = null;
File file = null;
try {
file = new File(filename +".txt");
// Create the file if it does not already exist
file.createNewFile();
// Writing metadata
pw = new PrintWriter(new FileWriter(file, false));
pw.println(cdarchive.getNumber());
// Writing data, if CdArchive is not empty
if (cdarchive.getCdTable()[0] != null) {
for (int i = 0; i<cdarchive.getNumber(); i++ ) {
CD c = cdarchive.getCdTable()[i];
pw.print(c.getId()); pw.print(DELIMITER);
pw.print(c.getTitle()); pw.print(DELIMITER);
pw.print(c.getArtist()); pw.print(DELIMITER);
pw.print(c.getLabel()); pw.print(DELIMITER);
pw.print(c.getGenre()); pw.print(DELIMITER);
pw.print(c.getYear()); pw.println(DELIMITER);
}
}
}
catch (FileNotFoundException e)
{
System.out.println("File not found!");
e.printStackTrace();
}
finally
{
if ( pw != null )
{
System.out.println("Closing PrintWriter");
pw.close();
}
}
}
I got a working example:
public static void main(String[] args) {
// write
String delimiter = "#";
StringWriter stringWriter = new StringWriter();
PrintWriter pw = new PrintWriter(stringWriter);
pw.println(3);
for (int i = 0; i < 3; i++) {
pw.print("id " + i);
pw.print(delimiter);
pw.print("titel " + i);
pw.print(delimiter);
pw.print("artist " + i);
pw.println(delimiter);
}
String theString = stringWriter.toString();
System.out.println(theString);
try {
pw.close();
stringWriter.close();
} catch (IOException e) {
// ignore in example
}
// read
Scanner in = new Scanner(theString);
in.useDelimiter("\\s*#\\s*|\\s*\n\\s*"); // add new line as delimiter aswell
int libSize = in.nextInt();
for (int i = 0; i < libSize; i++) {
String inId = in.next();
String inTitle = in.next();
String inArtist = in.next();
in.nextLine();
System.out.println("read: " + inId + ", " + inTitle + ", " + inArtist);
}
in.close();
}
The point is to add new line to the used delimiters aswell
try to use
static final String DELIMITER = "\\s*#\\s*";
Otherwise any leading or trailing spaces will cause that error.

Categories