save contents from void method to variable - java

I am trying to print write the contents from void method to a file but I cant seem to get it to work. I call my method in the main and it prints to the console just fine. I have tried many different approaches but not one worked. Can anyone help/guide me in the right direction?
I have pasted my code below for reference. In my main function I call dijkstra(M, SV - 1) that prints my array to the screen, my goal is to have that same array printed to a file.
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.Scanner;
public class Main_2 {
static int SV = 0; // source vertex
static int N = 0;
static int M[][];
public static int distance[];
static int minDistance(int dist[], Boolean shortestPath[]) {
int min = Integer.MAX_VALUE, minI = -1;
for (int i = 0; i < N; i++)
if (shortestPath[i] == false && dist[i] <= min) {
min = dist[i];
minI = i;
}
return minI;
}
public static void printArr(int dist[], int n) {
// System.out.println("vertex distance");
for (int i = 0; i < N; i++)
System.out.println("[" + dist[i] + "]");
}
public static void dijkstra(int graph[][], int src) {
// The output array. dist[i] will hold
// the shortest distance from src to i
int dist[] = new int[N];
// sptSet[i] will true if vertex i is included in shortest
// path tree or shortest distance from src to i is finalized
Boolean shortestPath[] = new Boolean[N];
// Initialize all distances as INFINITE and stpSet[] as false
for (int i = 0; i < N; i++) {
dist[i] = Integer.MAX_VALUE;
shortestPath[i] = false;
}
// Distance of source vertex from itself is always 0
dist[src] = 0;
// Find shortest path for all vertices
for (int i = 0; i < N - 1; i++) {
// Pick the minimum distance vertex from the set of vertices
// not yet processed. u is always equal to src in first
// iteration.
int u = minDistance(dist, shortestPath);
// Mark the picked vertex as processed
shortestPath[u] = true;
// Update dist value of the adjacent vertices of the
// picked vertex.
for (int j = 0; j < N; j++)
// Update dist[v] only if is not in sptSet, there is an
// edge from u to v, and total weight of path from src to
// v through u is smaller than current value of dist[v]
if (!shortestPath[j] && graph[u][j] != 0 && dist[u] != Integer.MAX_VALUE
&& dist[u] + graph[u][j] < dist[j])
dist[j] = dist[u] + graph[u][j];
}
// print the constructed distance array
printArr(dist, N);
}
public static void main(String[] args) {
try {
int i = 0, j = 0; // counters
FileInputStream textFile = new FileInputStream("EXAMPLE(2).txt"); // name of input file must go in here
Scanner scan = new Scanner(textFile);
N = scan.nextInt(); // read in the size
String flush = scan.nextLine(); // gets rid of linefeed
System.out.println(N);
M = new int[N][N]; // instantiates array
// this loop reads in matrix from input file
String line;
while (i < N && (line = scan.nextLine()) != null) {
j = 0;
String delim = " ";
String tokens[] = line.split(delim);
for (String a : tokens) {
M[i][j] = Integer.parseInt(a);
j++;
}
i++;
}
if (i > N)
;
SV = scan.nextInt();
} catch (Exception e) {
e.printStackTrace();
}
printMatrix(M);
System.out.println(SV);
System.out.println();
dijkstra(M, SV - 1);
try {
FileWriter fw = new FileWriter("Shortest_path.txt"); // writes transitive closure to file
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < N; i++) {
// bw.write(dist[i]);
}
} catch (Exception e) {
System.out.println(e);
}
}
public static void printMatrix(int[][] Matrix) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.print(Matrix[i][j]);
System.out.print(" ");
}
System.out.println();
}
}
}

try (FileWriter fileWriter = new FileWriter("YourFileName.txt");
PrintWriter printWriter = new PrintWriter(fileWriter)) {
for (int i=0; i<N; i++) {
printWriter.printf(Integer.toString(dist[i]));
}
} catch (Exception e) {
System.out.println(e);
}

"A" simple solution, would be to pass the PrintStream you want to use to the method, for example...
public static void printArr(int dist[], int n, PrintStream ps) {
for (int i = 0; i < N; i++) {
ps.println("[" + dist[i] + "]");
}
}
This will then require you to pass a PrintStream instance to the method when ever you call it. Since dijkstra also calls printArr, you will need to pass the instance of the PrintStream to it as well...
public static void dijkstra(int graph[][], int src, PrintStream ps) {
//...
// print the constructed distance array
printArr(dist, N, ps);
}
Then you just create an instance of the PrintStream you want to use and pass it to the methods...
public static void main(String[] args) {
try (FileInputStream textFile = new FileInputStream("EXAMPLE(2).txt")) {
int i = 0, j = 0; // counters
Scanner scan = new Scanner(textFile);
N = scan.nextInt(); // read in the size
String flush = scan.nextLine(); // gets rid of linefeed
System.out.println(N);
M = new int[N][N]; // instantiates array
// this loop reads in matrix from input file
String line;
while (i < N && (line = scan.nextLine()) != null) {
j = 0;
String delim = " ";
String tokens[] = line.split(delim);
for (String a : tokens) {
M[i][j] = Integer.parseInt(a);
j++;
}
i++;
}
if (i > N)
;
SV = scan.nextInt();
try (PrintStream ps = new PrintStream("EXAMPLE(2).txt")) {
printMatrix(M);
System.out.println(SV);
System.out.println();
dijkstra(M, SV - 1, ps);
}
} catch (Exception e) {
e.printStackTrace();
}
}
I restructured your main method slightly, as the output is depended on the success of the input ;). Also see The try-with-resources statement for more details
This means you could do something like...
dijkstra(M, SV - 1, System.out);
and it would once again print the output to the console :)

Related

Selection Sort using a comparable class [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I made java Selection Sort using Comparable class, File scanner.
In this code, we get txt file's name and store all words in String[] list and show index and stored word.
Finally, we sort this String[] list using Selection Sorting and check how much time was spent. but there's some error code.
This is an AbstractSort class
abstract class AbstractSort
{
public static void sort(Comparable[] a) { };
protected static boolean less(Comparable v, Comparable w )
{
return v.compareTo(w) < 0; // This Line is Error
}
protected static void exch(Comparable[] a, int i, int j)
{
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
}
protected static void show(Comparable[] a)
{
for(int i = 0; i < a.length; i++)
System.out.println(a[i] + " ");
System.out.println();
}
protected static boolean isSorted(Comparable[] a)
{
for(int i = 1; i < a.length; i++)
{
if(less(a[i], a[i - 1])) // This Line is also Error
return false;
}
return true;
}
}
and this is a Selection Sort class which is extends AbstractSort class
class Selection extends AbstractSort {
public static void sort(Comparable[] a) {
int n = a.length;
for(int i = 0; i < n - 1; i++) {
int min = i;
for(int j = i + 1; j < n; j++) {
if(less(a[j], a[min]))
min = j;
}
exch(a, i, min);
}
assert isSorted(a);
};
}
and this is main function
public class HW1{
static String[] resize(int idx, String[] arr) {
String[] temp = new String[idx * 2];
for(int i = 0; i < idx; i++)
temp[i] = arr[i];
return temp;
}
public static void main(String args[]) {
int INIT_LEN = 10000;
long start, end, time;
String[] list = new String[INIT_LEN];
Scanner sc = new Scanner(System.in);
int idx = 0;
try {
System.out.println("File Name?");
String src = sc.nextLine();
sc = new Scanner(new FileInputStream(src));
while(sc.hasNext()) {
String word = sc.next().toString();
if(idx == list.length)
list = resize(idx, list);
list[idx++] = word;
}
System.out.println("1. Total Word = " + idx);
for(int i = 0; i < idx; i++)
System.out.println(i + "idx:" + list[i]);
start = System.currentTimeMillis();
Selection.sort(list); // This Line is also Error
end = System.currentTimeMillis();
time = end - start;
System.out.println("2. Selection Sorted? = true, Time = " + time + "ms");
}catch (FileNotFoundException fnfe) {
System.out.println("No File");
}catch (IOException ioe) {
System.out.println("Can't Read File");
}
}
}
when I run this code, I can see all words are stored int String[] list but there's also error code together.
Exception in thread "main" java.lang.NullPointerException
at AbstractSort.less(HW1.java:8)
at Selection.sort(HW1.java:40)
at HW1.main(HW1.java:84)
I don't know why this error code is occured...
When you call Selection.sort(list) in main, it appears that the list has a length of 10000.
Every element defaults to null.
So if you read in three words your list will look like this:
word1,word2,word3,null,null,null......null
Quick hack so you don't need to resize the array - try making your inner loop in Selection::sort:
for (int j = i + 1; j < n; j++) {
if (a[j] == null) {
break;
}
if (less(a[j], a[min]))
min = j;
}
Or - resize the array appropriately before processing.
Or - use an ArrayList to push words to and then convert to an array if you absolutely must use an array.

How to populate 2D array (Matrix) from input txt taken from args?

My brain has probably stopped working so I really need your help with this.
So, I have an input txt file formatted like this:
3 //Number of Heroes (nodes lets say)
43 43 // left int = hp, right int = damage etc...
22 444
12 43
2 //Number of enemies
20 39 //likewise with the heroes
//The latter (enemies) is not yet implemented, cause I am stuck with the
//first part (so let's say the part before '2' is present in the input
//txt at the moment
My main is this (I want to be able to take multiple files in the future):
public static void main(String[] args) {
Q2 ks = new Q2();
int length = args.length;
for (int i = 0; length > 0; i++) {
ks.readFile(args[i]);
break;
}
}
And this is my readFile(), where I am trying to populate the matrix with the data (but failing miserably because my brain has really stopped working):
public int[][] readFile(String inputName) {
BufferedReader reader;
int Matrix[][] = null;
try {
reader = new BufferedReader(new FileReader(inputName));
String line = reader.readLine();
int numberOfHeroes = Integer.parseInt(line);
Matrix = new int[numberOfHeroes][2];
line = reader.readLine();
System.out.println(numberOfHeroes);
for (int i = 0; i < numberOfHeroes; i++) {
int hitpoints = 0;
int damage = 0;
//while (line != null) {
String splittedLine[] = line.split(" ");
//while (splittedLine[1] != null){
hitpoints = Integer.parseInt(splittedLine[0]);
damage = Integer.parseInt(splittedLine[1]);
Matrix[i][0] = hitpoints;
Matrix[i][i+1] = damage;
line = reader.readLine();
//}
//}
}
System.out.println("====GRAPH====");
for (int i = 0; i < numberOfHeroes; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(Matrix[i][j] + " ");
}
System.out.println();
}
System.out.println("============");
} catch(IOException e) {
return null;
}
return Matrix;
}
You put the damage value into the wrong cell. Instead of Matrix[i][i+1] = damage; you want to do Matrix[i][1] = damage;.

Java - NumberFormatException when using .parseInt(String)

I am trying to run a loop to see if an int is sorted. however the int has to be converted from a string. here is my code.
public static void main(String[] args) {
// TODO code application logic here
Scanner maxVal = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
System.out.println("enter the max value of ordered squares:");
int max = maxVal.nextInt();
for(int i = 0; i*i <= max; i++){
int L = String.valueOf(i*i).length();
String sq = String.valueOf(i*i);
String [] digits = new String[L];
for(int a = 0; a < L; a++){
digits [a] = Character.toString(sq.charAt(a));
if(L == 1){
System.out.print(sq + "");
}else if(Integer.parseInt(digits [a]) < Integer.parseInt(digits[a+1])){
System.out.print(sq);
}else{
}
}
}
}
when I run it, I get an error :
Exception in thread "main" java.lang.NumberFormatException: null
0149 at java.lang.Integer.parseInt(Integer.java:542)
at java.lang.Integer.parseInt(Integer.java:615)
why does Integer.parseInt() not work
Your problem is that digits[a+1] hasn't been defined yet. I see that on line 2 you have
digits[a] = Character.toString(sq.charAt(a));
and you're iterating over a in a for loop, so I daresay that digits[a+1] hasn't been assigned yet.
UPDATE 1
Check out this solution, it shows how to properly catch that exception and how to avoid it:
Java: Good way to encapsulate Integer.parseInt()
UPDATE 2
I decided to add a fixed version of your code:
public static void main(String[] args) {
// TODO code application logic here
Scanner maxVal = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
System.out.println("enter the max value of ordered squares:");
int max = maxVal.nextInt();
for(int i = 0; i*i <= max; i++){
int L = String.valueOf(i*i).length();
String sq = String.valueOf(i*i);
String [] digits = new String[L];
for(int a = 0; a < L; a++){
digits [a] = Character.toString(sq.charAt(a));
if(L == 1 || a == 0){
System.out.print(sq + "");
}else if(Integer.parseInt(digits [a]) < Integer.parseInt(digits[a+1])){
System.out.print(sq);
}else{
}
}
}
}
While I don't know the utility of your code, but this implementation might be simpler:
public static void main(String[] args) {
// TODO code application logic here
Scanner maxVal = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
System.out.println("enter the max value of ordered squares:");
int max = maxVal.nextInt();
for(int i = 0; i*i <= max; i++){
long sq = i*i;
if(sq > 9){
String[] digits = sq.toString().split("");
//Notice that I start at index 1, so I can do [a-1] safely
for(int a = 1; a < digits.length; a++){
if(Integer.parseInt(digits [a-1]) < Integer.parseInt(digits[a])){
System.out.print(sq);
//I guess we don't want a number like 169 (13*13) to be displayed twice, so:
break;
}
}
} else {
System.out.print(sq);
}
}
}

printing optimal binary search tree in preorder dynamic programming algorith

I have just finished up computing the average cost of an OBST and I know I computed it correctly. My next task is to print the tree in preorder. I have an attempt at this using recursion but can't seem to shake the null pointer error.
Here's my code:
public class OBST {
static String[] keysA;
static Integer[][] root;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int tot = sc.nextInt();
HashMap<String, Double> hm = new HashMap<String, Double>();
int uniqNum = 0;
String[] rawInput = new String[tot];
for(int i=0; i<tot; i++) {
String tmp1 = sc.next();
if(i==0) {
hm.put(tmp1, 1.0);
uniqNum += 1.0;
} else if( i != 0) {
if(!hm.containsKey(tmp1)) {
hm.put(tmp1, 1.0);
uniqNum += 1.0;
} else {
Double tmpfreq = 0.0;
tmpfreq = hm.get(tmp1);
hm.put(tmp1, (tmpfreq + 1.0));
}
}
}
Set<String> keys = hm.keySet();
keysA = keys.toArray(new String[uniqNum]);
Double[] freqsA = new Double[uniqNum];
Arrays.sort(keysA);
for(int i=0; i<uniqNum; i++) {
Double tmp = 0.0;
String tmpK = keysA[i];
tmp = hm.get(tmpK);
tmp = tmp/tot;
freqsA[i] = tmp;
}
Double[][] eee = new Double[uniqNum+2][uniqNum+1];
Double[][] www = new Double[uniqNum+2][uniqNum+1];
//matrix to store optimal structure
root = new Integer[uniqNum+1][uniqNum+1];
for(int i=1; i<uniqNum+2; i++) {
eee[i][i-1] = 0.0;
www[i][i-1] = 0.0;
}
for(int l=1; l<uniqNum+1; l++) {
for(int i=1; i<=uniqNum-l+1; i++) {
int j = i + l - 1;
eee[i][j] = Double.MAX_VALUE;
www[i][j] = www[i][j-1] + freqsA[j-1];
for(int r=i; r<=j; r++) {
Double t = eee[i][r-1] + eee[r+1][j] + www[i][j];
if(t<eee[i][j]) {
eee[i][j] = t;
root[i][j] = r-1;
}
}
}
}
//total cost
System.out.println(eee[1][uniqNum]);
printTree(1,uniqNum-1,-1, "");
}
public static void printTree(int min, int max, int parent, String s) {
int r = root[min][max];
if(parent == -1 ) {
System.out.println(keysA[r] + " is root");
} else if(min < parent) {
System.out.println(keysA[r] + " is the left child of " + s);
} else {
System.out.println(keysA[r] + " is the right child of " + s);
} if(min < max) {
printTree(min,r,r+1,keysA[r]);
printTree(r+1,max,r,keysA[r]);
}
}
}
My trouble is in the method print tree.
Looks like you aren't checking your bounds correctly. If there is no left or right child, you shouldn't be printing that side. so make sure you check that r+1 is within the array size, and also that a node exists there. do the same for both left and right sides.

How can I avoid repetition of the same number?

This is what I want :
Let the user enter as many numbers as they want until a non number is entered (you may
assume there will be less than 100 numbers). Find the most frequently entered number. (If
there are more than one, print all of them.)
Example output:
Input: 5
Input: 4
Input: 9
Input: 9
Input: 4
Input: 1
Input: a
Most common: 4, 9
I have got to the point in my code where I have managed to find out which are the most common numbers. However, I don't want to print out the same number over and over again; example from above: Most common: 4, 9, 9, 4
What needs to be done?
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] input = new String[100];
System.out.print("Input: ");
input[0] = in.readLine();
int size = 0;
for (int i = 1; i < 100 && isNumeric(input[i-1]); i++) {
System.out.print("Input: ");
input[i] = in.readLine();
size = size + 1;
}
/*for (int i = 0; i < size; i++) { //testing
System.out.println(input[i]);
}*/
int numOccur;
int[] occur = new int[size];
for(int i = 0; i < size; i++) {
numOccur = 0;
for (int j = 0; j < size; j++) {
if(input[i].equals(input[j])) {
numOccur = numOccur + 1;
}
}
occur[i] = numOccur;
//System.out.println(numOccur); //testing
}
int maxOccur = 0;
for(int i = 0; i < size; i++) {
if(occur[i] > maxOccur) {
maxOccur = occur[i];
}
}
//System.out.println(maxOccur); //testing
for (int i = 0; i < size && !numFound; i++) {
if(occur[i] == maxOccur) {
System.out.println(input[i]);
}
}
}
//checks if s is an in, true if it is an int
public static boolean isNumeric (String s) {
try {
Integer.parseInt(s);
return true; //parse was successful
} catch (NumberFormatException nfe) {
return false;
}
}
Found the solution!
String[] mostCommon = new String[size];
int numMostCommon = 0;
boolean numFound = false;
for (int i = 0; i < size; i++) {
int isDifferent = 0;
if (occur[i] == maxOccur) {
for (int j = 0; j < size; j++) {
if (!(input[i].equals(mostCommon[j]))) {
isDifferent = isDifferent + 1;
}
}
if (isDifferent == size) {
mostCommon[numMostCommon] = input[i];
numMostCommon = numMostCommon + 1;
}
}
}
for (int i = 0; i < numMostCommon - 1; i++) {
System.out.print("Most common: " + mostCommon[i] + ", ");
}
System.out.println(mostCommon[numMostCommon - 1]);
you could use the hash table for this to store the frequenceis as the limit is very less i.e. less than 100.
pseudo code would be like:
vector<int> hash(101)
cin>>input
if(isnumeric(input))
hash[input]++
else{
max=max_element(hash.begin(),hash.end());
for(int i=0;i<100;i++)
if(hash[i]==max)
print i
}
Set<Integer> uniqueMaxOccur = new HashSet<Integer>();
for (int i = 0; i < size ; i++) {
if(occur[i] == maxOccur) {
//System.out.println(input[i]);
uniqueMaxOccur.add(input[i]);
}
}
and display the values in the set
You can use a Set and store the values already printed.
What about something like this?
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Map<string,int> numberLookup = new HashMap<string,int>();
Boolean doContinue = true;
while (doContinue)
{
System.out.print("Input: ");
String input = in.readLine();
if (isNumeric(input))
{
if (!numberLookup.containsKey(input))
numberLookup.put(input,1);
else
numberLookup.put(input, numberLookup.get(input) + 1);
}
else
doContinue = false;
}
maxOccur = numberLookup.values().max();
System.out.print("These numbers were all entered " + maxOccur + " times:");
Iterator it = numberLookup.entrySet().iterator();
while (it.hasNext())
{
(Map.Entry)it.next();
System.out.println(pairs.getKey());
}
}
Sorry, I'm a C# person and don't have a Java compiler on me, so this might need some tweaking.

Categories