Why am I getting an java.lang.ArrayIndexOutOfBoundsException exception? - exception

I am writing the following code for a program that returns a boolean of whether or not three consecutive numbers in an array of ints add up to 7. I am getting the following exception instead of the output that I want: "java.lang.ArrayIndexOutOfBoundsException:5". Please can someone explain how I can fix this issue?
public static void main(String[] args) {
int[] numbers ={2,1,5,1,0};
System.out.println(luckysevens(numbers));
}
public static boolean luckysevens(int array[]) {
boolean isLucky= false;
for (int i=0; i<=array.length; i++){
if (array[i]+array[i+1]+array[i+2]==7){
isLucky=true;
}
else {
i++;
}
}
return isLucky;
}
}

Because you are accessing the array elements beyond its length.
For an array of length L, you can access elements in index range of 0 to L-1.
The above exception arises when you access elements beyond this index range.
You don't even need to increment in the else condition.
public static void main(String[] args) {
int[] numbers ={2,1,5,1,0};
System.out.println(luckysevens(numbers));
}
public static boolean luckysevens(int array[]) {
boolean isLucky= false;
for (int i=0; i<array.length-2; i++){
if (array[i]+array[i+1]+array[i+2]==7){
isLucky=true;
}
}
return isLucky;
}
}

You're comparing from 0 - 5 (i.e. 6 elements, but your array has only 5), so you're going out of the bounds.
All you have to do is to go from 0 - array.length-1; therefore have to change condition part i<=array.length; to like this i<(array.length-1);
public static void main(String[] args) {
int[] numbers ={2,1,5,1,0};
System.out.println(luckysevens(numbers));
}
public static boolean luckysevens(int array[]) {
boolean isLucky= false;
for (int i=0; i<(array.length-1); i++){
if (array[i]+array[i+1]+array[i+2]==7){
isLucky=true;
}
else {
i++;
}
}
return isLucky;
}

public static void main(String[] args)
{
int[] numbers ={2,1,5,1,0};
System.out.println(luckysevens(numbers));
}
public static boolean luckysevens(int array[])
{
boolean isLucky= false;
//Use array.length-2 in the code
for (int i=0; i<=array.length-2; i++)
{
if (array[i]+array[i+1]+array[i+2]==7)
{
isLucky=true;
return isLucky;
}
}
return isLucky;
}

Related

how to solve Arithmetic Exception in java

Below is my code :
public class prg34 {
public static void main(String[] args) {
int a=6;
for(int i=0;i<10;i++){
System.out.println(a/i);
}
}
}
Exception:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at run.prg34.main(prg34.java:8)
How to solve above Arithmetic Exception in java ?
You are trying to divide by zero in your first iteration. Change your first condition of i = 0, to something other than zero.
You cannot divide by 0, as I believe Java handles the division by zero error by a processor exception which triggers an interrupt.
Your first iteration is trying 6/0.
public static void main(String[] args) {
int a=6;
for(int i=1;i<10;i++){
System.out.println(a/i);
}
}
The first loop in your code gives an exception because you are trying to divide 6 by 0 i.e the ArithmeticException.
In order to fix this you must have to use try catch block. I've illustrated full code here. Please fix this.
public class prg34 {
public static void main(String[] args) {
int a=6;
try {
for(int i = 0; i < 10; i++) {
System.out.println(a/i);
}
}catch(ArithmeticException e) {
System.out.println("Division by zero is not possible. "+ e);
}
}
}

Getting a constructor error in processing

I'm playing with processing from some days, but I encountered an error that i didn't understand. I declared the class and the constructor with the proper arguments, maybe you can help me. This is the code:
Cell[][] grid;
int rnc = 5;
int side = 5;
void setup(){
size(rnc*side,rnc*side);
grid = new Cell[rnc][rnc];
for(int i = 0; i < rnc; i++){
for(int j = 0; j < rnc; j++){
grid[i][j] = new Cell(i,j);
rect(grid[i][j].row*side,grid[i][j].column*side,side,side);
}
}
}
void draw(){}
class Cell
{
boolean isChecked;
int row,column;
int side;
void Cell(int trow, int tcolumn){
row=trow;
column=tcolumn;
}
void toggleCheck(){
if(isChecked == true){
isChecked = false;
}else{
isChecked = true;
}
}
}
The error I got after i tried to ran the program is : The constructor sketch.Cell(int,int) is undefined.
Thank you in advance.
I'm assuming this is Java, although you haven't specified a language. If so, this is the problem:
void Cell(int trow, int tcolumn){
row=trow;
column=tcolumn;
}
That's not a constructor. That's a method called Cell, with a void return type. You meant:
Cell(int trow, int tcolumn){
row=trow;
column=tcolumn;
}
(Or possibly public Cell(...).)
At that point, you should be okay. Note that this would have been a compile-time error - not an execution-time error. Don't try to run your code until it compiles.
Also, it's not clear why you've made your constructor parameters trow and tcolumn - what's the t meant to be for? I'd also make your variables private, and final if possible, and simplify your toggleCheck method. For example:
public final class Cell {
private final int row, column;
private boolean checked;
// It's not clear what side was for
public Cell(int row, int column) {
this.row = row;
this.column = column;
}
public void toggleChecked() {
checked = !checked;
}
public boolean isChecked() {
return checked;
}
}

null pointer exception at run time

This is my first post here. I am trying to create a singly link list. I am using AtEnd and AtStart methods to insert values at the end or in the beginning of the list and using display method to print all the values. The insertion methods seems to be working fine (at least I think so) but whenever I call display method it shows only the first value and then there is a null pointer exception. For example when I run this code I see only 9 and then there is the NPE despite the fact that I have put a check on the display method for "not null".
class node {
private int data;
private node next;
node() {
}
node(int data) {
this.data = data;
this.next = null;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data=data;
}
public node getNext() {
return next;
}
public void setNext(node next) {
this.next = next;
}
}
public class list extends node {
node head;
list() {
}
public void AtStart(int val) {
node n = new node(val);
if (head == null) {
head=n;
} else {
n.setNext(head);
int temp = head.getData();
head.setData(val);
n.setData(temp);
//n = head;
}
}
public void AtEnd(int val) {
if (head == null) {
node n = new node(val);
head = n;
} else {
node t = head;
for(; t.getNext() != null; ) {
if(t.getNext() == null) {
t.setNext(new node (val));
}
t = t.getNext();
}
}
}
public void display() {
node t = head;
for(; t.getNext() == null;) {
if (t !=null) {
System.out.println(t.getData());
t = t.getNext();
}
}
}
}
public static void main(String args[]) {
list l = new list();
l.AtStart(16);
l.AtEnd(6);
l.AtEnd(36);
l.AtStart(9);
l.AtEnd(22);
l.display();
}
i dont get what your AtStart function does, it should be much simpler:
public void AtStart(int val){
if(head==null){
head=n;
}
else{
head.setnext(head);
head.setData(val);
}
}

How to know what text has been deleted from a JTextPane

I have added a document listener to a JTextPane. I want to know what text has been added or removed so I can take action if certain key words are entered. The insert part works just fine, but I do not know how to detect what text was deleted.
The insert works because the text is there and I can select it, but the delete has already removed the text so I get bad location exceptions sometimes.
I want to make reserved words that are not inside quotes bold so I need to know what has been removed, removing even one character (like a quote) could have a huge impact.
My code follows:
#Override
public void insertUpdate(DocumentEvent e)
{
Document doc = e.getDocument();
String i = "";
try
{
i = doc.getText(e.getOffset(), e.getLength());
}
catch(BadLocationException e1)
{
e1.printStackTrace();
}
System.out.println("INSERT:" + e + ":" + i);
}
#Override
public void removeUpdate(DocumentEvent e)
{
Document doc = e.getDocument();
String i = "";
try
{
i = doc.getText(e.getOffset(), e.getLength());
}
catch(BadLocationException e1)
{
e1.printStackTrace();
}
System.out.println("REMOVE:" + e + ":" + i);
}
This is strange that there is no simple way to get this information.
I've looked at the source code of Swing libraries for this. Of course - there is this information in DocumentEvent, which is of class AbstractDocument$DefaultDocumentEvent, which contains protected Vector<UndoableEdit> edits, which contains one element of type GapContent$RemoveUndo, which contains protected String string that is used only in this class (no other "package" classes get this) and this RemoveUndo class have no getter for this field.
Even toString didn't show it (because RemoveUndo hasn't overrided toString method):
[javax.swing.text.GapContent$RemoveUndo#6303ddfd hasBeenDone: true alive: true]
This is so strange for me that I belive that there is some other easy way to get the removed string and that I just don't know how to accomplish it.
One thing you can do is the most obvious:
final JTextArea textArea = new JTextArea();
textArea.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
previousText = textArea.getText();
}
});
textArea.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent e) {
if(previousText != null) {
String removedStr = previousText.substring(e.getOffset(), e.getOffset() + e.getLength());
System.out.println(removedStr);
}
}
#Override
public void insertUpdate(DocumentEvent e) {
}
#Override
public void changedUpdate(DocumentEvent e) {
}
});
where previousText is an instance variable.
or (the most nasty ever):
textArea.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent e) {
String removedString = getRemovedString(e);
System.out.println(removedString);
}
#Override
public void insertUpdate(DocumentEvent e) {
}
#Override
public void changedUpdate(DocumentEvent e) {
}
});
plus this method:
public static String getRemovedString(DocumentEvent e) {
try {
Field editsField = null;
Field[] fields = CompoundEdit.class.getDeclaredFields();
for(Field f : fields) {
if(f.getName().equals("edits")) {
editsField = f;
break;
}
}
editsField.setAccessible(true);
List edits = (List) editsField.get(e);
if(edits.size() != 1) {
return null;
}
Class<?> removeUndo = null;
for(Class<?> c : GapContent.class.getDeclaredClasses()) {
if(c.getSimpleName().equals("RemoveUndo")) {
removeUndo = c;
break;
}
}
Object removeUndoInstance = edits.get(0);
fields = removeUndo.getDeclaredFields();
Field stringField = null;
for(Field f : fields) {
if(f.getName().equals("string")) {
stringField = f;
break;
}
}
stringField.setAccessible(true);
return (String) stringField.get(removeUndoInstance);
}
catch(SecurityException e1) {
e1.printStackTrace();
}
catch(IllegalArgumentException e1) {
e1.printStackTrace();
}
catch(IllegalAccessException e1) {
e1.printStackTrace();
}
return null;
}
I had the same problem than you. And what Xeon explained help me a lot too. But after, i found a way to do that. In my case, i created a custom StyledDocument class that extends DefaultStyledDocument:
public class CustomStyledDocument extends DefaultStyledDocument
{
public CustomStyledDocument () {
super();
}
#Override
public void insertString(int offset, String string, AttributeSet as) throws BadLocationException {
super.insertString(offset, string, as);
}
#Override
public void remove(int offset, int i1) throws BadLocationException {
String previousText = getText(offset, i1);
super.remove(offset, i1);
}
}
So if you call getText method before you call super.remove(...), you will get the previous text.

How do I implement a fibonacci sequence in java using try/catch logic?

I know how to do it using simple recursion, but in order to complete this particular assignment I need to be able to accumulate on the stack and throw an exception that holds the answer in it.
So far I have:
public static int fibo(int index) {
int sum = 0;
try {
fibo_aux(index, 1, 1);
}
catch (IntegerException me) {
sum = me.getIntValue();
}
return sum;
}
fibo_aux is supposed to throw an IntegerException (which holds the value of the answer that is retireved via getIntValue) and accumulates the answer on the stack, but so far I can't figure it out. Can anyone help?
I don't know what your implementations for fibo_aux and IntegerException look like, but the following two implementations work with your existing code (I don't think there's anything wrong with the code you posted, so I assume something is awry in either fibo_aux or IntegerException). Maybe you'll find this helpful.
public static void fibo_aux(int index, int a, int b) throws IntegerException
{
if (--index > 0)
fibo_aux(index, b, a + b);
else
throw new IntegerException(a + b);
}
An implementation for IntegerException:
public class IntegerException extends Exception
{
private static final long serialVersionUID = -6795044518321782305L;
private Integer intValue;
public IntegerException(int i)
{
this.intValue = i;
}
public Integer getIntValue()
{
return intValue;
}
}
Here you go :
public class ExcFib {
/**
* #param args
*/
public static void main(String[] args) {
new ExcFib().fibo ( 10 );
}
class FiboException extends Throwable
{
public int n;
public FiboException(int n)
{
this.n = n;
}
private static final long serialVersionUID = 1L;
}
public void fibo(int idx) {
try {
fibo_aux(idx-1,1,1);
} catch (FiboException e) {
System.out.println ( "F(" + idx + ") = " + e.n );
}
}
private void fibo_aux(int i, int j, int k) throws FiboException {
if ( i < 1 )
{
throw new FiboException(k);
}
fibo_aux(i - 1, k, j + k );
}
}