Resource leak 'blank' never closed - java

It seems that when I create my scanner I get this error. I have tried to solve this by searching the error name, but have so far been unsuccessful in getting the message to stop appearing.
Code:
import java.util.Scanner;
public class PrintQueue {
//Instance variables
private Queue<Job> pq;
//Constructor
public PrintQueue() {
pq = new Queue<Job>();
}
//Adds a job object to the end of the queue
public void lpr(String owner, int jobId) {
Job j = new Job(owner, jobId);
pq.enqueue(j);
}
//Enumerates the queue
public void lpq() {
Job curr = pq.first();
for (int i = 0; i < pq.size(); i++) {
System.out.println(curr);
curr = pq.next();
}
}
//Removes the first entry in the queue if the input integer matches the integer contained within the job object
public void lprm(int jobId) {
if (pq.first().getJobId() == (jobId))
pq.dequeue();
else
System.out.println("Unable to find jobId.");
}
//Removes all objects that contain the input String
public void lprmAll(String owner) {
Job curr = pq.first();
for (int i = 0; i < pq.size(); i++) {
if (curr.getOwner().equals(owner))
pq.dequeue();
curr = pq.next();
}
}
//Demo
public static void main(String[] args) {
Scanner k = new Scanner(System.in);
PrintQueue myPQ = new PrintQueue();
String name;
int id;
for (int i = 1; i <= 5; i++) {
System.out.print("Enter owner and id: ");
name = k.next();
id = k.nextInt();
myPQ.lpr(name, id);
}
System.out.println("Print Queue");
myPQ.lpq();
myPQ.lprm(101);
myPQ.lprmAll("ronaldinho");
System.out.println("Print Queue");
System.out.println("\n\n");
myPQ.lpq();
}
}
Part where I get the error:
Scanner k = new Scanner(System.in);

That's because you're never closing the Scanner. Change your code to:
Scanner k = null;
try {
k = new Scanner(System.in);
//do stuff with k here...
} finally {
if( k != null )
k.close();
}

It seems that it is rather warning than error. However it is good practice to solve it.
Actually you just have to call k.close(); in the end of your method.
The best practice is to call close in finally block: this guarantees that the resource is closed whenever exception is thrown or not;
Scanner k = null;
try {
k = new Scanner(System.in);
........
} finally {
if (k != null) {
k.close();
}
}
Fortunately java 7 provides makes this syntax less verbose:
try (
Scanner k = new Scanner(System.in);
) {
.... // use k
}
When object of any class that implements Closable is created in special section of try block that marked with regular brackets () you do not have to write finally block: it is added by compiler.

Related

Finding whether two strings are connected in a Hashmap<String, ArrayList<String>> through recursion?

The question is asking us to find whether a connection between two airlines are possible. For the input code, they give us the list of airlines and then which airlines are connected to which. I was able to read everything into the scanner and make a Hashmap of String values connecting to a String ArrayList, in order to compensate for duplicating keys. There is no issues with the Hashmap, as after reading out all of the keys and the corresponding values in their ArrayList, everything was matching up.
Here is the printed Hashmap below(some airlines are not listed below because they have no connections, ie: southwest):
continental, [america_west, air_china, alaska, air_france, virgin_atlantic]
austrian_airways, [delta]
virgin_atlantic, [air_france]
delta, [swiss_air, austrian_airways, air_canada]
america_west, [mesa, alaska, twa]
The issue is calling the recursion in which, given two Strings of Airlines, find if there is a connection. My recursion below is checking whether there is an initial connection between the Airlines, and it not, recursively go inwards. However the error seems to be a Stack Overflow Error. I do not understand why it would overflow
if the test case gives Airlines {"delta" "america_west"},{"continental" "mesa"},{"southwest" "delta"},{"twa" "air_france"}.
public static boolean recur(String a, String b) {
boolean connection = false;
if(partners.containsKey(a)&&partners.get(a).contains(b)) {return true;}
for(String airlines: (ArrayList<String>)partners.get(a)) {
if(partners.containsKey(airlines))
recur(airlines,b);
}
return connection;
}
Edit:
I'm sorry I didn't include all of the code, it's my first time uploading, and I felt that it was a bit long.
public class airlinePartners{
static Map<String, ArrayList> partners = new HashMap<String, ArrayList>();
static String returnT = "PARTNERS\n";
static String returnF = "No miles for you\n";
int number = 0;
public static void readIn() throws Exception{
Scanner sc = new Scanner(new File("partners.dat"));
String[] temp = new String[2];
int airline = sc.nextInt();
for(int i = 0; i < airline; i++) {
sc.next();
}
int partner = sc.nextInt();
sc.nextLine();
for(int i = 0; i < partner; i++) {
temp = sc.nextLine().split(" ");
ArrayList<String> temps = new ArrayList<String>();
if(partners.containsKey(temp[0])) {
partners.get(temp[0]).add(temp[1]);
}
else {
temps.add(temp[1]);
partners.put(temp[0], temps);
}
}
Iterator<Map.Entry<String, ArrayList>> i = partners.entrySet().iterator();
while(i.hasNext()){String key = i.next().getKey();
System.out.println(key+", "+partners.get(key));
}
int repeat = sc.nextInt();
sc.nextLine();
for(int m = 0; m < repeat;m++) {
temp= sc.nextLine().split(" ");
//System.out.println(temp[0] + " "+ temp[1]);
if(recur(temp[0], temp[1])) {
System.out.println(returnT);
}
else {
System.out.println(returnF);
}
}
}
public static boolean recur(String a, String b) {
boolean connection = false;
if(partners.containsKey(a)&&partners.get(a).contains(b)) {return true;}
for(String airlines: (ArrayList<String>)partners.get(a)) {
if(partners.containsKey(airlines))
recur(airlines,b);
}
return connection;
}
public static void main(String args[]) throws Exception
{
new airlinePartners().readIn();
}
}

Sequential Search of an Array

i am in desperate need of more help this week. My professor is sub par and makes no effort to clear things up.
The Problem:
import a file and search for a specific piece of data that is requested by a user.
The output must return something similar to:
Sequential found ID number 77470, and its price is $49.55.
or
Sequential did not find ID number 77777.
I have no idea where to go from here, or even if this is correct....
public class MainClass
{
public static void main(String[] args)
{
Payroll acmePay = new Payroll();
Scanner myScanner = new Scanner(System.in);
int target;
acmePay.loadEmpNums();
System.out.println("Enter the product number you would like to search: ");
target = myScanner.nextInt();
System.out.print(acmePay.seqSearch(target));
myScanner.close();
}//END main
}//END class MainClass
Payroll Class:
public class Payroll
{
private int[] empNums = new int[1000];
private int empCount = 0;
Payroll(){} //Currently nothing done in constructor
public void loadEmpNums()
{
String name;
double salary;
empCount = 0; //Just to make sure!
try
{
String filename = "employees.dat";
Scanner infile = new Scanner (new FileInputStream(filename));
while (infile.hasNext())
{
//Read a complete record
empNums[empCount] = infile.nextInt();
name = infile.nextLine();
salary = infile.nextDouble();
//Increment the count of elements
++empCount;
}
infile.close();
}
catch (IOException ex)
{
//If file has problems, set the count to -1
empCount = -1;
ex.printStackTrace();
}
}//END loadEmpNums
public int seqSearch (int target)
{
int ind = 0;
int found = -1;
while (ind < empCount) {
if(target==empNums[ind])
{
found = ind;
ind = empCount;
}
else
{
++ind;
}
}
return found;
}
}//END class Payroll
Are you reading in from a txt file or are they entering the data in when you run the program?

Object Not Resolved to a Local Variable (Java)

I'm writing a Java program to process each state of a search graph, but can't seem to create instances of State inside one of my loops.
The program takes numbers from a file, line by line, and converts each number into a State object, however I'm getting an error State cannot be resolved to a variable
public class ABSrch {
static HashMap<Integer, State> states = new HashMap<Integer, State>();
public static void main(String[] args) {
File file = new File("D:\\Stuff\\TextExample.txt");
int level = 0, depthBound = 0, stateNumber = 0;
try {
Scanner s = new Scanner(file);
depthBound = Integer.parseInt(s.nextLine().split(" ")[1]);
s.close(); s = new Scanner(file);
while(s.hasNextLine()) {
String line = s.nextLine();
String[] tokens = line.split(" ");
if(level >= 0 && level <= 7) {
if(level == 0) tokens = line.split(" |7");
}
for(int i = 0; i < tokens.length; i++)
State parent = new State(false,0,0,null); //error: State not resolved to variable
level++;
}
s.close();
} catch (FileNotFoundException e) {
System.err.println("File not found");
}
}
}
State class:
public class State {
private boolean max;
private int name, value;
private State parent;
private ArrayList<State> children;
public State(boolean max, int name, int value, State parent) {
this.max = max;
this.name = name;
this.parent = parent;
children = new ArrayList<State>();
}
public boolean isMax() { if(max == true) return true; else return false; }
public void setMax(boolean max) { this.max = max; }
public int getValue() { return value; }
public void setValue(int value) { this.value = value; }
public int getName() { return name; }
}
for(int i = 0; i < tokens.length; i++)
State parent = new State(false,0,0,null);
You cannot have initialization inside for loop without braces. It counts as local variable declaration and is not allowed in Java loops. This is to prevent you from using references which are valid only during object initialization. After iterating over the loop, references to the object created in previous iteration would be lost so garbage collector would soon destroy this objects.
This, hovewer, should work (but it is a bad practice and probably won't do what you expect from it):
for(int i = 0; i < tokens.length; i++) {
State parent = new State(false,0,0,null);
}
Joshua Bloch in his book Java Puzzlers provides an excellent explanation:
A local variable declaration looks like a statement but technically
speaking is not; it is a local variable declaration statement [JLS
14.4]. The syntax of the language does not allow a local variable declaration statement as the statement repeated by a for, while, or do
loop [JLS 14.12-14]. A local variable declaration can appear only as a
statement directly within a block. (A block is a pair of curly braces
and the statements and declarations contained within it.)

Filtering/sorting a collection through object fields?

I'm not sure why this isn't working. I'm not sure if it's a problem with the printing, or if it's a problem with the methods themselves.
I am making a program that takes a collection of songs and filters or sorts it according to a given user input. The user should be able to input multiple commands to further narrow down the list.
My filterRank and filterYear methods work perfectly fine, but the other methods end up printing a seemingly random selection of songs that do not change regardless of what is inputted as the title or artist to be filtered by, which generally appears only after an extremely long waiting period and a long series of spaces.
Even after this amalgam of songs is printed, the program does not terminate, and periodically outputs a space in the console, as in a System.out.println() statement were being continuously run.
If I remove the code that configures the output file, which is a requirement for the project, the methods fail to print entirely. Regardless of either of these changes, filterRank and filterYear continue to work perfectly.
This problem also occurs with my sort methods. No matter what sort method I run, it still prints out the spaces and the random songs, or nothing at all.
Is there something I'm missing? I've tried printing out variables and strategically inserting System.out.println("test") in my program to determine what the program is, but it seems as though it's parsing the input correctly, and the methods are indeed being successfully run.
I've been otherwise unable to isolate the problem.
Can I get assistance in determining what I'm missing? Despite poring over my code for two hours, I just can't figure out what the logical error on my part is.
Here is the relevant code:
The main class:
public static void main(String[] args) throws FileNotFoundException, IOException{
//user greeting statements and instructions
//scanning file, ArrayList declaration
Scanner input = new Scanner(System.in);
while (input.hasNextLine()) {
int n = 0;
SongCollection collection = new SongCollection(songs);
String inputType = input.nextLine();
String delims = "[ ]";
String[] tokens = inputType.split(delims);
for (int i = 0; i < tokens.length; i++) {
n = 0;
if (n == 0) {
if ((tokens[i]).contains("year:")) {
collection.filterYear(Range.parse(tokens[i]));
n = 1;
}// end of year loop
if ((tokens[i]).contains("rank:")) {
collection.filterRank(Range.parse(tokens[i]));
n = 1;
}// end of rank
if ((tokens[i]).contains("artist:")) {
collection.filterArtist(tokens[i]);
n = 1;
}// end of artist
if ((tokens[i]).contains("title:")) {
collection.filterTitle(tokens[i]);
n = 1;
}// end of title
if ((tokens[i]).contains("sort:")) {
if ((tokens[i]).contains("title")) {
collection.sortTitle();
n = 1;
}// end of sort title
if ((tokens[i]).contains("artist")) {
collection.sortArtist();
n = 1;
}// end of sort artist
if ((tokens[i]).contains("rank")) {
collection.sortRank();
n = 1;
}// end of sort rank
if ((tokens[i]).contains("year")) {
collection.sortYear();
n = 1;
}// end of sort year
}//end of sort
}// end of for loop
}// end of input.hasNextline loop
/*final PrintStream console = System.out; //saves original System.out
File outputFile = new File("output.txt"); //output file
PrintStream out = new PrintStream(new FileOutputStream(outputFile)); //new FileOutputStream
System.setOut(out); //changes where data will be printed
*/ System.out.println(collection.toString());
/*System.setOut(console); //changes output to print back to console
Scanner outputFileScanner = new Scanner(outputFile); //inputs data from file
while ((outputFileScanner.hasNextLine())) { //while the file still has data
System.out.println(outputFileScanner.nextLine()); //print
}
outputFileScanner.close();
out.close();*/
}
}// end of main
}// end of class
The SongCollection Class, with all of its respective filter and sort methods:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class SongCollection {
ArrayList<Song> songs2;
ArrayList<Song> itemsToRemove = new ArrayList<Song>(); // second collection
// for items to
// remove
public SongCollection(ArrayList<Song> songs) { // constructor for SongCollection
System.out.println("Test");
this.songs2 = songs;
}
public void filterYear(Range r) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if (song1.year > (r.getMax()) || (song1.year) < (r.getMin())) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
}
public void filterRank(Range r) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if (song1.rank > (r.getMax()) || (song1.rank) < (r.getMin())) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
}
public void filterArtist(String s) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if ((!(((song1.artist).contains(s))))) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
}
public void filterTitle(String s) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if ((!(((song1.title).contains(s))))) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
}
public void sortTitle() {
Collections.sort(songs2, SongComparator.byTitle()); // now we have a sorted list
}
public void sortRank() {
Collections.sort(songs2, SongComparator.byRank()); // now we have a sorted list
}
public void sortArtist() {
Collections.sort(songs2, SongComparator.byArtist()); // now we have a sorted list
}
public void sortYear() {
Collections.sort(songs2, SongComparator.byYear()); // now we have a sorted list
}
public String toString() {
String result = "";
for (int i = 0; i < songs2.size(); i++) {
result += " " + songs2.get(i);
}
return result;
}
}
SongComparator Class:
import java.util.Comparator;
public class SongComparator implements Comparator<Song> {
public enum Order{
YEAR_SORT, RANK_SORT, ARTIST_SORT, TITLE_SORT
}
private Order sortingBy;
public SongComparator(Order sortingBy){
this.sortingBy = sortingBy;
}
public static SongComparator byTitle() {
return new SongComparator(SongComparator.Order.TITLE_SORT);
}
public static SongComparator byYear() {
return new SongComparator(SongComparator.Order.YEAR_SORT);
}
public static SongComparator byArtist() {
return new SongComparator(SongComparator.Order.ARTIST_SORT);
}
public static SongComparator byRank() {
return new SongComparator(SongComparator.Order.RANK_SORT);
}
#Override
public int compare(Song song1, Song song2) {
switch (sortingBy) {
case YEAR_SORT:
System.out.println("test");
return Integer.compare(song1.year, song2.year);
case RANK_SORT:
System.out.println("test");
return Integer.compare(song1.rank, song2.rank);
case ARTIST_SORT:
System.out.println("test");
return song1.artist.compareTo(song2.artist);
case TITLE_SORT:
System.out.println("test");
return song1.title.compareTo(song2.title);
}
throw new RuntimeException(
"Practically unreachable code, can't be thrown");
}
}
After you output the filtered collection, your program doesn't terminate because you are still in a while loop looking for the next user input line. This is basically what your program is doing:
while (input.hasNextLine()) {
// stuff happens here
System.out.println(collection.toString());
/*
* System.setOut(console); //changes output to print back to console Scanner outputFileScanner = new Scanner(outputFile); //inputs data from file while ((outputFileScanner.hasNextLine()))
* { //while the file still has data System.out.println(outputFileScanner.nextLine()); //print } outputFileScanner.close(); out.close();
*/
}

problem with print output to a .txt file in java

i write a program in netbeans, but i can not print it in a .txt file.
indead, my programming codes do note work properly.
i think the problem is in last lines of codes.
here is my codes:
import java.io.*;
import java.util.*;
public class converttopathbased_bfs
{
static String START;
static String END;
static int numberOfNodes;
static int numberOfArcs;
static int numberOfCommodities;
static int OriginDestinationOfCommodities[][] = new int[numberOfCommodities][2];
static int neighborhoods[][] = new int[numberOfNodes][numberOfNodes];
static int variableCosts[][] = new int[numberOfNodes][numberOfNodes];
static int capacities[][] = new int[numberOfNodes][numberOfNodes];
static int fixedCosts[][] = new int[numberOfNodes][numberOfNodes];
static int demandOfCommodities[] = new int[numberOfCommodities];
java.io.File file = new java.io.File("pathBasedTest.txt");
java.io.PrintWriter output;
public static void main(String[] args) throws Exception
{
java.io.File data = new java.io.File("samples//test.txt");
Scanner scanner = new Scanner(data);
numberOfNodes = scanner.nextInt();
numberOfArcs = scanner.nextInt();
numberOfCommodities = scanner.nextInt();
Graph graph = new Graph();
for (int i = 0; i < numberOfArcs; i++)
{
int m = scanner.nextInt() - 1;
int n = scanner.nextInt() - 1;
String S = "";
String E = "";
S = Integer.toString(m + 1);
E = Integer.toString(n + 1);
scanner.nextInt();
scanner.nextInt();
scanner.nextInt();
graph.addEdge(S, E);
scanner.nextInt();
scanner.nextInt();
}
for (int i = 0; i < numberOfCommodities; i++)
{
converttopathbased_bfs.START = scanner.next();
converttopathbased_bfs.END = scanner.next();
scanner.nextInt();
LinkedList<String> visited = new LinkedList();
visited.add(START);
new converttopathbased_bfs().breadthFirst(graph, visited);
}
}
private void breadthFirst(Graph graph, LinkedList<String> visited) throws Exception
{
output = new java.io.PrintWriter (file) ;
LinkedList<String> nodes = graph.adjacentNodes(visited.getLast());
// examine adjacent nodes
for (String node : nodes)
{
if (visited.contains(node))
{
continue;
}
if (node.equals(END))
{
visited.add(node);
printPath(visited);
visited.removeLast();
break;
}
}
// in breadth-first, recursion needs to come after visiting adjacent nodes
for (String node : nodes)
{
if (visited.contains(node) || node.equals(END))
{
continue;
}
visited.addLast(node);
breadthFirst(graph, visited);
visited.removeLast();
}
}
private void printPath(LinkedList<String> visited)
{
for (String node : visited)
{
output.printf("s", node);
output.printf(" ");
}
output.printf("\n");
}
}
The main problem is that you are creating output every time breadhtfirst is called. You should only create it once at the beginning of your code, and then close it at the end of your code.
You probably want for those last few lines:
for (String node : visited)
{
output.printf("%s ", node);
}
output.println();
But we need a little more information to be sure.
You will also want to close the file at the end of your code.
output.close();
You will want to add the following two lines:
output.flush();
output.close();
Convert it to a BufferedWriter and use the append method.
Try closing your filestream:
output.close()

Categories