Fixing checkstyle error - java

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.

Related

Convert JAVA program to PHP code

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

Error: missing return statement (once more)

public static int salariDepart1( int duradaPeriode, int horesEfectives, float preuHora, int bonificHoresExtres) {
int salary;
if(duradaPeriode<0||horesEfectives<0||preuHora<0||bonificHoresExtres<0){
return (int) -1;
}
else if(horesEfectives<(duradaPeriode-(duradaPeriode*0.75))){
if(preuHora<6){
salary = (int) (preuHora * horesEfectives);
return (int) Math.round(salary);
}
else{
salary = (int) (horesEfectives * (preuHora-(preuHora*0.10)));
return (int) Math.round(salary);
}
}
else if(horesEfectives>(duradaPeriode+(duradaPeriode*0.20))){
bonificHoresExtres = (int) (preuHora+(preuHora*0.03));
if(bonificHoresExtres>200){
return (int) -2;
}
else if(bonificHoresExtres<200){
salary = (int) (horesEfectives * (preuHora+(preuHora*0.03)));
return (int) Math.round(salary);
}
else{
salary = (int) (horesEfectives * preuHora);
return (int) Math.round(salary);
}
}
}
public static void main(String[] args){
System.out.println(salariDepart1(200,120,8,5));
System.out.println(salariDepart1(190,100,7,10));
System.out.println(salariDepart1(180,90,7,20));
}
}
This error keeps popping up, and I dont know why. Help is appreciated. :)
The reason gets clearer if you indent the code consistently and clearly:
public static int salariDepart1(int duradaPeriode, int horesEfectives, float preuHora, int bonificHoresExtres) {
int salary;
if (duradaPeriode < 0 || horesEfectives < 0 || preuHora < 0 || bonificHoresExtres < 0) {
return (int) - 1;
} else if (horesEfectives < (duradaPeriode - (duradaPeriode * 0.75))) {
if (preuHora < 6) {
salary = (int)(preuHora * horesEfectives);
return (int) Math.round(salary);
} else {
salary = (int)(horesEfectives * (preuHora - (preuHora * 0.10)));
return (int) Math.round(salary);
}
} else if (horesEfectives > (duradaPeriode + (duradaPeriode * 0.20))) {
bonificHoresExtres = (int)(preuHora + (preuHora * 0.03));
if (bonificHoresExtres > 200) {
return (int) - 2;
} else if (bonificHoresExtres < 200) {
salary = (int)(horesEfectives * (preuHora + (preuHora * 0.03)));
return (int) Math.round(salary);
} else {
salary = (int)(horesEfectives * preuHora);
return (int) Math.round(salary);
}
}
}
What if duradaPeriode is >= 0 but neither horesEfectives < (duradaPeriode - (duradaPeriode * 0.75)) nor horesEfectives > (duradaPeriode + (duradaPeriode * 0.20)) is true? That's the path where the code doesn't return a value. So there's a path through the code that doesn't have a return.
Even if the conditions were all mutually-exclusive, the compiler can't always know that they are If they really are (which I don't think is the case above), make the final else if just an else. If they aren't, well, that's your problem, you need a returnin that case.
There is no else path for
else if(horesEfectives>(duradaPeriode+(duradaPeriode*0.20))){
So if that condition is not satisfied the compiler needs a return statement, which is missing.
Generally one should avoid to have many return statements, instead you better should introduce a returnValue variable which you inizialize at the beginning. This improves the abiliyt to debug your code.
int retVal = -1;
and assign the retVal in each of the conditions,
eg:
..
retVal = Math.round(salary);
..
finally return the value as last line
return retVal;
Set a default value that is returned when none of the conditional return statements are used.
So adding
return -1
for example at the end of the function will solve this
Not all code paths in your logic will encounter a return statement. Hence, you're missing one.
Your structure looks essentially like this:
if (something) {
if (something) {
return;
} else {
return;
}
} else if (something) {
if (something) {
return;
} else {
return;
}
}
Your "inner" conditionals are fine, but look at the "outer" one:
if (something) {
// every path in here returns
} else if (something) {
// and every path in here returns
}
What if neither of the "outer" conditions is true? No return statement is ever encountered.
Add an else to the "outer" conditional with a return or add a return after the entire conditional block. Every possible logical path through the method must return something.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 15

I cannot find my exception although the errors are at
at puzzle.Puzzle.isSafe(Puzzle.java:97)
at puzzle.Puzzle.main(Puzzle.java:49)
Java Result: 1
I need to print a 15x 15 grid with random words in 6 directions and starts in empty spaces.
My java code is as follows.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package puzzle;
//import java.util.Arrays;
import java.util.Random;
/**
*
* #author sony
*/
public class Puzzle {
static char[][] grid;
//class solve= new Puzzle();
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
grid =new char[15][15];
String[] words={"hello","coward","heartbeat","beautiful","kind"};
String[] direction = {"horizontal","horizontalBack","vertical","varticalUp",
"diagonal","diagonalBack"};
int i,j,x,y,dir;
Random randGen = new Random();
for(i=0; i<15 ;i++)
{
for(j=0;j<15;j++)
grid[i][j]='*';
}
for(i=0;i< words.length;i++)
{
int set=0;
while(set!=1)
{
x = randGen.nextInt(15);
y = randGen.nextInt(15);
dir = randGen.nextInt(6);
if((isSafe(x,y,words[i],direction[dir])))
{
place(x,y,words[i],direction[dir]);
set=1;
}
}
}
for(i=0; i<15; i++)
{
for(j=0;j<15;j++)
System.out.print(grid[i][j]);
System.out.println("");
}
}
static boolean isSafe(int x,int y, String word, String d)
{ int len=word.length();
int i,k,j;
if(d.equals("horizontal"))
for(i=y,k=0;i< (y+len);i++,k++)
{
if((grid[x][i]!='*')&& (grid[x][i]!=word.charAt(k)) && ((y+len) >15) )
return false;
}
if(d.equals("horizontalBack"))
for(i=y,k=0;i >(y-len);i--,k++)
{
if((grid[x][i]!='*')&& (grid[x][i]!=word.charAt(k)) && ((y-len) <0) )
return false;
}
if(d.equals("vertical"))
for(i=x,k=0;i <(x+len);i++,k++)
{
if((grid[i][y]!='*')&& (grid[i][y]!=word.charAt(k)) && ((x+len) >15) )
return false;
}
if(d.equals("verticalUp"))
for(i=x,k=0;i >(x+len);i++,k++)
{
if((grid[i][y]!='*')&& (grid[i][y]!=word.charAt(k)) && ((x-len) <0) )
return false;
}
if(d.equals("diagonal"))
{ k=0;i=y;j=x;
while((i< (y+len)) && (j< x+len)) {
if((grid[i][j]!='*')&& (grid[i][j]!=word.charAt(k)) && ((x+len) >15) && ((y+len)>15) )
{return false;}
i++;j++;k++;
}
}
if(d.equals("diagonalBack"))
{ k=0;i=y;j=x;
while((i> (y-len)) && (j>x-len)) {
if((grid[i][j]!='*')&& (grid[i][j]!=word.charAt(k)) && ((x-len)<0) && ((y-len)<0) )
{return false;}
i--;j--;k++;
}
}
return true;
}
static void place(int x, int y, String word, String d)
{ int len = word.length();
int i,k,j;
if(d.equals("horizontal"))
for( i=y, k=0;i< (y+len);i++,k++)
{
grid[x][i]=word.charAt(k);
}
if(d.equals("horizontalBack"))
for( i=y,k=0;i> (y-len);i--,k++)
{
grid[x][i]=word.charAt(k);
}
if(d.equals("vertical"))
for( i=x,k=0;i< (x+len);i++,k++)
{
grid[i][y]=word.charAt(k);
}
if(d.equals("verticalUp"))
for( i=x,k=0;i> (x-len);i--,k++)
{
grid[i][y]=word.charAt(k);
}
if(d.equals("diagonal"))
{ i=y;j=x;k=0;
while((i< (y+len)) && (j< (x+len)))
{
grid[i][j]=word.charAt(k);
i++;j++;k++;
}
}
if(d.equals("diagonalUp"))
{ i=y;j=x;k=0;
while((i> (y-len)) && (j> (x-len)))
{
grid[i][j]=word.charAt(k);
i--;j--;k++;
}
}
}
}
Instead of telling you how to fix your code, I'll help you understand the error.
Log
at puzzle.Puzzle.isSafe(Puzzle.java:97)
at puzzle.Puzzle.main(Puzzle.java:49)
Java Result: 1
Puzzle.java:97
if (grid[i][j]!='*' && grid[i][j]!=word.charAt(k) && (x+len)>15 && (y+len)>15)
Exception
Exception java.lang.ArrayIndexOutOfBoundsException means that either:
i >= grid.length
j >= grid[i].length
Detail
grid.length and grid[i].length are determined when the array is created:
grid = new char[15][15];
grid.length is 15
grid[i].length is 15
Moreover
Also, there is the string word:
for (i=y, k=0; i < (y+len); i++, k++)
word.charAt(k);
This will cause an issue too, when k at some point becomes k >= word.length() so that loop should be like this:
for (i=y, k=0; i < (y+len) && k < word.length(); i++, k++)
word.charAt(k);
I can see two bugs.
(1) The line that reads
for(i=x,k=0;i >(x+len);i++,k++)
should read
for(i=x,k=0;i >(x-len);i--,k++)
I think it's line 89.
(2) The bug that's causing this exception is the fact that every time you've got a whole lot of conditions separated by &&, the first one should be && and the subsequent ones should be ||.
For example,
if((grid[x][i]!='*')&& (grid[x][i]!=word.charAt(k)) && ((y+len) >15)) {
should read
if((grid[x][i]!='*')&& (grid[x][i]!=word.charAt(k)) || ((y+len) >15)) {
because you need to return that this square is an unsafe place to start the word if y + len > 15 regardless of what is found at each of the grid squares that you're checking. Similarly, with all the other conditions that look like this.
Please note the typo. varticalUp in the array declaration and verticalUp in the if condition. Although this is not the cause of the problem but its worth noting it.
I just quickly went through your code and it seems that the problem is in your variable len. See the statement int len=word.length(); on line 68. In fact it should be int len=word.length()-1; because the array index starts from 0. I have not tested it, but you can give it a try.

Code continues on for a long time - Recursion Issues - How can I fix?

I used the following code in my class with the intention of doing one round of recursion (specifically creating an object within an object of the same type). Well, that one round of recursion is now like 200 rounds of recursion... So that messes a lot of stuff up. The following code is where I call the recursion:
//Find Solute
try{if(iterations == 0){ //RECONDITION::: iterations is equal to zero at start of program and is static!
remaining = Whitespace.removePreceding(remaining);
String unused = remaining.substring(0);
InterpretInput solute = new InterpretInput(remaining);
solute.begin();
solute.fixSoluteAmount();
soluteAmount = solute.getSolventAmount();
isSolution = true;
++iterations;
}}catch(Exception ex){
}
finally{
System.out.println("Debugging point D");
findNumber();
fixSolventAmount();
fixSoluteAmount();
}
You'll find "Debugging point D" above, this is printed a ton of times so it apparently is going after the recursion with a bunch of objects, and the rest of the code is screwed up because of this. I just need someone experienced to point out how this is flawed as one iteration of recursion.
If you need the entire class, I'll also copy / paste that bellow, but it's almost 200 lines... so yeah... (I know I shouldn't make classes that long but this object needed a lot of stuff in it).
import java.util.ArrayList;
public class InterpretInput {
/**
* #param remaining - The string that was input, what's left to analyze
*/
/** Variables */
private String remaining; //The string input by the user, containing what's left to analyze
private static int iterations = 0;
//Solvent Info
private double solventAmount; //The amount of the solvent expressed as final in MOLES
private M solventAmountMeas; //The measurement used in solventAmount
private double solventConc; //The concentration of the solvent
private M solventConcMeas; //The measurement used in solventConc
private E[] solventCompound; //The compound of the solvent
private E[] water = {E.H, E.H, E.O};
//Solute Info
private double soluteAmount; //The amount of solute in the solution
//Type of Data
private boolean isElement = false; //Determines if the information input is only an element
private boolean hasAmount = false; //Determines if the information input has an amount of solvent
private boolean isSolution = false; //determines if the information input is a solution
private int identificationNumber;
/** Constructor */
public InterpretInput (String remain){
remaining = remain;
}
/** Mutator Methods
* #throws Exception */
public void begin() throws Exception{
//Find Measurement
FindMeasurements measureObject = new FindMeasurements(remaining);
while (measureObject.exists() == true){
measureObject.determineNumber();
measureObject.determineMeasurement();
double solventAmountTemp = measureObject.getAmount();
M solventAmountMeasTemp = measureObject.getMeasurement();
if( (solventAmountMeasTemp.getType()) == 3 ){
isSolution = true;
solventConc = solventAmountTemp;
solventConcMeas = solventAmountMeasTemp;
}else{
hasAmount = true;
solventAmount = solventAmountTemp;
solventAmountMeas = solventAmountMeasTemp;
}
remaining = measureObject.getRemaining();
}
//Find Compound
FindCompound comp = new FindCompound(remaining);
comp.getCompound();
solventCompound = comp.getValue();
remaining = comp.getRemaining();
if (solventCompound.length == 1)
isElement = true;
//Find Solute
try{if(iterations == 0){
remaining = Whitespace.removePreceding(remaining);
String unused = remaining.substring(0);
InterpretInput solute = new InterpretInput(remaining);
solute.begin();
solute.fixSoluteAmount();
soluteAmount = solute.getSolventAmount();
isSolution = true;
++iterations;
}}catch(Exception ex){
}
finally{
System.out.println("Debugging point D");
findNumber();
fixSolventAmount();
fixSoluteAmount();
}
}
public void fixSoluteAmount() throws Exception {
fixSolventAmount();
}
public void fixSolventAmount() throws Exception {
switch (identificationNumber){ //VIEW findNumber TO SEE INDEX OF THESE CASES
case 1:{
//In this situation, there would be nothing to change to begin with
break;
}
case 2:{
//In this situation, there would be nothing to change to begin with
break;
}
case 3:{
solventAmount *= solventAmountMeas.ofBase();
switch (solventAmountMeas.getType()){
case 1:{ //volume
if (!solventCompound.equals(water))
throw new Exception();
else{
solventAmount *= 1000; //Convert 1000g for every 1L
double molarMass = 0;
for (E e : solventCompound)
molarMass += e.atomicMass();
solventAmount /= molarMass; //convert to moles
}
}
case 2:{ //mass
double molarMass = 0;
for (E e : solventCompound)
molarMass += e.atomicMass();
solventAmount /= molarMass; //convert to moles
}
}
}
case 4:{
if(solventAmountMeas.equals(M.m)){
throw new Exception(); //I AM TAKING OUT THIS FEATURE, IT WILL BE TOO DIFFICULT TO IMPLEMENT
//BASICALLY, YOU CANNOT USE MOLALITY IN THIS PROGRAM ANYMORE
}
}
case 5:{
if(solventAmountMeas.equals(M.m))
throw new Exception(); //I AM TAKING OUT THIS FEATURE, IT WILL BE TOO DIFFICULT TO IMPLEMENT
//BASICALLY, YOU CANNOT USE MOLALITY IN THIS PROGRAM ANYMORE
double molarMass = 0;
for (E e : solventCompound)
molarMass += e.atomicMass();
solventAmount /= molarMass; //convert to moles
}
}
}
public void findNumber(){
/**
* 1 = Element
* 2 = Compound
* 3 = measured amount of compound
* 4 = specific concentration of solution
* 5 = Measured amount of specific concentration of solution
* */
if(isElement==true)
identificationNumber = 1;
else if(isSolution == false && hasAmount == false)
identificationNumber = 2;
else if(isSolution == false && hasAmount == true)
identificationNumber = 3;
else if(isSolution == true && hasAmount == false)
identificationNumber = 4;
else
identificationNumber = 5;
}
/** Accessory Methods */
public double getSolventAmount(){
return solventAmount;
}
public double getSoluteAmount(){
return soluteAmount;
}
public double getConcentration(){
return solventConc;
}
public E[] returnCompound(){
return solventCompound;
}
}
Your Begin function appears to call itself prior to incrementing the iterations variable. This will cause an infinite recursion. See my HERE notes in the code below.
//Find Solute
try{if(iterations == 0){
remaining = Whitespace.removePreceding(remaining);
String unused = remaining.substring(0);
InterpretInput solute = new InterpretInput(remaining);
// HERE - calls itself again, prior to incrementing
// iterations variable
solute.begin();
solute.fixSoluteAmount();
soluteAmount = solute.getSolventAmount();
isSolution = true;
// HERE - iterations is incremented, but too late
++iterations;
}}catch(Exception ex){
}
To resolve the recursion issue, you should increment iterations prior to the begin call.
The code here is pretty messy; it's a little difficult to figure out what the goal is. What are you trying to do with the string in InterpretInput, and why does it take such a complex solution (recursively built objects) as opposed to a loop or even just a recursive method?
Beyond that, however, it doesn't appear that there should be any way for your recursion to break. The only valid way for it to do so is if iterations != 0, which is never true because the ONLY time iterations is ever incremented is after the recursive call. Thus, I think the only reason the program terminates at all is that you overflow the stack, but the exception is caught by the empty catch block. Try printing something out in that block; I bet that's where the code is going even if you don't expect it to.

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