How to stop FileNotFoundException from popping up? - java

So I'm trying to find the two closest pairs in a text file and then find how close they are. I have most of it worked out but for some reason whenever I try to run the code the file not found exception keeps popping up. I can't seem to get it to run the actual code. Any help would be greatly appreciated.
import java.util.*;
import java.io.FileNotFoundException;
import java.io.File;
/**
*
* #author birnbook
*/
public class ClosestPair {
public static void ClosePair() { // string compare
try{
File text = new File("/Lab2%20Output.txt");
double temp = 0;
double x = 0;
double y = 0;
double stormag = 0;
// scanning the file in
Scanner scnr = new Scanner(text);
int lines = 0;
while (scnr.hasNextLine()) {
lines++;
}
Scanner scnnr = new Scanner(text);
double[] arr = new double[lines];
while (scnnr.hasNextLine()) {
String num = scnnr.nextLine();
arr[1] = Double.parseDouble(num);
}
stormag = arr[0] - arr[1];
if (stormag == 0){
stormag *= -1;
}
for(int i=0; i< arr.length;i++){
for(int k=1;k< arr.length; k++){
if(i != k){
temp = arr[i] - arr[k];
if(temp <= 0){
temp *= -1;
}
if (temp < stormag){
stormag = temp;
x = arr[i];
y = arr[k];
}
}
}
}
System.out.println("The numbers " + x + " and " + y + "are the closest pair with a difference of " + stormag);
} catch (FileNotFoundException e){
System.out.println("FileNotFoundException");
}
}
public static void main(String[] args) {
ClosePair();
}
}

Related

median and mode displaying -1

Hey guys I have been learning coding recently and got an assignment of finding the mean, median and mode of a number of integers in an integer array. The issue that I am facing is that my median and mode displays -1 and I'm not too sure how to fix it, my "if user inputs no, print an error statement" is also not working and I would be very grateful if someone could help me out.
This is my code:
package com.company;
import java.io.File;
import java.io.FileNotFoundException;
import static com.company.ProjectConstants.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] a = new int[MAXDATA];
int counter = 0;
boolean fileDone = false;
boolean inputOk;
String userInput;
String theDataFile;
Scanner s = new Scanner(System.in);
genProgInfo();
userInput = s.nextLine();
userInput = userInput.toLowerCase();
while (!userInput.equals("yes") && (!userInput.equals("no"))) {
System.out.println("ERROR: Please input either yes or no: ");
userInput = s.nextLine();
userInput = userInput.toLowerCase();
}
inputOk = userInput.equals("yes");
initDataStorage(a);
//do {
try {
// create file & scanner objects
System.out.println("enter one of the file names:\nData10File.txt\nData30file.txt\nData35file.txt");
theDataFile = s.next();
theDataFile = theDataFile.toLowerCase();
//fName = userInput;
File f = new File(theDataFile);
Scanner sc = new Scanner(f);
// store file data in array, a
for (int i = 0; i < MAXDATA; i++) {
if (sc.hasNext()) {
a[i] = sc.nextInt();
} else {
fileDone = true;
sc.close();
break;
}
}
// print error message if file data exceeds the range of array
if (!fileDone) {
System.out.println("\n\tCAUTION: file has additional data, consider making array larger.");
}
} catch (FileNotFoundException e) {
System.out.println(e);
e.printStackTrace();
}
//} while (inputOk);
s.close();
for (int i=0; i<MAXDATA; i++) {
if (a[i] != -1) {
counter = a[i];
}
}
System.out.println("counter: "+ counter);
displayResults(calcMean(a), calcMedian(a), calcMode(a));
}
public static void initDataStorage(int[] data) {
for (int i = 0; i < MAXDATA; i++) {
data[i] = INVALID;
}
}
public static double calcMean(int[] data) {
int counter = 0;
int mean;
int sum = 0;
for (int i = 0; i < MAXDATA; i++) {
if (data[i] != -1) {
sum += data[i];
counter++;
}
}
mean = sum / counter;
return mean;
}
public static double calcMedian(int[] data) {
int middle = data.length / 2;
if (data.length % 2 == 1) {
return data[middle];
} else {
return (data[middle -1] + data[middle]) / 2.0;
}
}
public static int calcMode(int[] data) {
int mode = 0, maxCount = 0;
for (int i = 0; i < data.length; ++i) {
int count = 0;
for (int j = 0; j < data.length; ++j) {
if (data[j] == data[i]) {
count++;
}
}
if (count > maxCount) {
maxCount = count;
mode = data[i];
}
}
return mode;
}
public static void genProgInfo() {
System.out.println("This program will calculate the mean, median, and mode of a number of integers stored in the array");
System.out.println("Would you like to continue?");
}
public static void displayResults(double mean, double median, int mode) {
System.out.println("mean: " + mean);
System.out.println("median: " + median);
System.out.println("mode: " + mode);
}
}
I'm assuming the value of INVALID is -1 based on the other code I see and your description of what it outputs. Your array is of length MAXDATA and is initially filled with value INVALID in all elements. You then fill it with n values where n may be less than MAXDATA, and in that (probably common) case, many or even most of the values in the array are the INVALID value.
Your calcMean function is correctly skipping over the -1 (INVALID?) values and not including them in the calculation. Note however that the valid values are all at the beginning of the array and once you find an invalid value, you could break out of the loop in calcMean.
But the calcMedian and calcMode functions are not accounting for the invalid values. If n is significantly less than MAXDATA, then -1 probably really is the mode. Your calcMedian function has an additional problem as well, in that the (valid) data needs to be sorted in order for the "middle" or median value to be in the middle of the array.
Bonus question for your assignment: What if -1 occurs in the input file?

Getting names from text file shifts names 1 place to the left (in array)

I was trying to solve problem 22 of Euler Project. Description of what I'm trying to solve is here:
https://projecteuler.net/problem=22
Where's the problem?: I've got the names from the text file, put them on one string,
edited the string so that the names are separated by one space.
After getting those names on an array of Strings, I sort them. After finishing the program and getting the result wrong, I started testing different parts of the program and notice that the name "COLIN", which by eulerproject page is said to be the 938th, is 937th on my array. I can't seem to get why is it happening and how to fix this. Help would be much appreciated.
Here is the code:
package Project022;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class NameScore {
private long scoreSum;
private LinkedList<String> allNames;
private String[] sortedNames;
private int[] nameScores;
public NameScore(){
scoreSum = 0;
allNames = new LinkedList<>();
getNames();
}
private void getNames(){
List<String> content = null;
File names;
// read "names.txt" file and put all the names in one line(not effective when line
// length surpasses String maximum character range(2^31 - 1) but is good enough for us
// for now)
try {
names = new File("Project022\\names.txt");
content = Files.readAllLines(Paths.get(names.getPath()), StandardCharsets.US_ASCII);
} catch (Exception e){
System.out.println("something went wrong while getting the file");
}
assert content != null;
//replace (",") with a space ( )
String filtered = content.get(0).replaceAll("\",\"", " ");
//then remove first and last (")
filtered = filtered.substring(1, filtered.length() - 1);
//declare "tempName" as a helper string
StringBuilder tempName = new StringBuilder();
//get every name and put it on the LinkedList
for (int i = 0; i < filtered.length(); i++) {
if (filtered.charAt(i) != ' '){
tempName.append(filtered.charAt(i));
} else {
allNames.add(tempName.toString().trim());
tempName = new StringBuilder();
}
}
//now we use an pre defined array since it is faster.
sortedNames = new String[allNames.size()];
for (int i = 0; i < sortedNames.length; i++) {
sortedNames[i] = allNames.get(i);
}
//make the new array worthy of its name
Arrays.sort(sortedNames);
System.out.println(sortedNames[937]);
System.out.println(Arrays.asList(sortedNames) + "\n" + sortedNames.length);
}
public void calculate(){
//we set the score for each name
nameScores = new int[sortedNames.length];
//
for (int i = 0; i < nameScores.length; i++) {
setScore(sortedNames[i], i + 1);
}
for (int i = 0; i < nameScores.length; i++) {
scoreSum += nameScores[i];
}
}
private void setScore(String name, int n) {
int sc = 0;
for (int i = 0; i < name.length(); i++) {
sc += (int)name.toUpperCase().charAt(i) - 'A' + 1;
}
sc *= n;
nameScores[n-1] = sc;
}
#Override
public String toString(){ return "the score of all names is: " + scoreSum; }
public static void main(String[] args) {
NameScore name = new NameScore();
name.calculate();
System.out.println(name);
}
}
What I've ruled out as a problem:
the setScore() method which gives a score for every name, because I tested it with examples by hand and by program and got same results.
the calculate() method, since what it does is gets the score for each name and adds to the total sum.
This works for me.
Path p = Paths.get("p022_names.txt");
try {
List<String> lines = Files.readAllLines(p); // throws java.io.IOException
System.out.println(lines.size()); // Only one line in file.
// Remove all " (double quotes) characters.
String tmp = lines.get(0).replaceAll("\"", "");
String[] names = tmp.split(",");
System.out.println(names.length);
Arrays.sort(names);
// Test against example given in problem description.
System.out.println(names[937]); // Should be COLIN
char[] lett = names[937].toCharArray();
int sigma = 0;
for (int k = 0; k < lett.length; k++) {
sigma += lett[k] - 'A' + 1; // Since only uppercase letters in file.
}
int score = sigma * (937 + 1);
System.out.println(score); // Should be 49714
// Now obtain answer, i.e. the total of all the name scores in the file.
int total = 0;
for (int i = 0; i < names.length; i++) {
char[] letters = names[i].toCharArray();
int sum = 0;
for (int j = 0; j < letters.length; j++) {
sum += letters[j] - 'A' + 1;
}
total += sum * (i + 1);
}
System.out.println(total);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
Output obtained when running above code is as follows.
1
5163
COLIN
49714
871198282
I didn't want to make too many changes to your code, so just removed your replacement of "," and instead just removed all ". Then I added ALONSO in the end after the loop.
I figure if we're all in consensus about the total score of all the names, then we're doing it right :)
It prints:
-- Where's ALONSO ?
sortedNames[145] = ALONA
sortedNames[146] = ALONSO
sortedNames[147] = ALONZO
-- Where's COLIN ?
sortedNames[936] = COLETTE
sortedNames[937] = COLIN
sortedNames[938] = COLLEEN
-- Where's MARY ?
sortedNames[3361] = MARX
sortedNames[3362] = MARY
sortedNames[3363] = MARYA
-- sortedNames.length = 5163
the score of all names is: 871198282
I also called it Project022:
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
//public class NameScore {
public class Project022 {
private long scoreSum;
private LinkedList<String> allNames;
private String[] sortedNames;
private int[] nameScores;
public Project022(){
scoreSum = 0;
allNames = new LinkedList<>();
getNames();
}
private void getNames(){
List<String> content = null;
File names;
// read "names.txt" file and put all the names in one line(not effective when line
// length surpasses String maximum character range(2^31 - 1) but is good enough for us
// for now)
try {
// names = new File("Project022\\names.txt");
names = new File("resource\\p022_names.txt");
content = Files.readAllLines(Paths.get(names.getPath()), StandardCharsets.US_ASCII);
} catch (Exception e){
System.out.println("something went wrong while getting the file");
}
assert content != null;
//replace (",") with a space ( )
// String filtered = content.get(0).replaceAll("\",\"", " ");
String filtered = content.get(0).replaceAll("\"", "");
// //then remove first and last (")
// filtered = filtered.substring(1, filtered.length() - 1);
//declare "tempName" as a helper string
StringBuilder tempName = new StringBuilder();
//get every name and put it on the LinkedList
for (int i = 0; i < filtered.length(); i++) {
// if (filtered.charAt(i) != ' '){
if (filtered.charAt(i) != ','){
tempName.append(filtered.charAt(i));
} else {
allNames.add(tempName.toString().trim());
tempName = new StringBuilder();
}
}
allNames.add(tempName.toString().trim()); // added to include ALONSO
//now we use an pre defined array since it is faster.
sortedNames = new String[allNames.size()];
for (int i = 0; i < sortedNames.length; i++) {
sortedNames[i] = allNames.get(i);
}
//make the new array worthy of its name
Arrays.sort(sortedNames);
System.out.println("\n -- Where's ALONSO ?");
for (int i = 145; i < 148; i++) {
// sortedNames[0] = AARON
System.out.println("sortedNames[" + i + "] = " + sortedNames[i]);
}
System.out.println("\n -- Where's COLIN ?");
for (int i = 936; i < 939; i++) {
// sortedNames[0] = AARON
System.out.println("sortedNames[" + i + "] = " + sortedNames[i]);
}
System.out.println("\n -- Where's MARY ?");
for (int i = 3361; i < 3364; i++) {
// sortedNames[0] = AARON
System.out.println("sortedNames[" + i + "] = " + sortedNames[i]);
}
System.out.println("\n -- sortedNames.length = " + sortedNames.length + "\n");
// System.out.println(Arrays.asList(sortedNames) + "\n" + sortedNames.length);
}
public void calculate(){
//we set the score for each name
nameScores = new int[sortedNames.length];
//
for (int i = 0; i < nameScores.length; i++) {
setScore(sortedNames[i], i + 1);
}
for (int i = 0; i < nameScores.length; i++) {
scoreSum += nameScores[i];
}
}
private void setScore(String name, int n) {
int sc = 0;
for (int i = 0; i < name.length(); i++) {
sc += (int)name.toUpperCase().charAt(i) - 'A' + 1;
}
sc *= n;
nameScores[n-1] = sc;
}
#Override
public String toString(){ return "the score of all names is: " + scoreSum; }
public static void main(String[] args) {
Project022 name = new Project022();
name.calculate();
System.out.println(name);
}
}

Taking input to a Java or C program from a web page?

I was implementing traveling salesman optimisation problem and i programmed the same using Java and C program. The program takes matrix as a input and displays the optimal path.
Java Code
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Stack;
public class TSPNearestNeighbour {
private int numberOfNodes;
private Stack<Integer> stack;
public TSPNearestNeighbour() {
stack = new Stack<Integer>();
}
public void tsp(int adjacencyMatrix[][]) {
numberOfNodes = adjacencyMatrix[1].length - 1;
int[] visited = new
int[numberOfNodes + 1];
visited[1] = 1;
stack.push(1);
int element, dst = 0, i;
int min = Integer.MAX_VALUE;
boolean minFlag = false;
System.out.print(1 + "\t");
while (!stack.isEmpty()) {
element = stack.peek();
i = 1;
min = Integer.MAX_VALUE;
while (i <= numberOfNodes) {
if
(adjacencyMatrix[element][i] > 1 && visited[i] == 0) {
if (min > adjacencyMatrix[element][i]) {
min = adjacencyMatrix[element][i];
dst = i;
minFlag = true;
}
}
i++;
}
if (minFlag) {
visited[dst] = 1;
stack.push(dst);
System.out.print(dst + "\t");
minFlag = false;
continue;
}
stack.pop();
}
}
public static void main(String... arg) {
int number_of_nodes;
Scanner scanner = null;
try {
System.out.println("Enter the number of nodes in the graph");
scanner = new Scanner(System.in);
number_of_nodes = scanner.nextInt();
int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1];
System.out.println("Enter the adjacency matrix");
for (int i = 1; i <= number_of_nodes; i++) {
for (int j = 1; j <= number_of_nodes; j++) {
adjacency_matrix[i][j] = scanner.nextInt();
}
}
for (int i = 1; i <= number_of_nodes; i++) {
for (int j = 1; j <= number_of_nodes; j++) {
if
(adjacency_matrix[i][j] == 1 && adjacency_matrix[j][i] == 0) {
adjacency_matrix[j][i] = 1;
}
}
}
System.out.println("the citys are visited as follows");
TSPNearestNeighbour tspNearestNeighbour = new TSPNearestNeighbour();
tspNearestNeighbour.tsp(adjacency_matrix);
} catch (InputMismatchException inputMismatch) {
System.out.println("Wrong Input format");
}
scanner.close();
}
}
C Code
#include<stdio.h>
#include<conio.h>
int a[10][10],visited[10],n,cost=0;
void get()
{
int i,j;
printf("Enter No. of Cities: ");
scanf("%d",&n);
printf("\nEnter Cost Matrix\n");
for(i=0;i < n;i++)
{
printf("\nEnter Elements of Row # : %d\n",i+1);
for( j=0;j < n;j++)
scanf("%d",&a[i][j]);
visited[i]=0;
}
printf("\n\nThe cost list is:\n\n");
for( i=0;i < n;i++)
{
printf("\n\n");
for(j=0;j < n;j++)
printf("\t%d",a[i][j]);
}
}
void mincost(int city)
{
int i,ncity;
visited[city]=1;
printf("%d -->",city+1);
ncity=least(city);
if(ncity==999)
{
ncity=0;
printf("%d",ncity+1);
cost+=a[city][ncity];
return;
}
mincost(ncity);
}
int least(int c)
{
int i,nc=999;
int min=999,kmin;
for(i=0;i < n;i++)
{
if((a[c][i]!=0)&&(visited[i]==0))
if(a[c][i] < min)
{
min=a[i][c]+a[c][i];
kmin=a[c][i];
nc=i;
}
}
if(min!=999)
cost+=kmin;
return nc;
}
void put()
{
printf("\n\nMinimum cost:");
printf("%d",cost);
}
void main()
{
clrscr();
get();
printf("\n\nThe Path is:\n\n");
mincost(0);
put();
getch();
}
The two programs are also working fine. But i want to implement a case study for it and i need to take input for those matrix from a webpage. So is there any way to do it so? For java or for c, either of one is fine. I know JSP and Web Programming too. I just want to how to take the input for those matrix and send it to server side.
For Java i used Jsp and Servlets.
Index.jsp
<body>
<form action="sample" method="post">
<h1>Travelling Salesman Problem</h1>
<input placeholder="Number of Cities" type="text" name="cities" required="">
<input placeholder="Matrix" type="text" name="matrix" required="">
<button>Submit</button>
</form>
</body>
Servlet Sample.java
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Stack;
import static java.lang.System.out;
public class sample extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String city = request.getParameter("cities");
String numbers = request.getParameter("matrix");
int[] abc=new int[100];
String[] args = new String[2];
args[0] = city;
args[1] = numbers;
abc = TSPNearestNeighbour.main(args); //passing the two arguments to my java class
PrintWriter out = response.getWriter();
for (int i=0;i<=abc.length;i++) {
out.println(abc[i]);
}
}
}
TSPNearestNeighbour.Java (Java Class)
import java.util.InputMismatchException;
import java.util.Stack;
public class TSPNearestNeighbour
{
private int numberOfNodes;
private Stack<Integer> stack;
public TSPNearestNeighbour()
{
stack = new Stack<Integer>();
}
public int[] tsp(int[][] adjacencyMatrix)
{
int[] arr= new int[100];
numberOfNodes = adjacencyMatrix[1].length - 1;
int[] visited = new
int[numberOfNodes + 1];
visited[1] = 1;
stack.push(1);
int element, dst = 0, i;
int min = Integer.MAX_VALUE;
boolean minFlag = false;
System.out.print(1 + "\t");
while (!stack.isEmpty())
{
element = stack.peek();
i = 1;
min = Integer.MAX_VALUE;
while (i <= numberOfNodes)
{
if
(adjacencyMatrix[element][i] > 1 && visited[i] == 0)
{
if (min > adjacencyMatrix[element][i])
{
min = adjacencyMatrix[element][i];
dst = i;
minFlag = true;
}
}
i++;
}
if (minFlag)
{
visited[dst] = 1;
stack.push(dst);
System.out.print(dst +"\t");
minFlag = false;
continue;
}
stack.pop();
}
return arr;// ignore this line,it's regarding my logic
}
public static int[] main (String[] args) {
if (args.length < 2) {
System.out.println("Two arguments required <city> <numbers>");
System.exit(-1);
}
int number_of_nodes;
number_of_nodes = Integer.parseInt(args[0]);
String[] splitText = args[1].split(" +");
int[] mat = new int[splitText.length];
for (int i = 0; i < splitText.length; i++) {
mat[i] = Integer.parseInt(splitText[i]); // since we are passing the parameters to matrix,we convert every value from string type to integer
}
int[] abc = new int[100];
try {
int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1];
int count = 0;
for (int i = 1; i <= number_of_nodes; i++) {
for (int j = 1; j <= number_of_nodes; j++) {
if (count == mat.length)
break;
adjacency_matrix[i][j] = mat[(i - 1) * number_of_nodes + (j - 1)];//matrix input
count++;
}
}
for (int i = 1; i <= number_of_nodes; i++) {
for (int j = 1; j <= number_of_nodes; j++) {
if (adjacency_matrix[i][j] == 1 && adjacency_matrix[j][i] == 0) {
adjacency_matrix[j][i] = 1;
}
}
}
System.out.println("the citys are visited as follows");
TSPNearestNeighbour tspNearestNeighbour = new TSPNearestNeighbour();
abc = tspNearestNeighbour.tsp(adjacency_matrix);
} catch (InputMismatchException inputMismatch) {
System.out.println("Wrong Input format");
}
return abc;
}
}

save contents from void method to variable

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 :)

Training data algorithm not working. (Perceptron)

I am trying to write an algorithm to train perceptron but there seems to be values exceeding max value for double. I have been trying to figure out since yesterday but cannot.
The value of weights seems to be exceeding as well as the value of variable output.
The text file that is read in is of the form:
Input variables and the output
/**
* Created by yafael on 12/3/16.
*/
import java.io.*;
import java.util.*;
public class Perceptron {
static double[] weights;
static ArrayList<Integer> inputValues;
static ArrayList<Integer> outputValues;
static int[] inpArray;
static int[] outArray;
public static int numberOfInputValues(String filePath)throws IOException
{
Scanner valueScanner = new Scanner(new File(filePath));
int num = valueScanner.nextInt();
return num;
}
public static void inputs(String filePath)throws IOException
{
inputValues = new ArrayList<Integer>();
outputValues = new ArrayList<Integer>();
Scanner valueScanner = new Scanner(new File(filePath));
int num = valueScanner.nextInt();
while (valueScanner.hasNext())
{
String temp = valueScanner.next();
String[] values = temp.split(",");
for(int i = 0; i < values.length; i++)
{
if(i+1 != values.length)
{
inputValues.add(Integer.parseInt(values[i]));
}else
{
outputValues.add(Integer.parseInt(values[i]));
}
}
}
valueScanner.close();
}
public static void trainData(int[] inp, int[] out, int num,int epoch)
{
weights = new double[num];
Random r = new Random();
int i,ep;
int error = 0;
/*
* Initialize weights
*/
for(i = 0; i < num; i++)
{
weights[i] = r.nextDouble();
}
for(ep = 1; ep<= epoch; ep++)
{
double totalError = 0;
for(i = 0; i < inp.length/(num); i++)
{
double output = calculateOutput(inp, i, weights);
System.out.println("Output " + (i + 1) + ": " + output);
//System.out.println("Output: " + output);
if(output > 0)
{
error = out[i] - 1;
}else
{
error = out[i] - 0;
}
for(int temp = 0; temp < num; temp++)
{
double epCalc = (1000/(double)(1000+ep));
weights[temp] += epCalc*error*inp[((i*weights.length)+temp)];
//System.out.println("Epoch calculation: " + epCalc);
//System.out.println("Output: " + output);
//System.out.println("error: " + error);
//System.out.println("input " + ((i*weights.length)+temp) + ": " + inp[(i*weights.length)+temp]);
}
totalError += (error*error);
}
//System.out.println("Total Error: " + totalError);
if(totalError == 0)
{
System.out.println("In total error");
for(int temp = 0; temp < num; temp++)
{
System.out.println("Weight " +(temp)+ ": " + weights[temp]);
}
double x = 0.0;
for(i = 0; i < inp.length/(num); i++)
{
for(int j = 0; j < weights.length; j++)
{
x = inp[((i*num) + j)] * weights[j];
}
System.out.println("Output " + (i+1) + ": " + x);
}
break;
}
}
if(ep >= 10000)
{
System.out.println("Solution not found");
}
}
public static double calculateOutput(int[] input, int start, double[] weights)
{
start = start * weights.length;
double sum = 0.0;
for(int i = 0; i < weights.length; i++)
{
//System.out.println("input[" + (start + i) + "]: " + input[(start+i)]);
//System.out.println("weights[i]" + weights[i]);
sum += (double)input[(start + i)] * weights[i];
}
return sum - 1.0 ;
}
public static void main(String args[])throws IOException
{
BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
//Read the file path from the user
String fileName;
System.out.println("Please enter file path for Execution: ");
fileName = obj.readLine();
int numInputValues = numberOfInputValues(fileName);
//Call the function to store values in the ArrayList<>
inputs(fileName);
inpArray = inputValues.stream().mapToInt(i->i).toArray();
outArray = outputValues.stream().mapToInt(i->i).toArray();
trainData(inpArray, outArray, numInputValues, 10000);
}
}
I believe your code is problematic, so i am giving you a simple example but i am sure you will get help from this code to resolve your problem.
import java.util.Random;
public class Perceptron {
double[] weights;
double threshold;
public void Train(double[][] inputs, int[] outputs, double threshold, double lrate, int epoch) {
this.threshold = threshold;
int n = inputs[0].length;
int p = outputs.length;
weights = new double[n];
Random r = new Random();
//initialize weights
for(int i=0;i<n;i++) {
weights[i] = r.nextDouble();
}
for(int i=0;i<epoch;i++) {
int totalError = 0;
for(int j =0;j<p;j++) {
int output = Output(inputs[j]);
int error = outputs[j] - output;
totalError +=error;
for(int k=0;k<n;k++) {
double delta = lrate * inputs[j][k] * error;
weights[k] += delta;
}
}
if(totalError == 0)
break;
}
}
public int Output(double[] input) {
double sum = 0.0;
for(int i=0;i<input.length;i++) {
sum += weights[i]*input[i];
}
if(sum>threshold)
return 1;
else
return 0;
}
public static void main(String[] args) {
Perceptron p = new Perceptron();
double inputs[][] = {{0,0},{0,1},{1,0},{1,1}};
int outputs[] = {0,0,0,1};
p.Train(inputs, outputs, 0.2, 0.1, 200);
System.out.println(p.Output(new double[]{0,0})); // prints 0
System.out.println(p.Output(new double[]{1,0})); // prints 0
System.out.println(p.Output(new double[]{0,1})); // prints 0
System.out.println(p.Output(new double[]{1,1})); // prints 1
}
}

Categories