I have been working on this for quite some time and cannot figure out why i am getting the error
Exception in thread "main" java.lang.NullPointerException
at LifeGame.cellValue(LifeGame.java:91)
at Life.main(Life.java:31)
after I input the file name each time I run it.
This is the main file.
Life.java
import java.util.*; // Scanner
import java.io.*; // PrintStream
public class Life {
static PrintStream theScreen = new PrintStream(System.out);
static Scanner theKeyboard = new Scanner(System.in);
public static void main( String args[]) {
theScreen.print("\nEnter the name of the initial configuration file: ");
String inFile, str;
inFile = theKeyboard.nextLine();
// initialize the game
LifeGame theGame = new LifeGame(inFile);
int count = 0;
while(true)
{
// display current configuration
theScreen.println(theGame.cellValue(0, 0));
theScreen.println("\nGeneration " + count
+ " - press 'Enter' for the next "
+ "generation or type 'done' to finish");
str = theKeyboard.nextLine();
if (str.equals("done")) break;
// generate next configuration
theGame.nextGeneration();
count++;
}
}
}
This is LifeGame.java
import java.util.*; // Scanner
import java.io.*; // File
public class LifeGame
{
// define private variables here
int myRows=0;
int myCols=0;
int[][] myGrid;
static PrintStream theScreen = new PrintStream(System.out);
// ++++++++++++++++++++++++++++++++++++++++++++++++++
// * LifeGame constructor. *
// * Receive: fileName, a string. *
// * Precondition: fileName contains the name of *
// * a file containing a Life configuration *
// * (the number of rows, the number of columns, *
// * and the values of each cell). *
// * Postcondition: myGrid has been initialized *
// * to the configuration in fileName. *
// ++++++++++++++++++++++++++++++++++++++++++++++++++
public LifeGame(String fileName)
{
Scanner theFile = null;
try
{
theFile = new Scanner(new File(fileName));
}
catch (FileNotFoundException e)
{
System.err.println("File Not Found");
System.exit(1);
}
myRows = theFile.nextInt();
myCols = theFile.nextInt();
int[][] myGrid = new int[myRows][myCols];
for (int i = 0; i < myRows; i++)
{
for (int j = 0; j < myCols; j++)
{
int num = theFile.nextInt();
myGrid[i][j] = num;
}
}
theFile.close();
System.out.println(myRows+" "+myCols);
}
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++
// * LifeGame columns extractor. *
// * Return: the number of columns in my configuration. *
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++
public int columns()
{
return myCols;
}
// ++++++++++++++++++++++++++++++++++++++++++++++++++*
// * LifeGame rows extractor. *
// * Return: the number of rows in my configuration. *
// ++++++++++++++++++++++++++++++++++++++++++++++++++*
public int rows()
{
return myRows;
}
// ++++++++++++++++++++++++++++++++++++++++++++++++++*
// * LifeGame cell Value extractor. *
// * Return: the value in cell [row][col] *
// ++++++++++++++++++++++++++++++++++++++++++++++++++*
public int cellValue(int row,int col)
{
for (int i = 0; i < rows(); i++)
{
for(int j = 0; j < columns(); j++)
{
if (myGrid[i][j] == '1')
{
theScreen.println("* ");
}
else
{
theScreen.println(" ");
}
}
System.out.println();
}
return 0;
}
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++
// * Mutator to generate next LifeGame generation. *
// * Postcondition: For each cell myGrid[r][c]: *
// * if myGrid[r][c] had 3 living neighbors: *
// * myGrid[r][c] contains a 1. *
// * if myGrid[r][c] had less than 2 neighbors OR *
// * myGrid[r][c] had more than 3 neighbors: *
// * myGrid[r][c] contains a 0. *
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++
public void nextGeneration()
{
int neighbors = 0;
int tempGrid[][] = myGrid;
for (int r = 0; r < myRows; r++)
{
for (int c = 0; c < myCols; c++)
{
neighbors = (tempGrid[r-1][c-1]
+ tempGrid[r-1][c]
+ tempGrid[r-1][c+1]
+ tempGrid[r][c-1]
+ tempGrid[r][c+1]
+ tempGrid[r+1][c-1]
+ tempGrid[r+1][c]
+ tempGrid[r+1][c+1]);
if ( neighbors == 3)
{
myGrid[r][c] = 1;
}
else if ( neighbors < 2 || neighbors > 3)
myGrid[r][c] = 0;
}
}
}
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++
// * LifeGame toString function member. *
// * override the toString method to display the array *
// * Return: a String containing my configuration. *
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++
public String toString()
{
return "";
}
} // end of the class
And this is the file being read in
test.life
5 5\n
0 0 0 0 0\n
0 0 1 0 0\n
0 0 1 0 0\n
0 0 1 0 0\n
0 0 0 0 0\n
The problem is myGrid is null. If you look at LifeGame() you will notice you're redefining a local version of myGrid so you're not setting the member variable correctly.
Change:
int[][] myGrid = new int[myRows][myCols];
To:
myGrid = new int[myRows][myCols];
MyGrid is probably null. You initialize something called myGrid in your constructor (scoped only in the constructor), but not self.myGrid (which is for the class)
Around line 40 in LifeGame.java you have:
int[][] myGrid = new int[myRows][myCols];
If you're trying to instantiate the instance variable myGrid instead of a local myGrid, then you should take off the int[][]
myGrid = new int[myRows][myCols];
Since you never instantiate the instance variable, it's null when you call it later in the cellValue() function.
Related
I need to create a method which must return the partial derivative of a function in the form of a term when passed the var you want to differentiate w respect to. This is my class the method is differentiate:
package poly;
import java.util.ArrayList;
import java.util.TreeSet;
import util.Vector;
/** Implements an individual term in a polynomial. If 5x^2 + 3xy is a polynomial,
* it has two terms 5x^2 and 2xy, each of which would be represented by a different
* instance of this class.
*
* #author ssanner#mie.utoronto.ca
*
*/
public class Term {
// For term 2.1*x^4*y*z^2, the data members would take values as follows:
public double _coef; // = 2.1
public ArrayList<String> _vars; // = ["x", "y", "z"]
public ArrayList<Integer> _pows; // = [4, 1, 2]
/** This constructor has been implemented for you.
*
* #param coef -- sets the _coef member
*/
public Term(double coef) {
_coef = coef;
_vars = new ArrayList<String>();
_pows = new ArrayList<Integer>();
}
/** This constructor has been implemented for you -- it parses a term
* representation from a String into the format required by this class.
* You need two understand the following code.
*
* #param s -- String to parse
* #throws PolyException if s is malformed
*/
public Term(String s) throws PolyException {
if (s == null || s.trim().equals(""))
throw new PolyException("Empty Term, cannot read");
// Initialize this term
_coef = 1.0d; // Will multiply any constants by this
_vars = new ArrayList<String>();
_pows = new ArrayList<Integer>();
// You need to understand all lines of the following code
String[] factors = s.split("\\*");
for (String factor : factors) {
factor = factor.trim(); // Get rid of leading and trailing whitespace
try {
// If successful, multiplies in a constant (multiple constants in a product allowed)
_coef *= Double.parseDouble(factor);
} catch (NumberFormatException e) {
// If not a coefficient, must be a factor "<var>^<pow>"
// Must be a variable to a power -- parse the factor and add to list
int pow = 1; // If no power, defaults to 1
String[] var_pow = factor.split("\\^");
String var = var_pow[0];
if (var_pow.length == 2) {
try { // Second part must be exponent
pow = Integer.parseInt(var_pow[1]);
} catch (NumberFormatException f) {
throw new PolyException("ERROR: could not parse " + factor);
}
} else if (var_pow.length > 2)
throw new PolyException("ERROR: could not parse " + factor);
// Successfully parsed variable and power, add to list
if (_vars.contains(var))
throw new PolyException("ERROR: " + var + " appears twice in " + s);
_vars.add(var);
_pows.add(pow);
}
}
}
/** Produce a re-parseable representation of this Term as a String. This
* has been done for you.
*
*/
public String toString() {
// Using "+" to append Strings involves a lot of String copies since Strings are
// immutable. StringBuilder is much more efficient for append.
StringBuilder sb = new StringBuilder();
sb.append(String.format("%01.3f", _coef));
for (int i = 0; i < _vars.size(); i++) {
String var = _vars.get(i);
int pow = _pows.get(i);
sb.append("*" + var + (pow == 1 ? "" : "^" + pow));
}
return sb.toString();
}
/** Returns all of the variables used in this Term as a sorted set (TreeSet).
* This has been implemented for you, but you need to understand how it works
* since you'll write a similar method in Polynomial that uses this method.
*
* #return
*/
public TreeSet<String> getAllVars() {
// TreeSets are like HashSets but sorted alphabetically (lookup and insertion are
// a little less efficient than HashSets, but this won't matter for our sizes).
return new TreeSet<String>(_vars);
}
///////////////////////////////////////////////////////////////////////////////
// TODO: Your methods here! You should add some helper methods that facilitate
// the implementation of the methods below.
///////////////////////////////////////////////////////////////////////////////
/** If Term defines a function f(x,y) = 2xy^2 and assignments is { x=2.0 y=3.0 }
* then this method returns 36.0, which is the evaluation of f(2.0,3.0).
*
* #param assignments
* #return
* #throws PolyException
*
*
*/
public double coef(){
return _coef;
}
public Double var(int i){
return Double.parseDouble(_vars.get(i));
}
public ArrayList power(){
return _pows;
}
public double evaluate(Vector assignments) throws PolyException {
double evaluated = 0;
double sum = 0;
for(int i = 0; i < _vars.size(); i++){
sum += Math.pow(var(i), _pows.get(i));
}
evaluated *= sum;
return evaluated;
}
/** If Term defines a function f(.) then this method returns the **symbolic**
* partial derivative (which you can verify from calculus is still a Term):
*
* partial f(1.0,2.0) / partial var.
*
* Specifically, if Term defines a function f(x,y) = 2xy^2 and var = "x"
* then this method returns a **new** Term 2y^2 and if var = "y" then it
* instead returns a **new** Term 4xy.
*
* #param var
* #return partial derivative of this w.r.t. var as a new Term
*/
public Term differentiate(String var) {
// TODO: Should not return null!
return null;
}
}
I'm unsure on how the differentiate method would be called but an example of the method to differentiate a relatively simple function could be done like the following...
Please note this method could use some fine-tuning (it returns a String not a Term value) and it doesn't take into consideration logs/trig functions etc but hopefully it's a helpful start.
public static void main(String args[]) {
String differentiated = differentiate("32x^2y^3", "x");
System.out.println(differentiated);
}
public static String differentiate(String function, String var) {
StringBuilder partialDerivative = new StringBuilder();
int indexOfVar = function.indexOf(var);
boolean coefficient = false;
String coefficientValue;
double coefficientAmount = 1;
StringBuilder powerValue = new StringBuilder();
StringBuilder variable = new StringBuilder();
double powerAmount;
StringBuilder otherVariables = new StringBuilder();
//ascertains whether a coefficient is present
int k = 0;
while (Character.isDigit(function.charAt(k))) {
coefficient = true;
if (k == 0) {
coefficientValue = Character.toString(function.charAt(k));
} else {
coefficientValue = function.substring(0, k+1);
}
coefficientAmount = Double.parseDouble(coefficientValue);
k++;
}
//checks for other variables that may also have polynomials
for (int i = 0; i <= function.length() - 1; i++) {
if (Character.isLetter(function.charAt(i)) && function.charAt(i) != var.charAt(0)) {
otherVariables.append(function.charAt(i));
if (i < function.length() - 1) {
if (function.charAt(i + 1) == '^') {
findPolynomial(function, i, otherVariables);
}
}
}
}
//works out if the var value has a polynomial and therefore times the coefficient by it and reduces it by one
if (function.charAt(indexOfVar + 1) == '^') {
findPolynomial(function, indexOfVar, powerValue);
powerAmount = Double.parseDouble(powerValue.toString().substring(1));
coefficientAmount *= powerAmount;
powerAmount -= 1;
powerValue.replace(1,powerValue.length(),Double.toString(powerAmount));
if(powerAmount != 1) {
variable.append(var).append(powerValue);
} else {
variable.append(var);
}
}
//include method for ln() or exponential functions
//include method for trig functions (sin() cos() etc)
if (coefficient) {
partialDerivative.append(coefficientAmount).append(otherVariables).append(variable);
} else {
partialDerivative.append(otherVariables).append(variable);
}
return partialDerivative.toString();
}
private static void findPolynomial(String function, int indexOfVar, StringBuilder powerValue) {
powerValue.append(function.charAt(indexOfVar + 1));
int j = indexOfVar + 2;
while (Character.isDigit(function.charAt(j))) {
powerValue.append(function.charAt(j));
if (j == function.length() - 1) {
break;
} else {
j++;
}
}
}
I have a problem how to find GCD and LCM using ArrayList. Now I have implemented Euklides algorithm using primitive type. Below are my model and view packages. Please give me advice how change method in the model?
Model:
package Model;
import java.util.ArrayList;
import java.util.List;
/**
*
* Class used to calculate two math formulas.
*
* #author anonymous
* #version 1.24
*
*/
public class LeastGreatestCommon {
int result; // result of counting Least Common Multiple **
int result2; // result of counting Greatest Common Divisor **
/**
* Method counting Greatest Common Divisor from Euclidean algorithm
*
* #param a the first value of arguments
* #param b the second value of arguments
* #return returns the value of the largest common divisor for two input
* values
* #throws NegativeValueException where is one or more negative values
*/
public int gcd(int a, int b) throws NegativeValueException {
if (a < 0) {
throw new NegativeValueException("You entered negative characters. Enter only posiitive numbers");
}
return b == 0 ? a : gcd(b, a % b);
}
/**
* Method counting Least Common Multiple from Euclidean algorithm
*
* #param a the first value of arguments
* #param b the second value of arguments
* #return returns the value of the least common multiple for two input
* values
* #throws NegativeValueException where is one or more negative values
*/
private int lcm(int a, int b) throws NegativeValueException {
if (a < 0) {
throw new NegativeValueException("You entered negative characters. Enter only posiitive numbers");
}
return a * b / (gcd(a, b));
}
/**
* Method counting Greatest Common Divisor of n numbers
*
* #param r the number of arguments that will be used to calculate GCD
* #param tab_tmp the value of the array
* #return returns the value of the Greatest common divisor for all input
* values from the input stream or defined arguments
* #throws NegativeValueException where is one or more negative values
*/
public int calculateGreatestCommonDivisor(int r, int number) throws NegativeValueException {
List<Integer> getGreatestCommonDivisor = new ArrayList<Integer>();
for (int i = 0 ; i < r ; ++i) {
getGreatestCommonDivisor.add(i);
result2 = gcd(result2, getGreatestCommonDivisor.get(i));
// getGreatestCommonDivisor.remove(i);
}
return result2;
}
/**
* Method counting Least Common Multiple of n numbers
*
* #param r the number of arguments that will be used to calculate LCM
* #param tab_tmp the value of the array
* #return returns the value of the Least Common Multiple for all input
* values from the input stream or defined arguments
* #throws NegativeValueException where is one or more negative values
*/
// public int calculateLeastCommonMultiple(int r, int[] tab_tmp) throws NegativeValueException {
//
// int i; // integer representing the i-element array
// int[] tab = tab_tmp; // element of the array **
// int r_tmp = r; // number of elements in the array **
// r = tab.length;
// result = lcm(tab[0], tab[1]);
//
// for (i = 1; i < r; i++) {
// if (tab[i] < 0) {
// throw new NegativeValueException("You entered negative characters. Enter only posiitive numbers");
// }
// result = lcm(result, tab[i]);
// }
// return result;
// }
}
View:
package View;
import Model.LeastGreatestCommon;
import Model.NegativeValueException;
import java.util.ArrayList;
import java.util.Scanner;
/**
* Main view class
*
* #author anonymous
* #version 1.23
*
*/
public class View {
/**
* The main method of counting calculate based on the given arguments value
* of GCD and LCM
*
* #param args the command line arguments
*/
public static void main(String[] args) throws NegativeValueException {
int ResultOfTheMultiple;
int ResultOfTheDivisor;
//int r_tmp;
LeastGreatestCommon leastGreatestCommon = new LeastGreatestCommon(); // Creating new object of LeastGreatestCommon class
// Scanner scanner = new Scanner(System.in);
ArrayList<Integer> getGreatestCommonDivisor = new ArrayList<>();
if (args.length == 0) { // Interaction with the user via the console
int r;
int number = 0;
Scanner input = new Scanner(System.in); // Creating Scanner object class associated with the input stream of object
System.out.println("How many numbers will we count? ");
r = input.nextInt();
//int[] tab = new int[r];
//System.out.println(r);
for (int i = 0; i < r; i++) {
System.out.println("Enter the number ");
number = input.nextInt();
}
System.out.println("The array consists of " + r + " elements\n");
for (int i = 0; i < r ; ++i) {
System.out.print(number + " , ");
}
System.out.println("\n");
try {
// getGreatestCommonDivisor.forEach(s -> System.out.println(s));
ResultOfTheDivisor = leastGreatestCommon.calculateGreatestCommonDivisor(r, number);
// for (Integer calculations : ResultOfTheDivisor) {
// System.out.println(calculations);
// }
// ResultOfTheDivisor.forEach(System.out::println);
//ResultOfTheMultiple = leastGreatestCommon.calculateLeastCommonMultiple(r, tab);
System.out.println("The Greatest Common Divisor of these numbers is " + ResultOfTheDivisor);
// System.out.println("The Least Common Multiple of these numbers is " + ResultOfTheMultiple);
} catch (NegativeValueException ex) {
// System.out.println(e);
System.out.println(ex.getMessage());
}
}
// if (args.length > 1) { // Interaction with the user using arguments in the project properties
//
// System.out.println("Arguments were entered");
// System.out.println("\n");
// int[] tab_tmp = new int[args.length];
// r_tmp = Integer.parseInt(args[0]);
//
// for (int i = 0; i < args.length; i++) {
// tab_tmp[i] = Integer.parseInt(args[i]);
// }
//
// try {
// ResultOfTheDivisor = leastGreatestCommon.calculateGreatestCommonDivisor(r_tmp, tab_tmp);
// ResultOfTheMultiple = leastGreatestCommon.calculateLeastCommonMultiple(r_tmp, tab_tmp);
// System.out.println("The Greatest Common Divisor of these numbers is " + ResultOfTheDivisor);
// System.out.println("The Least Common Multiple of these numbers is " + ResultOfTheMultiple);
// } catch (NegativeValueException ex) {
// System.out.println(ex.getMessage());
// }
// }
}
};
The issue was caused because in the method CalculateGreatestCommonDivisor doesn't get any normal result. Can you check this one?
title: There is a board of size: nxm and a set of words.We need to find such a way of writing words on the board such that one cell include at most one letter and every continuous sequence of letters read horizontally and vertically is a word from a subset of the size K of the set S acquired from file
I don't know how to get data from user in this code. I need code like I describe in the "Title". In this code words can not read from a file.
Does any one help me to solve it out this problem? I need solution before tomorrow. Does any one can do it for me?
import java.util.*;
import java.awt.*;
import java.io.*;
/**
* Solves a crossword puzzle as defined by the heuristics and variables
*/
public class CrosswordSolver {
/**
* Puzzle content (words / border)
*/
private char[][] puzzle;
/**
* Crossword puzzle slots which all need to be fit
*/
private CrosswordSlot[] slots;
/**
* Crossword Puzzle words which can be used to fill the slots
*/
private CrosswordWord[] words;
/**
* Whether there are characters in the field in the puzzle
*/
private int[][] letterUsage;
/**
* The number of backtracks used to try to fill the puzzle.
*/
private int countBacktracks;
public static final char BLANK = ' ';
public static final char FILLED = '#';
CrosswordSolver(char[][] puzzle, CrosswordSlot[] slots, CrosswordWord[] words) {
this.puzzle = puzzle;
this.slots = slots;
this.words = words;
}
/**
* Initialize the puzzle.
*/
private void reinitialize() {
letterUsage = new int[puzzle.length][puzzle[0].length];
countBacktracks = 0;
}
/**
* Solve the crossword puzzle.
*/
private void solve() {
reinitialize();
if (fillPuzzle(0)) {
System.out.println("Solution found!!!");
System.out.println("Backtracks:" + countBacktracks);
} else {
System.out.println("No solution found!!!");
}
}
/**
* Tries to fill the puzzle starting from a slot.
*
* #param slot slot to start filling in from
* #return whether the puzzle could be filled from the current slot
*/
private boolean fillPuzzle(int slot) {
if (slot == slots.length) {
printPuzzle();
return true;
}
for (CrosswordWord word : words) {
if (wordFitInSlot(word, slots[slot])) {
putWordInSlot(word, slots[slot]);
if (fillPuzzle(slot + 1)) {
return true;
} else {
//If we need to backtrack (fillPuzzle(slot + 1) didn't work)
removeWordFromSlot(word, slots[slot]);
}
}
}
countBacktracks++;
return false;
}
/**
* Checks if a word fits in a slot
*
* #param w word to try to fit in slot
* #param slot slot to try to fit the word into
* #return does word fit
*/
private boolean wordFitInSlot(CrosswordWord w, CrosswordSlot slot) {
if (w.getWord().length() != slot.getLength() || w.isUsed()) {
return false;
}
Point position = slot.getStart();
int row = position.y;
int column = position.x;
for (int i = 0; i < slot.getLength(); ++i) {
if (puzzle[row][column] != BLANK && puzzle[row][column] != w.getWord().charAt(i)) {
return false;
}
column += slot.getDirection().x;
row += slot.getDirection().y;
}
return true;
}
/**
* Puts a word inside a slot and sets the word as used.
*
* #param w word to put into the slot
* #param slot slot to put word into
*/
private void putWordInSlot(CrosswordWord w, CrosswordSlot slot) {
Point position = slot.getStart();
int row = position.y;
int column = position.x;
for (int i = 0; i < slot.getLength(); ++i) {
puzzle[row][column] = w.getWord().charAt(i);
letterUsage[row][column]++;
column += slot.getDirection().x;
row += slot.getDirection().y;
}
w.setUsed(true);
}
/**
* Remove word from slot.
*
* #param w word to remove from slot
* #param slot slot to remove the word from
*/
private void removeWordFromSlot(CrosswordWord w, CrosswordSlot slot) {
Point position = slot.getStart();
int row = position.y;
int column = position.x;
for (int i = 0; i < slot.getLength(); ++i) {
letterUsage[row][column]--;
if (letterUsage[row][column] <= 0) {
puzzle[row][column] = BLANK;
}
column += slot.getDirection().x;
row += slot.getDirection().y;
}
w.setUsed(false);
}
/**
* Print the puzzle.
*/
public void printPuzzle() {
printPuzzleBorder();
for (int row = 0; row < puzzle.length; row++) {
System.out.print("|");
for (int col = 0; col < puzzle[row].length; col++) {
System.out.print(puzzle[row][col] + "|");
}
System.out.println();
}
printPuzzleBorder();
System.out.println();
}
/**
* Print the border of the puzzle.
*/
private void printPuzzleBorder() {
for (int i = 0; i < puzzle[0].length * 2; ++i) {
System.out.print("-");
}
System.out.println();
}
public static void main(String args[]) {
CrosswordSlot[] slots = {new CrosswordSlot(new Point(0, 0), new Point(1, 0), 3),
new CrosswordSlot(new Point(0, 0), new Point(0, 1), 3),
new CrosswordSlot(new Point(2, 0), new Point(0, 1), 2),
new CrosswordSlot(new Point(2, 1), new Point(1, 0), 3),
new CrosswordSlot(new Point(4, 0), new Point(0, 1), 2),
};
char[][] smallPuzzle = {{BLANK, BLANK, BLANK, FILLED, BLANK}, {BLANK, FILLED, BLANK, BLANK, BLANK}, {BLANK, BLANK, FILLED, BLANK, FILLED}};
try {
String get_file = "C:/Users/xyz/Desktop/lemma.txt";
System.out.println("File name is:"+get_file);
FileReader fr = new FileReader(get_file);
BufferedReader br = new BufferedReader(fr);
String s1;
FileInputStream fis = new FileInputStream(get_file);
char c1;
while ((s1 = br.readLine()) != null) {
c1= (char)fis.read();
for (int i = 0; i < s1.length(); ++i) {
char c = s1.charAt(i);
if (c1 == 'a' || c1 == 'v' || (c1 == 'a' && c1 == 'd' && c1 == 'v')) {
System.out.println(c1);
//CrosswordWord[] words = {new CrosswordWord("abbey"), new CrosswordWord("accommodate"), new CrosswordWord(" about")};
}
}
} catch (Exception e) {
System.out.println(e);
}
CrosswordWord[] words = {new CrosswordWord("abb"), new CrosswordWord("acb"), new CrosswordWord("add"), new CrosswordWord("ba"), new CrosswordWord("bd")};
CrosswordSolver s = new CrosswordSolver(smallPuzzle, slots, words);
s.printPuzzle();
s.solve();
}
}
/**
* A slot in the crossword puzzle that we will need to fill.
*/
class CrosswordSlot {
private Point start;
private Point direction;
private int length;
public CrosswordSlot(Point start, Point direction, int length) {
this.start = start;
this.direction = direction;
this.length = length;
}
public Point getStart() {
return start;
}
public Point getDirection() {
return direction;
}
public int getLength() {
return length;
}
}
/**
* A word that we will try to fit inside the crossword.
*/
class CrosswordWord {
private String word;
private boolean used;
public CrosswordWord(String word) {
this.word = word;
used = false;
}
public String getWord() {
return word;
}
public boolean isUsed() {
return used;
}
public void setUsed(boolean isUsed) {
used = isUsed;
}
}
I used jflex to generate a Java class and now I want to use it to get lexical analysis of a .txt file. The Java Class begins like this:
/* The following code was generated by JFlex 1.6.1 */
/**
* This class is a scanner generated by
* JFlex 1.6.1
* from the specification file <tt>patch.flex</tt>
*/
public class Patch {
/** This character denotes the end of file */
public static final int YYEOF = -1;
/** initial size of the lookahead buffer */
private static final int ZZ_BUFFERSIZE = 16384;
/** lexical states */
public static final int YYINITIAL = 0;
/**
* ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l
* ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l
* at the beginning of a line
* l is of the form l = 2*k, k a non negative integer
*/
private static final int ZZ_LEXSTATE[] = {
0, 0
};
/**
* Translates characters to character classes
*/
private static final String ZZ_CMAP_PACKED =
"\141\0\1\1\1\2\1\3\1\4\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffab\0";
/**
* Translates characters to character classes
*/
private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED);
/**
* Translates DFA states to action switch labels.
*/
private static final int [] ZZ_ACTION = zzUnpackAction();
private static final String ZZ_ACTION_PACKED_0 =
"\1\0\2\1\3\0\1\2\2\0\2\2";
private static int [] zzUnpackAction() {
int [] result = new int[11];
int offset = 0;
offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result);
return result;
}
private static int zzUnpackAction(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
do result[j++] = value; while (--count > 0);
}
return j;
}
/**
* Translates a state to a row index in the transition table
*/
private static final int [] ZZ_ROWMAP = zzUnpackRowMap();
private static final String ZZ_ROWMAP_PACKED_0 =
"\0\0\0\5\0\12\0\12\0\17\0\24\0\31\0\36"+
"\0\31\0\5\0\36";
private static int [] zzUnpackRowMap() {
int [] result = new int[11];
int offset = 0;
offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result);
return result;
}
private static int zzUnpackRowMap(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int high = packed.charAt(i++) << 16;
result[j++] = high | packed.charAt(i++);
}
return j;
}
/**
* The transition table of the DFA
*/
private static final int [] ZZ_TRANS = zzUnpackTrans();
private static final String ZZ_TRANS_PACKED_0 =
"\1\2\1\3\3\2\6\0\1\4\1\5\1\6\3\0"+
"\1\5\1\7\2\0\1\10\1\0\1\6\4\0\1\11"+
"\1\12\1\0\1\13\3\0";
private static int [] zzUnpackTrans() {
int [] result = new int[35];
int offset = 0;
offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result);
return result;
}
private static int zzUnpackTrans(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
value--;
do result[j++] = value; while (--count > 0);
}
return j;
}
/* error codes */
private static final int ZZ_UNKNOWN_ERROR = 0;
private static final int ZZ_NO_MATCH = 1;
private static final int ZZ_PUSHBACK_2BIG = 2;
/* error messages for the codes above */
private static final String ZZ_ERROR_MSG[] = {
"Unknown internal scanner error",
"Error: could not match input",
"Error: pushback value was too large"
};
/**
* ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code>
*/
private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute();
private static final String ZZ_ATTRIBUTE_PACKED_0 =
"\1\0\1\11\1\1\3\0\1\1\2\0\1\11\1\1";
private static int [] zzUnpackAttribute() {
int [] result = new int[11];
int offset = 0;
offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result);
return result;
}
private static int zzUnpackAttribute(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
do result[j++] = value; while (--count > 0);
}
return j;
}
/** the input device */
private java.io.Reader zzReader;
/** the current state of the DFA */
private int zzState;
/** the current lexical state */
private int zzLexicalState = YYINITIAL;
/** this buffer contains the current text to be matched and is
the source of the yytext() string */
private char zzBuffer[] = new char[ZZ_BUFFERSIZE];
/** the textposition at the last accepting state */
private int zzMarkedPos;
/** the current text position in the buffer */
private int zzCurrentPos;
/** startRead marks the beginning of the yytext() string in the buffer */
private int zzStartRead;
/** endRead marks the last character in the buffer, that has been read
from input */
private int zzEndRead;
/** number of newlines encountered up to the start of the matched text */
private int yyline;
/** the number of characters up to the start of the matched text */
private int yychar;
/**
* the number of characters from the last newline up to the start of the
* matched text
*/
private int yycolumn;
/**
* zzAtBOL == true <=> the scanner is currently at the beginning of a line
*/
private boolean zzAtBOL = true;
/** zzAtEOF == true <=> the scanner is at the EOF */
private boolean zzAtEOF;
/** denotes if the user-EOF-code has already been executed */
private boolean zzEOFDone;
/**
* The number of occupied positions in zzBuffer beyond zzEndRead.
* When a lead/high surrogate has been read from the input stream
* into the final zzBuffer position, this will have a value of 1;
* otherwise, it will have a value of 0.
*/
private int zzFinalHighSurrogate = 0;
/**
* Creates a new scanner
*
* #param in the java.io.Reader to read input from.
*/
public Patch(java.io.Reader in) {
this.zzReader = in;
}
/**
* Unpacks the compressed character translation table.
*
* #param packed the packed character translation table
* #return the unpacked character translation table
*/
private static char [] zzUnpackCMap(String packed) {
char [] map = new char[0x110000];
int i = 0; /* index in packed string */
int j = 0; /* index in unpacked array */
while (i < 44) {
int count = packed.charAt(i++);
char value = packed.charAt(i++);
do map[j++] = value; while (--count > 0);
}
return map;
}
/**
* Refills the input buffer.
*
* #return <code>false</code>, iff there was new input.
*
* #exception java.io.IOException if any I/O-Error occurs
*/
private boolean zzRefill() throws java.io.IOException {
/* first: make room (if you can) */
if (zzStartRead > 0) {
zzEndRead += zzFinalHighSurrogate;
zzFinalHighSurrogate = 0;
System.arraycopy(zzBuffer, zzStartRead,
zzBuffer, 0,
zzEndRead-zzStartRead);
/* translate stored positions */
zzEndRead-= zzStartRead;
zzCurrentPos-= zzStartRead;
zzMarkedPos-= zzStartRead;
zzStartRead = 0;
}
/* is the buffer big enough? */
if (zzCurrentPos >= zzBuffer.length - zzFinalHighSurrogate) {
/* if not: blow it up */
char newBuffer[] = new char[zzBuffer.length*2];
System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length);
zzBuffer = newBuffer;
zzEndRead += zzFinalHighSurrogate;
zzFinalHighSurrogate = 0;
}
/* fill the buffer with new input */
int requested = zzBuffer.length - zzEndRead;
int numRead = zzReader.read(zzBuffer, zzEndRead, requested);
/* not supposed to occur according to specification of java.io.Reader */
if (numRead == 0) {
throw new java.io.IOException("Reader returned 0 characters. See JFlex examples for workaround.");
}
if (numRead > 0) {
zzEndRead += numRead;
/* If numRead == requested, we might have requested to few chars to
encode a full Unicode character. We assume that a Reader would
otherwise never return half characters. */
if (numRead == requested) {
if (Character.isHighSurrogate(zzBuffer[zzEndRead - 1])) {
--zzEndRead;
zzFinalHighSurrogate = 1;
}
}
/* potentially more input available */
return false;
}
/* numRead < 0 ==> end of stream */
return true;
}
/**
* Closes the input stream.
*/
public final void yyclose() throws java.io.IOException {
zzAtEOF = true; /* indicate end of file */
zzEndRead = zzStartRead; /* invalidate buffer */
if (zzReader != null)
zzReader.close();
}
/**
* Resets the scanner to read from a new input stream.
* Does not close the old reader.
*
* All internal variables are reset, the old input stream
* <b>cannot</b> be reused (internal buffer is discarded and lost).
* Lexical state is set to <tt>ZZ_INITIAL</tt>.
*
* Internal scan buffer is resized down to its initial length, if it has grown.
*
* #param reader the new input stream
*/
public final void yyreset(java.io.Reader reader) {
zzReader = reader;
zzAtBOL = true;
zzAtEOF = false;
zzEOFDone = false;
zzEndRead = zzStartRead = 0;
zzCurrentPos = zzMarkedPos = 0;
zzFinalHighSurrogate = 0;
yyline = yychar = yycolumn = 0;
zzLexicalState = YYINITIAL;
if (zzBuffer.length > ZZ_BUFFERSIZE)
zzBuffer = new char[ZZ_BUFFERSIZE];
}
/**
* Returns the current lexical state.
*/
public final int yystate() {
return zzLexicalState;
}
/**
* Enters a new lexical state
*
* #param newState the new lexical state
*/
public final void yybegin(int newState) {
zzLexicalState = newState;
}
/**
* Returns the text matched by the current regular expression.
*/
public final String yytext() {
return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead );
}
/**
* Returns the character at position <tt>pos</tt> from the
* matched text.
*
* It is equivalent to yytext().charAt(pos), but faster
*
* #param pos the position of the character to fetch.
* A value from 0 to yylength()-1.
*
* #return the character at position pos
*/
public final char yycharat(int pos) {
return zzBuffer[zzStartRead+pos];
}
/**
* Returns the length of the matched text region.
*/
public final int yylength() {
return zzMarkedPos-zzStartRead;
}
/**
* Reports an error that occured while scanning.
*
* In a wellformed scanner (no or only correct usage of
* yypushback(int) and a match-all fallback rule) this method
* will only be called with things that "Can't Possibly Happen".
* If this method is called, something is seriously wrong
* (e.g. a JFlex bug producing a faulty scanner etc.).
*
* Usual syntax/scanner level error handling should be done
* in error fallback rules.
*
* #param errorCode the code of the errormessage to display
*/
private void zzScanError(int errorCode) {
String message;
try {
message = ZZ_ERROR_MSG[errorCode];
}
catch (ArrayIndexOutOfBoundsException e) {
message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
}
throw new Error(message);
}
/**
* Pushes the specified amount of characters back into the input stream.
*
* They will be read again by then next call of the scanning method
*
* #param number the number of characters to be read again.
* This number must not be greater than yylength()!
*/
public void yypushback(int number) {
if ( number > yylength() )
zzScanError(ZZ_PUSHBACK_2BIG);
zzMarkedPos -= number;
}
/**
* Resumes scanning until the next regular expression is matched,
* the end of input is encountered or an I/O-Error occurs.
*
* #return the next token
* #exception java.io.IOException if any I/O-Error occurs
*/
public int yylex() throws java.io.IOException {
int zzInput;
int zzAction;
// cached fields:
int zzCurrentPosL;
int zzMarkedPosL;
int zzEndReadL = zzEndRead;
char [] zzBufferL = zzBuffer;
char [] zzCMapL = ZZ_CMAP;
int [] zzTransL = ZZ_TRANS;
int [] zzRowMapL = ZZ_ROWMAP;
int [] zzAttrL = ZZ_ATTRIBUTE;
while (true) {
zzMarkedPosL = zzMarkedPos;
boolean zzR = false;
int zzCh;
int zzCharCount;
for (zzCurrentPosL = zzStartRead ;
zzCurrentPosL < zzMarkedPosL ;
zzCurrentPosL += zzCharCount ) {
zzCh = Character.codePointAt(zzBufferL, zzCurrentPosL, zzMarkedPosL);
zzCharCount = Character.charCount(zzCh);
switch (zzCh) {
case '\u000B':
case '\u000C':
case '\u0085':
case '\u2028':
case '\u2029':
yyline++;
yycolumn = 0;
zzR = false;
break;
case '\r':
yyline++;
yycolumn = 0;
zzR = true;
break;
case '\n':
if (zzR)
zzR = false;
else {
yyline++;
yycolumn = 0;
}
break;
default:
zzR = false;
yycolumn += zzCharCount;
}
}
if (zzR) {
// peek one character ahead if it is \n (if we have counted one line too much)
boolean zzPeek;
if (zzMarkedPosL < zzEndReadL)
zzPeek = zzBufferL[zzMarkedPosL] == '\n';
else if (zzAtEOF)
zzPeek = false;
else {
boolean eof = zzRefill();
zzEndReadL = zzEndRead;
zzMarkedPosL = zzMarkedPos;
zzBufferL = zzBuffer;
if (eof)
zzPeek = false;
else
zzPeek = zzBufferL[zzMarkedPosL] == '\n';
}
if (zzPeek) yyline--;
}
zzAction = -1;
zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL;
zzState = ZZ_LEXSTATE[zzLexicalState];
// set up zzAction for empty match case:
int zzAttributes = zzAttrL[zzState];
if ( (zzAttributes & 1) == 1 ) {
zzAction = zzState;
}
zzForAction: {
while (true) {
if (zzCurrentPosL < zzEndReadL) {
zzInput = Character.codePointAt(zzBufferL, zzCurrentPosL, zzEndReadL);
zzCurrentPosL += Character.charCount(zzInput);
}
else if (zzAtEOF) {
zzInput = YYEOF;
break zzForAction;
}
else {
// store back cached positions
zzCurrentPos = zzCurrentPosL;
zzMarkedPos = zzMarkedPosL;
boolean eof = zzRefill();
// get translated positions and possibly new buffer
zzCurrentPosL = zzCurrentPos;
zzMarkedPosL = zzMarkedPos;
zzBufferL = zzBuffer;
zzEndReadL = zzEndRead;
if (eof) {
zzInput = YYEOF;
break zzForAction;
}
else {
zzInput = Character.codePointAt(zzBufferL, zzCurrentPosL, zzEndReadL);
zzCurrentPosL += Character.charCount(zzInput);
}
}
int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ];
if (zzNext == -1) break zzForAction;
zzState = zzNext;
zzAttributes = zzAttrL[zzState];
if ( (zzAttributes & 1) == 1 ) {
zzAction = zzState;
zzMarkedPosL = zzCurrentPosL;
if ( (zzAttributes & 8) == 8 ) break zzForAction;
}
}
}
// store back cached position
zzMarkedPos = zzMarkedPosL;
if (zzInput == YYEOF && zzStartRead == zzCurrentPos) {
zzAtEOF = true;
return YYEOF;
}
else {
switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) {
case 1:
{ System.out.print(yytext());
}
case 3: break;
case 2:
{ System.out.println("***found match");
}
case 4: break;
default:
zzScanError(ZZ_NO_MATCH);
}
}
}
}
/**
* Runs the scanner on input files.
*
* This is a standalone scanner, it will print any unmatched
* text to System.out unchanged.
*
* #param argv the command line, contains the filenames to run
* the scanner on.
*/
public static void main(String argv[]) {
if (argv.length == 0) {
System.out.println("Usage : java Patch [ --encoding <name> ] <inputfile(s)>");
}
else {
int firstFilePos = 0;
String encodingName = "UTF-8";
if (argv[0].equals("--encoding")) {
firstFilePos = 2;
encodingName = argv[1];
try {
java.nio.charset.Charset.forName(encodingName); // Side-effect: is encodingName valid?
} catch (Exception e) {
System.out.println("Invalid encoding '" + encodingName + "'");
return;
}
}
for (int i = firstFilePos; i < argv.length; i++) {
Patch scanner = null;
try {
java.io.FileInputStream stream = new java.io.FileInputStream(argv[i]);
java.io.Reader reader = new java.io.InputStreamReader(stream, encodingName);
scanner = new Patch(reader);
while ( !scanner.zzAtEOF ) scanner.yylex();
}
catch (java.io.FileNotFoundException e) {
System.out.println("File not found : \""+argv[i]+"\"");
}
catch (java.io.IOException e) {
System.out.println("IO error scanning file \""+argv[i]+"\"");
System.out.println(e);
}
catch (Exception e) {
System.out.println("Unexpected exception:");
e.printStackTrace();
}
}
}
}
}
The shell keep giving me the error
Error: Could not find or load main class Patch
when I use the command like:
java Patch SearchText.txt
Besides, there's no error when I run:
javac Patch.java
I tried to set the path explicitly:
java -cp. Patch SearchText.txt
and got something like this:
{\rtf1\ansi\ansicpg1252\cocoartf1348\cocoasubrtf170
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
{\colortbl;\red255\green255\blue255;}
\margl1440\margr1440\vieww10800\viewh8400\viewkind0
\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural
\f0\fs24 \cf0 a+b+c+d}AmbertekiMacBook-Air:ADS4 amber95$ java Patch SearchText.txt
Error: Could not find or load main class Patch
Have you tried this?
java -cp ./ Patch file.txt
I am a beginner in java development field and still i am a learner of Java Programming. I wanted to see the output for the Support Vector Machine classifier on netbeans IDE. So i copied this attached piece of code and tried to run by using all the other required class and main method as well but i am getting Number format exception when i give a file containing input like 23,25,26,27 during the call of the method loadBinaryProblem() in main method and if i remove all the commas and replaced them with space ex: 23 25 26 27 then i am getting ArrayIndexOutOfBound exception instead of it. So anybody can help to get the output properly without any error.
package svmlearn;
import java.io.*;
import java.util.*;
/**
* Class representing an optimization problem (a data setting);
* taken from liblinear; "bias" excluded
* #author miafranc
*
*/
public class Problem {
/** The number of training data */
public int l;
/** The number of features (including the bias feature if bias >= 0) */
public int n;
/** Array containing the target values */
public int[] y;
/** Map of categories to allow various ID's to identify classes with. */
public CategoryMap<Integer> catmap;
/** Array of sparse feature nodes */
public FeatureNode[][] x;
public Problem() {
l = 0;
n = 0;
catmap = new CategoryMap<Integer>();
}
/**
* Loads a binary problem from file, i.e. having 2 classes.
* #param filename The filename containing the problem in LibSVM format.
*/
public void loadBinaryProblem(String filename) {
String row;
ArrayList<Integer> classes = new ArrayList<Integer>();
ArrayList<FeatureNode []> examples = new ArrayList<FeatureNode []>();
try {
BufferedReader r = new BufferedReader(new FileReader(filename));
while ((row = r.readLine()) != null) {
String [] elems = row.split(" ");
//Category:
Integer cat = Integer.parseInt(elems[0]);
catmap.addCategory(cat);
if (catmap.size() > 2) {
throw new IllegalArgumentException("only 2 classes allowed!");
}
classes.add(catmap.getNewCategoryOf(cat));
//Index/value pairs:
examples.add(parseRow(elems));
}
x = new FeatureNode[examples.size()][];
y = new int[examples.size()];
for (int i=0; i<examples.size(); i++) {
x[i] = examples.get(i);
y[i] = 2*classes.get(i)-1; //0,1 => -1,1
}
l = examples.size();
} catch (Exception e) {
System.out.println(e);
}
}
/**
* Parses a row from a LibSVM format file.
* #param row The already split row on spaces.
* #return The corresponding FeatureNode.
*/
public FeatureNode [] parseRow(String [] row) {
FeatureNode [] example = new FeatureNode[row.length-1];
int maxindex = 0;
for (int i=1; i<row.length; i++) {
String [] iv = row[i].split(":");
int index = Integer.parseInt(iv[0]);
if (index <= maxindex) {
throw new IllegalArgumentException("indices must be in increasing order!");
}
maxindex = index;
double value = Double.parseDouble(iv[1]);
example[i-1] = new FeatureNode(index, value);
}
if (n < maxindex)
n = maxindex;
return example;
}
}
i guess NumberformatExceptions comes from:
String [] elems = row.split(" "); //nothing done by "23,25,26,27"
//Category:
Integer cat = Integer.parseInt(elems[0]); //you are trying to parse "23,25,26,27"
ArrayIndexOutOfBound comes from:
String [] iv = row[i].split(":");//nothing done
...
double value = Double.parseDouble(iv[1]);//1 is out of bound