Convert JAVA program to PHP code - java

I have below program in JAVA.
private static int frogJump(int[] arrEl,int postion) {
/** Marker array for the leaf found on the way. */
boolean[] leafArray = new boolean[postion+1];
/** Total step needed for frog. */
int steps = postion;
for(int i = 0; i<arrEl.length; i++) {
/** if leaf needed for frog and it does not exist earlier. **/
if(postion>=arrEl[i] && !leafArray[arrEl[i]]) {
/* Mark leaf found */
leafArray[arrEl[i]] = true;
/** Reduce the step by one(coz one jump found). */
steps--;
}
if(steps == 0 && arrEl[i]==postion) {
return i;
}
}
return -1;
}
Which i want to convert in PHP.
Till now what i have done is
function solution ($A = [], $Position) {
$StonesArray = array();
$StonesArray[TRUE] = $Position + 1;
$steps = $Position;
for($i = 0; $i< count($A); $i++) {
echo "<pre>";
print_r($StonesArray);
if($Position >= $A[$i] && !$StonesArray[$A[$i]]) {
$StonesArray[$A[$i]] = true;
$steps--;
}
if($steps == 0 && $A[$i] == $Position) {
return $i;
}
}
return -1;
}
$GetSolution = solution([3,2,1], 1);
echo "<pre>";
print_r($GetSolution);
above program should return 3. but after i have converted the program to PHP language its not returning the expected value.
I am sure I have done everything correct except converting the below line
boolean[] leafArray = new boolean[postion+1];
How to write this line in PHP?

I just translated your original Java code to PHP 1:1, most of it can be used as is with little change, look at this example:
function frogJump(array $arrEl, $postion) {
/** Marker array for the leaf found on the way. */
$leafArray = array_fill(0, $postion+1, false);
/** Total step needed for frog. */
$steps = $postion;
for($i = 0; $i<count($arrEl); $i++) {
/** if leaf needed for frog and it does not exist earlier. **/
if($postion>=$arrEl[$i] && !$leafArray[$arrEl[$i]]) {
/* Mark leaf found */
$leafArray[$arrEl[$i]] = true;
/** Reduce the step by one(coz one jump found). */
$steps--;
}
if($steps == 0 && $arrEl[$i]==$postion) {
return $i;
}
}
return -1;
}
print_r(frogJump([3,2,1], 1)); outputs 2.
I also compiled the Java code and the output is also 2, so it seems correct to me? Run with System.out.println(frogJump(new int[]{3,2,1}, 1));

Related

java program is printing objects in the wrong order

I'm trying to write a class called RailwayStation that will print an array of train (using two different classes I wrote called TIME1and Train. My problem is that I can't understand why the output is arranged in the wrong order.
I assume the problem is in the method inside the class called addTrain, which supposed to add a train trip if there exists an empty cell in the array, and if the trip that wishes to be added does not exists already in the array. another method I used (and might be the problem) is called removeTrain, which receives a parameter of a train trip and removes that from the array. My methods addTrain, removerTrain, and toStringis as follows:
public class RailwayStation {
// declrations of final variables
private final int MAX_TRAINS = 100;
private final int MIN_VAL = 0;
// declrations of instant variables
private Train[] _station;
private int _noOfTrs;
/**
* Empty construter which initialize the instant variables of the class such that the trips array will be in a maximal size
*/
public RailwayStation() {
_station = new Train[MAX_TRAINS];
_noOfTrs = MIN_VAL;
}
/**
* adds a train trip to the trips array
*
* #param f the train trip
* #Returns true if a train trip has been added to the trips array
*/
public boolean addTrain(Train f) {
int i, j;
// boolean found = false;
if (isTrainOnSomeStation(f)) {
return false;
}
else {
for (j = MIN_VAL; j < _station.length; j++) {
if (_station[j] == null) {
_station[j] = f;
_noOfTrs++;
return true;
}
}
return false;
}
}
// a private method that checks if #param f is null
private boolean isTrainOnSomeStation(Train f) {
if (f == null) {
return false;
}
for (int i = MIN_VAL; i < _station.length; i++) {
if (_station[i] != null && _station[i].equals(f)) {
return true;
}
}
return false;
}
/**
* removes a trip from the trips array
* #param f the train trip
* #returns true if the train trip has been removed
*/
public boolean removeTrain(Train f) {
int i, j;
boolean found = false;
for (j = MIN_VAL; j < _station.length && !found; j++) {
if (_station[j] != null) {
for (i = MIN_VAL; i < _noOfTrs && !found; i++)
if (_station[i].equals(f)) {
_station[i] = _station[_noOfTrs];
_station[_noOfTrs] = null;
found = true;
_noOfTrs--;
}
}
}
return found;
}
/** Returns a string which describes all train in the array as apperas in the arrray
* #Returns a string of trains as appears in the arrat
*/
public String toString(){
String str = "The trains today are:" +"\n";
if(_noOfTrs == MIN_VAL){
return "There are no trains today.";
}
else {
String capacity = "";
for (int i = 0; i < _station.length; i++) {
if (_station[i] != null) {
if (_station[i].isFull() == true) {
capacity = "Train is full";
}
else {
capacity = "Train is not full";
}
str += _station[i].toString() + "\n";
}
}
}
return str;
}
}
In order to call the method addTrain I'll be writing:
//Check constructor
RailwayStation rs = new RailwayStation();
//AddTrain
Train f1 = new Train("Haifa",12,0,210,250,250,55);
Train f2 = new Train("Jerusalem",10,50,210,250,250,40);
rs.addTrain(f1);
rs.addTrain(f2);
System.out.println(rs);
//RemoveTrain
rs.removeTrain(f1);
System.out.println(rs);
//First Train to Destination
Train f3 = new Train("Tel-Aviv",11,35,180,100,200,35);
rs.addTrain(f3);
Train f3a = new Train("Tel-Aviv",7,15,180,200,200,35);
rs.addTrain(f3a);
I'm expecting to get the output:
The trains today are:
Train to Jerusalem departs at 10:50. Train is full.
Train to Tel-Aviv departs at 11:35. Train is not full.
Train to Tel-Aviv departs at 07:15. Train is full.
but what I get is:
The trains today are:
Train to Tel-Aviv departs at 11:35. Train is not full.
Train to Jerusalem departs at 10:50. Train is full.
Train to Tel-Aviv departs at 07:15. Train is full.
I've tried to use the debugger in order to understand in what part the order gets wrong, but I can't locate the problem.
When you add the first trains your array is like so:
Train[0] = Haifa...
Train[1] = Jerusalem..
Train[2] = null
Train[3] = null
...
Then you remove Haifa:
Train[0] = null
Train[1] = Jerusalem..
Train[2] = null
Train[3] = null
...
Then you add the other trains:
Train[0] = Tel Aviv..
Train[1] = Jerusalem..
Train[2] = Tel Aviv..
Train[3] = null
...
Does that explain it?
The data structure you're trying to build here is a Stack - but the good news is that java already has one, so no need to do what you are trying to do:
Stack<Train> trains = new Stack<>();
Train f1 = new Train("Haifa",12,0,210,250,250,55);
Train f2 = new Train("Jerusalem",10,50,210,250,250,40);
trains.push(f1);
trains.push(f2);
//RemoveTrain
trains.remove(f1);
//First Train to Destination
Train f3 = new Train("Tel-Aviv",11,35,180,100,200,35);
trains.push(f3);
Train f3a = new Train("Tel-Aviv",7,15,180,200,200,35);
trains.push(f3a);
String str = "The trains today are:" +"\n";
for(Train train: trains) {
str = str + train + "\n";
}
System.out.println(str);

Java - A* Search Issue

Issue resolved.
I've implemented an A* Search algorithm for path-finding in a simple grid-based game. It's my first time doing so, and the implementation works great most of the time. However, sometimes (albeit very rarely) it will get stuck when there is a path available. Of course, the fact that it gets stuck at all makes it not fit for purpose. I assume that I am missing something from my implementation.
I have looked for the issue for several days, to no avail. I have a fast-approaching deadline and a lot of things to do, I'd rather not waste any more time trying to fix this bug.
Edit: I've created a quick video to demonstrate the issue, that way you can see exactly what's going on. It includes captions.
Edit: The getPath method:
/**
* #param currentPosition - the vector the avatar currently occupies.
* #param targetPosition - the vector the avatar is aiming to reach.
* #param levelMap - a clip map of the level.
*
* #return an {#code ArrayList} of {#link ACTIONS} that the avatar can follow to reach its destination.
**/
public static ActionPath getPath(Vector2d currentPosition, Vector2d targetPosition, LevelMap levelMap) {
openTiles = new ArrayList<AStarTile>();
closedTiles = new ArrayList<AStarTile>();
targetMet = false;
AStarTile originTile = AStarTile.fromVector(currentPosition, levelMap.getBlockSize()),
targetTile = AStarTile.fromVector(targetPosition, levelMap.getBlockSize()),
currentTile = null,
parentTile = null;
ActionPath actionPath = new ActionPath(targetTile);
if (originTile.equals(targetTile)) {
targetMet = true;
return null;
}
GVGLogger.logInfo("Creating path from tile " + originTile + " to tile " + targetTile + " (" + currentPosition + " to " + targetPosition + ").");
/*
* Start the search.
*/
openTile(originTile);
originTile.calculateGeneration();// The origin tile will always be generation 0.
closeTile(originTile);
parentTile = originTile;
while(!targetMet) {
for (int i = 0; i != 4; i++) {
currentTile = parentTile.move(i);// Checks an adjacent tile - up, down, left, and right respectively
if (levelMap.inBounds(currentTile) && levelMap.isAccessible(currentTile) && !isClosed(currentTile)) {
if (isOpen(currentTile)) {
// Check to see if this path to this tile is a better one.
currentTile = getOpen(currentTile);
if (currentTile.getGeneration() > parentTile.getGeneration() + 1) {
// The open version's generation is higher than this version's generation - it's a better path
currentTile.setParentTile(parentTile);
currentTile.calculateGeneration();
currentTile.calculateFinalScore();
}
}
else {
currentTile.setParentTile(parentTile);
currentTile.setHeuristic(currentTile.distanceSquared(targetTile));
currentTile.calculateGeneration();
currentTile.calculateFinalScore();
openTile(currentTile);
}
}
}
if (openTiles.size() > 0) {
parentTile = getBestOption();
closeTile(parentTile);
if (parentTile.equals(targetTile)) {
targetMet = true;
}
}
else {
GVGLogger.logWarning("Target unreachable!");
return null;
}
}
//Convert the path of tiles into ACTIONS that the avatar can take to reach it.
for (int i = 0; i != closedTiles.size(); i++) {
Vector2i difference = getDifference(closedTiles.get(i), (i != closedTiles.size() - 1 ? closedTiles.get(i + 1) : targetTile));
if (difference.equals(1, 0)) {
actionPath.add(ACTIONS.ACTION_LEFT);
}
else if (difference.equals(-1, 0)) {
actionPath.add(ACTIONS.ACTION_RIGHT);
}
else if (difference.equals(0, -1)) {
actionPath.add(ACTIONS.ACTION_DOWN);
}
else if (difference.equals(0, 1)) {
actionPath.add(ACTIONS.ACTION_UP);
}
else if (difference.equals(0, 0)) {
return actionPath;
}
else {
GVGLogger.logWarning("Error in path-finding - found a difference of " + difference + "!");
}
}
return null;
}
private static Vector2i getDifference(AStarTile tileA, AStarTile tileB) {
return new Vector2i(tileA.getX() - tileB.getX(), tileA.getY() - tileB.getY());
}
public static boolean targetMet() {
return targetMet;
}
private static void openTile(AStarTile toOpen) {
if (isClosed(toOpen)) {
closedTiles.remove(getOpen(toOpen));
}
if (!isOpen(toOpen)) {
openTiles.add(toOpen);
}
}
private static void closeTile(AStarTile toClose) {
if (isOpen(toClose)) {
openTiles.remove(getOpen(toClose));
}
if (!isClosed(toClose)) {
closedTiles.add(toClose);
}
}
private static boolean isClosed(AStarTile toCheck) {
return getClosed(toCheck) != null;
}
private static boolean isOpen(AStarTile toCheck) {
return getOpen(toCheck) != null;
}
/**
* #return the open tile with the lowest 'final' score.
**/
private static AStarTile getBestOption() {
try {
Collections.sort(openTiles);
return openTiles.get(0);
}
catch(Exception e) {
}
return null;
}
private static AStarTile getClosed(AStarTile t) {
for (AStarTile p : closedTiles) {
if (p.equals(t)) {
return t;
}
}
return null;
}
private static AStarTile getOpen(AStarTile t) {
for (AStarTile p : openTiles) {
if (p.equals(t)) {
return t;
}
}
return null;
}
}
This method returns a list of 'ACTIONS' that the avatar can take to rich the destination tile. If you wish to see any other methods, please ask.
I wrote this implementation after reading an explanation/tutorial by Patrick Lester found at policyalmanac.org ("A* Pathfinding for Beginners").
I'd really appreciate it if you could glance over my implementation and point out any issues, especially if you are experienced with the A* Search algorithm. I think the code is pretty self-documenting, but please feel free to ask me to elaborate on anything if necessary.
Thanks for your time.
A couple of things look suspicious:
One
currentTile.getGeneration() > parentTile.getGeneration() + 1
Should this be >= instead of >?
Two
currentTile.setHeuristic(currentTile.distanceSquared(targetTile));
Squared distance is not an admissible heuristic as it can over-estimate the distance. Try using Manhattan distance (or simply setting the heuristic to 0 for a less efficient but more reliable search).
I've sorted it - I added a check on the generation when closing a tile. It now backtracks slightly instead of getting stuck.
Solution:
if (!closedTiles.isEmpty() && toClose.getGeneration() != lastClosed().getGeneration() + 1) {
openTiles.remove(getOpen(toClose));
return;
}
I'm so glad I've fixed it. Big thanks to anybody who took the time to read and/or answer the question! :)

Fixing checkstyle error

I need help with the checkstyle errors i keep getting in eclipse. I have tried everything the error is in my boolean method. It is stating that my nested if else is at 1 when it is supposed to be at zero. This is for all my if statements. Another error i had was that my method has 3 returns and checkstyle says the max is 2. I just want to rid myself of these errors can someone please help me.
public class Password {
private String potentialpassword;
private static final String SPECIAL_CHARACTERS = "!##$%^&*()~`-=_+[]{}|:\";',./<>?";
/**
* initializes the potential password and takes it as a string.
*
* #param potentialpassword
* takes in the potential password
*
*/
public Password(String potentialpassword) {
super();
this.potentialpassword = potentialpassword;
}
/**
* The purpose of this method is to validate whether the password meets the
* criteria that was given
*
* #param potentialpassword
* allows a string potential password to be accepted.
* #return true or false if the method fits a certain guideline.
* #precondition password has to be greater than 6 characters long. password
* also cannot contain any whitespace and the digits cannot be
* less than one.
*/
public static boolean isValid(String potentialpassword) {
if (potentialpassword.length() < 6) {
return false;
} else {
char x;
int count = 0;
for (int i = 0; i < potentialpassword.length(); i++) {
x = potentialpassword.charAt(i);
if (SPECIAL_CHARACTERS.indexOf(String.valueOf(x)) >= 1) {
return true;
}
if (Character.isWhitespace(x)) {
return false;
}
if (Character.isDigit(x)) {
count++;
} else if (count < 1) {
return false;
}
}
return true;
}
}
/**
* Print the potential string characters on a separate line.
*
* #return the potential password characters on each line.
*
*
*/
public String toString() {
String potentialpassword = "w0lf#UWG";
for (int i = 0; i < potentialpassword.length(); i++) {
System.out.println(potentialpassword.charAt(i));
}
return potentialpassword;
}
}
Style checkers can complain a lot. You can quiet it down by changing its settings to not be so picky, or you can work on some of its suggestions. In your case it does not like too much nesting and it does not like multiple returns.
The else after a return might be an issue, so you could say
if (potentialpassword.length() < 6) {
return false;
}
char x;
int count = 0;
for (int i = 0; i < potentialpassword.length(); i++) {
.
.
.
to reduce nesting. If the multiple return statements is more of a problem you can try:
// NOTE I am just copying over your code and not worrying about the algorithm's correctness
boolean valid = true;
if (potentialpassword.length() < 6) {
valid = false;
} else {
char x;
int count = 0;
for (int i = 0; i < potentialpassword.length(); i++) {
x = potentialpassword.charAt(i);
if (SPECIAL_CHARACTERS.indexOf(String.valueOf(x)) >= 1) {
valid = true;
break;
}
if (Character.isWhitespace(x)) {
valid = false;
break;
}
if (Character.isDigit(x)) {
count++;
} else if (count < 1) {
valid = false;
break;
}
}
return valid;
}
which reduces the number of return statements, but the nesting level stays high. Perhaps breaking your code into smaller methods may help:
public static boolean isValid(String potentialpassword) {
return potentialpassword.length >= 6 &&
containsAtLeastOneSpecialCharacter(potentialpassword) &&
!containsWhitespace(potentialpassword) &&
startsWithADigit(potentialpassword);
}
Then you have no nesting here, but the code is a little less efficient because you run each test on the whole string. And you will have quite a few more lines of code. I would imagine checkstyle would be quieter, though.

Depth-first search terminating early

I'm creating a program in Java that solves the n-puzzle, without using heuristics, simply just with depth-first and breadth-first searches of the state space. I'm struggling a little bit with my implementation of depth-first search. Sometimes it will solve the given puzzle, but other times it seems to give up early.
Here's my DFS class. DepthFirstSearch() is passed a PuzzleBoard, which is initially generated by shuffling a solved board (to ensure that the board is in a solvable state).
public class DepthFirst {
static HashSet<PuzzleBoard> usedStates = new HashSet<PuzzleBoard>();
public static void DepthFirstSearch(PuzzleBoard currentBoard)
{
// If the current state is the goal, stop.
if (PuzzleSolver.isGoal(currentBoard)) {
System.out.println("Solved!");
System.exit(0);
}
// If we haven't encountered the state before,
// attempt to find a solution from that point.
if (!usedStates.contains(currentBoard)) {
usedStates.add(currentBoard);
PuzzleSolver.print(currentBoard);
if (PuzzleSolver.blankCoordinates(currentBoard)[1] != 0) {
System.out.println("Moving left");
DepthFirstSearch(PuzzleSolver.moveLeft(currentBoard));
}
if (PuzzleSolver.blankCoordinates(currentBoard)[0] != PuzzleSolver.n-1) {
System.out.println("Moving down");
DepthFirstSearch(PuzzleSolver.moveDown(currentBoard));
}
if (PuzzleSolver.blankCoordinates(currentBoard)[1] != PuzzleSolver.n-1) {
System.out.println("Moving right");
DepthFirstSearch(PuzzleSolver.moveRight(currentBoard));
}
if (PuzzleSolver.blankCoordinates(currentBoard)[0] != 0) {
System.out.println("Moving up");
DepthFirstSearch(PuzzleSolver.moveUp(currentBoard));
}
return;
} else {
// Move up a level in the recursive calls
return;
}
}
}
I can assert that my moveUp(), moveLeft(), moveRight(), and moveDown() methods and logic work correctly, so the problem must lie somewhere else.
Here's my PuzzleBoard object class with the hashCode and equals methods:
static class PuzzleBoard {
short[][] state;
/**
* Default constructor for a board of size n
* #param n Size of the board
*/
public PuzzleBoard(short n) {
state = PuzzleSolver.getGoalState(n);
}
public PuzzleBoard(short n, short[][] initialState) {
state = initialState;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.deepHashCode(state);
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
PuzzleBoard other = (PuzzleBoard) obj;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (state[i][j] != other.state[i][j])
return false;
}
}
return true;
}
}
As previously stated, sometimes the search works properly and finds a path to the solution, but other times it stops before it finds a solution and before it runs out of memory.
Here is a snippet of the output, beginning a few moves before the search stops searching.
...
Moving down
6 1 3
5 8 2
0 7 4
Moving right
6 1 3
5 8 2
7 0 4
Moving left
Moving right
Moving up
6 1 3
5 0 2
7 8 4
Moving left
Moving down
Moving right
Moving up
Moving up
Moving right
Moving down
Moving up
Moving down
Moving up
Moving down
Moving up
Moving down
Moving up
Moving down
...
I truncated it early for brevity, but it ends up just moving up and down dozens of times and never hits the solved state.
Can anyone shed light on what I'm doing wrong?
Edit: Here is MoveUp(). The rest of the move methods are implemented in the same way.
/**
* Move the blank space up
* #return The new state of the board after the move
*/
static PuzzleBoard moveUp(PuzzleBoard currentState) {
short[][] newState = currentState.state;
short col = blankCoordinates(currentState)[0];
short row = blankCoordinates(currentState)[1];
short targetCol = col;
short targetRow = row;
newState[targetCol][targetRow] = currentState.state[col - 1][row];
newState[targetCol - 1][targetRow] = 0;
return new PuzzleBoard(n, newState);
}
I have had many problems with hashset in the past best thing to try is not to store object in hashset but try to encode your object into string.
Here is a way to do it:-
StringBuffer encode(PuzzleBoard b) {
StringBuffer buff = new StringBuffer();
for(int i=0;i<b.n;i++) {
for(int j=0;j<b.n;j++) {
// "," is used as separator
buff.append(","+b.state[i][j]);
}
}
return buff;
}
Make two changes in the code:-
if(!usedStates.contains(encode(currentBoard))) {
usedStates.add(encode(currentBoard));
......
}
Note:- Here no need to write your own hashcode function & also no need to implement equals function as java has done it for you in StringBuffer.
I got one of the problems in your implementation:-
In th following code:-
static PuzzleBoard moveUp(PuzzleBoard currentState) {
short[][] newState = currentState.state;
short col = blankCoordinates(currentState)[0];
short row = blankCoordinates(currentState)[1];
short targetCol = col;
short targetRow = row;
newState[targetCol][targetRow] = currentState.state[col - 1][row];
newState[targetCol - 1][targetRow] = 0;
return new PuzzleBoard(n, newState);
}
Here you are using the reference of same array as newState from currentState.state so when you make changes to newState your currentState.state will also change which will affect DFS when the call returns. To prevent that you should initialize a new array. Heres what to be done:-
static PuzzleBoard moveUp(PuzzleBoard currentState) {
short[][] newState = new short[n][n];
short col = blankCoordinates(currentState)[0];
short row = blankCoordinates(currentState)[1];
short targetCol = col;
short targetRow = row;
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
newState[i][j] = currentState.state[i][j];
}
}
newState[targetCol][targetRow] = currentState.state[col - 1][row];
newState[targetCol - 1][targetRow] = 0;
return new PuzzleBoard(n, newState);
}
Do this change for all moveup,movedown....
Moreover I donot think your hashset is working properly because if it was then you would always find your new state in hashset and your program would stop. As in equals you comparing the state arrays with same reference hence will always get true. Please try and use my encode function as hash.

Java Language Recognizer

I was given the assignment to "implement and test a language “recognizer” object, provided to you through a Java interface defined at the end of this document. A language recognizer accepts strings of characters and determines whether or not they are in the language."
The language is as follows:
L = {a*b} union {ab*}, or restated in English, L is the set of all strings of either (1) zero or more as (a*) followed by a b, or (2) an a followed by zero or more bs (b*).
I've made some progress, but I'm stuck.
Here's the interface:
/** The Recognizer interface provides a recognizer for the
* language L below.
*
* Let Sigma = {a,b} = the input character set.
*
* Let L = {ab*} union {a*b} be the language (set of
* legal strings) recognized by this recognizer.
*
* Let S = s1s2...sn be the string of n characters already
* input by this recognizer.
*
* Recognizer constructor must ensure: S' = < >
*/
interface Recognizer {
/**
* require: c in Sigma
*
* ensure: S' = S ^ c
*
* param c
*/
public void nextChar(char c);
/**
* Checks if input string S is in language L.
*
* return (S in L)
*/
public boolean isIn();
/**
* ensure: S' = < >
*/
public void reset();
}
Here's my structure:
import java.util.*;
public class LanguageVector implements Recognizer {
int element = 0;
int a = 0;
int b = 0;
Vector<Character> v = new Vector<Character>();
public void nextChar(char c) {
v.add(c);
}
public boolean isIn(){
boolean isTrue = true;
for(int i=0;i<v.size();i++) {
if (v.size() == 1){
if (v.firstElement() == 'a' || v.firstElement() =='b'){
isTrue = true;
}
else
isTrue = false;
}
else if (v.firstElement() == 'a'){
if (v.lastElement() == 'a')
isTrue = false;
else if (v.lastElement() == 'b')
while (v.elementAt(element)== 'a' ){
a++;
element++;
System.out.println(element);
}
while (v.elementAt(element)== 'b'){
b++;
element++;
System.out.println(element);
}
if (v.elementAt(element)!= 'b'){
isTrue = false;
}
else if (a > 1 && b > 1){
isTrue = false;
}
else
isTrue = true;
}
else if (v.firstElement() == 'b'){
isTrue = false;
}
else
isTrue = false;
}
return isTrue;
}
public void reset(){
v.clear();
}
}
And here's my testing class:
import java.util.*;
public class LanguageTester {
/**
* #param args
*/
public static void main(String[] args) {
Recognizer r = new LanguageVector();
r.nextChar('a');
r.nextChar('a');
r.nextChar('a');
r.nextChar('b');
if (r.isIn())
System.out.println("string is in L");
else
System.out.println("string is not in L");
System.out.println("End of test");
r.reset();
}
}
When I run, I get the following output:
1
2
3
Exception in thread "main" 4
java.lang.ArrayIndexOutOfBoundsException: 4 >= 4
at java.util.Vector.elementAt(Unknown Source)
at LanguageVector.isIn(LanguageVector.java:34)
at LanguageTester.main(LanguageTester.java:18)
Why is this happening?
Also, how can I use user input, turn it into a vector, and use that within this structure now?
Forgive me if this question is too lengthy, I wasn't sure how to narrow it down without leaving important details out. Thanks
When it occurs?
Out of bounds exception is occurred when you try to access an array with index that exceeded its length. maximum index of a java array is (length -1)
for example:
String [] stringArray = new String[10];
stringArray[10]
// the code above will produce an out of bounds exception, because the it bigger than length -1, which is 10 - 1 = 9.
If you don't know the size or length of an array, you can know it from stringArray.length.
How to handle it?
You should make sure that your program doesn't access an array with index bigger than length - 1.
example:
for(int i=0;i<stringArray.lenght;i++) {
//write your code here
}
the above code will guarantee that stringArray will never be accessed beyond its maximum index.
Your Case
In your case, 4 >= 4 itself says you are trying to access 5th element i.e. elementAt(4) however size of your Vector of 4.
Array is based on 0 index i.e. if your length is 4 you will have data at as Vector[0], Vector[1], Vector[2], Vector[3].
Also read this for more info...
The problem is in the isIn() method. You're not checking whether the element variable is still below v.size(). You just continue incrementing it so the next time that the application accesses v.elementAt(element); the variable element is bigger than the size of v, so it's an ArrayOutofBounds exception.

Categories