problem with print output to a .txt file in java - 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()

Related

Add String Input to Array Java

I'm trying to build an Array with 5 strings in there; indexed 0 - 4. After this I need to shuffle the different pieces in the array rounds. The problem that I'm having is that is creating 5 different arrays I think? Could someone explain to me what I'm doing wrong and how to fix it?
To give an better understanding; this is the input of the fileScanner:
5,4 4,5 8,7=6,3 3,2 9,6 4,3=7,6=9,8=5,5 7,8 6,5 6,4
class Pirate {
public static final int MAX_ELEMENTS = 5;
String [] coordinateArray;
int position;
PrintStream out;
Pirate() {
out = new PrintStream(System.out);
}
void addInOrginalArray (String coordinateRowInput) {
coordinateArray = new String [MAX_ELEMENTS];
int position = 0;
coordinateArray[position] = coordinateRowInput;
for (int i = 0; i < coordinateArray.length; i++) {
position += 1;
System.out.println(i + "\t" + coordinateArray [i]);
}
}
void start() {
Scanner fileScanner = UIAuxiliaryMethods.askUserForInput().getScanner();
fileScanner.useDelimiter("=");
while (fileScanner.hasNext()) {
String coordinateRowInput = fileScanner.next();
Scanner coordinateInputScanner = new Scanner(coordinateRowInput);
addInOrginalArray(coordinateRowInput);
}
}
public static void main(String[] argv) {
new Pirate().start();
}
}

How to fix my my loadData method with my main class

I am trying to load data from a txt file and it will only read one line of the txt file. When I specify what the int I variable is in my for loop within my loadData method it will print that particular line. I am not sure why it won't just add and print all my data.
I tried using an outer for loop to see if would print and add the data that way, but no luck
import java.io.*;
import java.util.*;
public class BingoSortTest
{
static BingoPlayer [] test;
public static void main (String [] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
test = new BingoPlayer [10];
loadData();
System.out.print(Arrays.toString(test));
}
public static void loadData() throws IOException
{
Scanner S = new Scanner(new FileInputStream("players.txt"));
double houseMoney = S.nextDouble();
S.nextLine();
int player = S.nextInt();
S.nextLine();
for(int i = 0; i < test.length; i++)
{
String line = S.nextLine();
String [] combo = line.split(",");
String first = combo [0];
String last = combo [1];
double playerMoney = Double.parseDouble(combo[2]);
BingoPlayer plays = new BingoPlayer(first, last, playerMoney);
add(plays);
}
}
public static void add(BingoPlayer d)
{
int count = 0;
if (count< test.length)
{
test[count] = d;
count++;
}
else
System.out.println("No room");
}
}
Here is the contents of the txt file I am using:
50.00
10
James,Smith,50.0
Michael,Smith,50.0
Robert,Smith,50.0
Maria,Garcia,50.0
David,Smith,50.0
Maria,Rodriguez,50.0
Mary,Smith,50.0
Maria,Hernandez,50.0
Maria,Martinez,50.0
James,Clapper,50.0
Every Time you put a BingoPlayer at Index 0 .
public static void add(BingoPlayer d)
{
int count = 0; // <-------------------- Here
if (count< test.length)
{
test[count] = d;
count++;
}
else
System.out.println("No room");
}
you have to define static counter variable where array of BingoPlayer is defined.
define count variable static
static BingoPlayer [] test;
static int count = 0;
and chane the add function definition like this.
public static void add(BingoPlayer d)
{
if (count< test.length) {
test[count] = d;
count++;
}
else
System.out.println("No room");
}

How to pass value of input file and pass it to another method

This is what I have tried:
I have tried to print matrix in isDeadlock method ,output is all zeros and seems like the value that called matrix after reading file is not kept and cannot be used in method.
import java.io.*;
import java.util.*;
public class Findcycle {
static int[][] matrix = new int[10000][10000];
public static void main(String[] args) {
{
int x=0, y=0;
try
{
BufferedReader in = new BufferedReader(new FileReader("TestCase1.txt"));
String line;
while ((line = in.readLine()) != null)
{
String[] values = line.split(",");
for (String str : values)
{
int str_int = Integer.parseInt(str);
matrix[x][y]=str_int;
System.out.print(matrix[x][y] + " ");
y=y+1;
}
System.out.println("");
x=x+1;
}
in.close();
System.out.println(isDeadlock(matrix));
}catch( IOException ioException ) {}
}
}
public static class Node{
int id;
List<Node> getNodes = new ArrayList<Node>();
public Node(int id){
this.id=id;
}
}
public static String isDeadlock(int matrix[][]){
List<Node> nodes = new ArrayList<Node>();
for(int i=0;i<matrix.length;i++) {
for(int j=0;j<matrix[i].length;j++) {
System.out.println(matrix[i][j]);
}
}
...
}
What should I do to fix this problem?
I am a newbie.
Thank you so much
When you are reading the file and filling the matrix you are not resetting y for each new line. So after x=x+1; you need to add y = 0; otherwise y will just continue to grow and all consecutive line will have there data offset more and more to the right.
Not a bug but since matrix is a static variable you don't need to send it as a parameter to isDeadlock.

Word-Puzzle (ArrayList problems)

So I have been creating a Word-Puzzle which I recently got stuck on a index out of bounds problem. This has been resolved however the program is not doing what I would like it to do. The Idea i that the test class will print 3 words in an array e.g. [FEN, GNU, NOB] (and yes they are apparently real english words). Then check to see if the first letter of each word combined is a word and so forth e.g. FGN if so add it to the next ArrayList else start again. Ideal output would be [FEN, GNU, NOB] [FGN, ENO, NUB] for example. However the current output is [FEN, GNU, NOB] [SOY, SOY, SOY] or [FEN, GNU, NOB] [].
The Test Class
public class Test_WordPuzzleGenerator {
public static void main(String[] args) throws FileNotFoundException {
System.out.println("Test 1: size 3");
int size = 3;
Puzzle.WordPuzzleGenerator.generatePuzzle(size);
}
}
WordGenerator:
public class WordPuzzleGenerator {
static ArrayList<String> wordList = new ArrayList<String>();
public static void generatePuzzle(int size) throws FileNotFoundException {
ArrayList<String> puzzleListY = new ArrayList<String>();
ArrayList<String> puzzleListX = new ArrayList<String>();
String randomXWord;
String letterSize = "" + size;
makeLetterWordList(letterSize);
boolean finished = false;
while ( !finished ) {
finished = true;
puzzleListX.clear();
puzzleListY.clear();
for (int i = 0; i < size; i++) {
int randomYWord = randomInteger(wordList.size());
String item = wordList.get(randomYWord);
puzzleListY.add(item);
}
for (int i = 0; i < puzzleListY.size(); i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < puzzleListY.size(); j++) {
sb.append(puzzleListY.get(j).charAt(i));
}
randomXWord = sb.toString();
if (!wordList.contains(randomXWord)) {
break;
}
puzzleListX.add(randomXWord);
if (puzzleListX.size() == size){
finished = false;
}
}
}
System.out.print(puzzleListY);
System.out.print(puzzleListX);
}
public static int randomInteger(int size) {
Random rand = new Random();
int randomNum = rand.nextInt(size);
return randomNum;
}
public static void makeLetterWordList(String letterSize) throws FileNotFoundException {
Scanner letterScanner = new Scanner( new File (letterSize + "LetterWords.txt"));
wordList.clear();
while (letterScanner.hasNext()){
wordList.add(letterScanner.next());
}
letterScanner.close();
}
}
I think you are confusing yourself with that finished variable. Replace the while condition with puzzleListX.size() != size and your code should work.

Resource leak 'blank' never closed

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.

Categories