Search Results

Search found 31 results on 2 pages for 'indexoutofboundsexception'.

Page 1/2 | 1 2  | Next Page >

  • I can't understand this issue java.lang.IndexOutOfBoundsException.

    - by praveenb
    I've strange issue, that My application is working fine on some devices, But its crashing one of the client device(on Galaxy Nexus 4.1.1 v) at app starting screen. I get this stack trace from ACRA report. java.lang.IndexOutOfBoundsException at android.graphics.Paint.getTextRunAdvances(Paint.java:1731) at android.graphics.Paint.getTextRunAdvances(Paint.java:1704) at android.text.MeasuredText.addStyleRun(MeasuredText.java:164) at android.text.MeasuredText.addStyleRun(MeasuredText.java:204) at android.text.StaticLayout.generate(StaticLayout.java:281) at android.text.DynamicLayout.reflow(DynamicLayout.java:284) at android.text.DynamicLayout.(DynamicLayout.java:170) at android.widget.TextView.makeSingleLayout(TextView.java:5843) at android.widget.TextView.makeNewLayout(TextView.java:5741) at android.widget.TextView.onMeasure(TextView.java:6098) at android.view.View.measure(View.java:15172) at android.widget.LinearLayout.measureVertical(LinearLayout.java:833) at android.widget.LinearLayout.onMeasure(LinearLayout.java:574) at android.view.View.measure(View.java:15172) at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:617) at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:399) at android.view.View.measure(View.java:15172) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814) at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) at android.view.View.measure(View.java:15172) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1390) at android.widget.LinearLayout.measureVertical(LinearLayout.java:681) at android.widget.LinearLayout.onMeasure(LinearLayout.java:574) at android.view.View.measure(View.java:15172) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814) at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2148) at android.view.View.measure(View.java:15172) at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1848) at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1100) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1273) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:998) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4212) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725) at android.view.Choreographer.doCallbacks(Choreographer.java:555) at android.view.Choreographer.doFrame(Choreographer.java:525) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711) at android.os.Handler.handleCallback(Handler.java:615) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4745) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) at dalvik.system.NativeStart.main(Native Method) Im seeing above stack trace. I'm unable to understand the issue. Please help me on tacking the issue. Thank you.

    Read the article

  • reference to IndexOutOfBoundsException is ambiguous

    - by senzacionale
    ERROR: reference to IndexOutOfBoundsException is ambiguous, both class com.sun.star.lang.IndexOutOfBoundsException in com.sun.star.lang and class java.lang.IndexOutOfBoundsException in java.lang match CODE: public void insertIntoCell(int CellX, int CellY, String theValue, XSpreadsheet TT1, String flag) throws IndexOutOfBoundsException { XCell oCell = null; oCell = TT1.getCellByPosition(CellX, CellY); if (flag.equals("V")) { oCell.setValue((new Float(theValue)).floatValue()); } else { if (theValue!=null && theValue.length()>0 && theValue.length()!=0) { oCell.setFormula("'"+(String)theValue.toString()); } else { oCell.setFormula((String)theValue.toString()); } } }

    Read the article

  • How do I solve this indexOutOfBoundsException in my server send/receive thread?

    - by Stefan Schouten
    I am creating a multiplayer game in Java with a server and multiple clients. Everything runs perfectly, until I press the Kick-button in the server to kick a client. Error at receive thread of server, after kicking the first person who joined out of three: java.lang.IndexOutOfBoundsException: Index: 2, Size: 2 at java.util.ArrayList.rangeCheck(ArrayList.java:604) at java.util.ArrayList.get(ArrayList.java:382) > at networktest.Server$3.run(Server.java:186) at java.lang.Thread.run(Thread.java:722) The pointed line is the ois = new ObjectInputStream where I send datatype. The server kicks the first person perfectly, but removes the second one in the list too, with an error of java.lang.ClassCastException. server receive: private static Thread receive = new Thread() { @Override public void run() { ObjectInputStream ois; while (true) { for (int i = 0; i < list_sockets.size(); i++) { try { ois = new ObjectInputStream(list_sockets.get(i).getInputStream()); int receive_state = (Integer) ois.readObject(); // receive state ois = new ObjectInputStream(list_sockets.get(i).getInputStream()); byte datatype = (byte) ois.readObject(); // receive datatype if(datatype == 2){ ois = new ObjectInputStream(list_sockets.get(i).getInputStream()); ChatLine chatLine = (ChatLine) ois.readObject(); // receive ChatLine } else if (datatype == 0){ ois = new ObjectInputStream(list_sockets.get(i).getInputStream()); DataPackage dp = (DataPackage) ois.readObject(); // receive dp list_data.set(i, dp); } if (receive_state == 1) // Client Disconnected by User { disconnectClient(i); i--; } } catch (Exception ex) // Client Disconnected (Client Didn't Notify Server About Disconnecting) { System.err.println("Error @ receive:"); ex.printStackTrace(); disconnectClient(i); i--; } } try { this.sleep(3); } catch (InterruptedException ex) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } } } }; user send: Thread send = new Thread() { public void run() { ObjectOutputStream oos; byte datatype = 0; while (connected){ if (socket != null){ try { DataPackage dp = new DataPackage(); dp.x = Client.player.x; dp.y = Client.player.y; dp.username = username; dp.charType = charType; dp.walking = (byte)Client.player.walking; if (Client.outputChatLine.line != null) datatype = 2; else { datatype = 0; } oos = new ObjectOutputStream(socket.getOutputStream()); oos.writeObject(Integer.valueOf(Client.this.state)); // send state oos = new ObjectOutputStream(socket.getOutputStream()); oos.writeObject(Byte.valueOf(datatype)); // send datatype if (datatype == 2) { oos.reset(); oos.writeObject(Client.outputChatLine); Client.outputChatLine = new ChatLine(); } else { oos = new ObjectOutputStream(socket.getOutputStream()); oos.writeObject(dp); } if (Client.this.state == 1) { connected = false; socket = null; JOptionPane.showMessageDialog(null, "Client Disconnected", "Info", 1); System.exit(0); } } catch (Exception ex){} } try { this.sleep(2); } catch (InterruptedException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } } } }; disconnect client method: public static void disconnectClient(int index) { try { list_clients_model.removeElementAt(index); list_client_states.remove(index); list_data.remove(index); list_sockets.remove(index); } catch (Exception ex) {} } Does anyone know how to solve this?

    Read the article

  • Sorting ArrayList - IndexOutOfBoundsException -Java

    - by FILIaS
    I'm trying to sort an ArrayList with strings(PlayersNames) and imageIcons(PlayersIcons) based on the values i store in an other arrayList with integers(results). As you can see i get an indexOutOfBoundsException but i cant understand why. Maybe the earling of the morning makes me not to see plain things. ArrayList<String> PlayersNames=new ArrayList<String>; ArrayList<ImageIcon> PlayersIcons=new ArrayList<ImageIcons>; public void sortPlayers(ArrayList<Integer> results){ String tmp; ImageIcon tmp2; for (int i=0; i<PlayersNames.size(); i++) { for (int j=PlayersNames.size(); j>i; j--) { if (results.get(i) < results.get(i+1) ) { //IndexOutOfBoundsException! tmp=PlayersNames.get(i+1); PlayersNames.set(i+1,PlayersNames.get(i)); PlayersNames.set(i,tmp); tmp2=PlayersIcons.get(i+1); PlayersIcons.set(i+1,PlayersIcons.get(i)); PlayersIcons.set(i,tmp2); } } } }

    Read the article

  • Java ArrayList<Double> IndexOutOfBoundsException Problem

    - by Sebastian Bechtel
    Hello, I've got a Problem with ArrayList. I need it to store a result. Because I want to start with element n I tryed to give the ArrayList a capacity with ensureCapacity(n+1) to use set(n,x) but I get an IndexOutOfBoundsException. I tryed to store n add(x) before the use of set and this works. So I'd like to know why it doesn't work on my way and how to solve this because put n times a add(x) isn't a good style ;-) Best regards, Sebastian

    Read the article

  • IndexOutOfBoundsException when updating a contact in contact list - Blackberry

    - by Taha
    Software and Simulator version i am using Blackberry Smartphone simulator: 2.13.0.65 Blackberry software version 5.0.0_5.0.0.14 I am looking at modifying contacts. Below is the code snippet i am using. I am getting a IndexOutOfBounds Exception at line String wtel = blackBerryContact.getString(BlackBerryContact.TEL, supportedAttributes[i]); Can someone advise what is going wrong here. Following is the code snippet ..... // Load the addressbook and let the user choose from list of contact BlackBerryContactList contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST,PIM.READ_WRITE); PIMItem pimItem = contactList.choose(); BlackBerryContact blackBerryContact = (BlackBerryContact)pimItem; PIMList pimList = blackBerryContact.getPIMList(); // get the supported attributes for Contact.TEL int[] supportedAttributes = pimList.getSupportedAttributes(Contact.TEL); Dialog.alert("Supported Attributes "+supportedAttributes.length); // gives me 8 for (int i=0; i < supportedAttributes.length;i++){ if(blackBerryContact.ATTR_WORK == supportedAttributes[i]){ Dialog.alert("updating Work"); // This alert is shown Dialog.alert("is supported "+ pimList.isSupportedAttribute(BlackBerryContact.TEL, supportedAttributes[i])+" "+pimList.getAttributeLabel(supportedAttributes[i])); // shows true and work String wtel = blackBerryContact.getString(BlackBerryContact.TEL, supportedAttributes[i]); // I get a IndexOutOfBounds Exception here if(wtel != ""){ pimItem.removeValue(BlackBerryContact.TEL, supportedAttributes[i]); } pimItem.addString( Contact.TEL, BlackBerryContact.ATTR_WORK, number); // passing the number that has to be updated if(pimItem.isModified()) { pimItem.commit(); Dialog.alert("Updated Work Number"); } } } ..... I want to update all the supported attributes for Contact.TEL field http://www.blackberry.com/developers/docs/5.0.0api/net/rim/blackberry/api/pdap/BlackBerryContact.html Field Values Per Field Supported Attributes ----------------------------------------------------------------------------- Contact.TEL 8 Contact.ATTR_WORK, Contact.ATTR_HOME, Contact.ATTR_MOBILE, Contact.ATTR_PAGER, Contact.ATTR_FAX, Contact.ATTR_OTHER, Contact.ATTR_HOME2, Contact.ATTR_WORK2

    Read the article

  • Java IndexOutOfBoundsException

    - by Meko
    Hi all ... I made an little shoot em up game..It works normal but I want also implement if fires intersects they will disappear. I have two list for Player bullets and for computer bullets ...But if I have more bullets from computer or reverse .Here my loop for (int i = 0; i < cb.size(); i++) { for (int j = 0; j < b.size(); j++) { if (b.get(j).rect.intersects(cb.get(i).rect)) { cb.remove(i); b.remove(j); continue; } if (cb.get(i).rect.intersects(b.get(j).rect)) { b.remove(j); cb.remove(i); continue; } } }

    Read the article

  • Why am I getting an IndexOutOfBoundsException here?

    - by Berzerker
    I'm getting an index out of bounds exception thrown and I don't know why, within my replaceValue method below. [null, (10,4), (52,3), (39,9), (78,7), (63,8), (42,2), (50,411)] replacement value test:411 size=7 [null, (10,4), (52,3), (39,9), (78,7), (63,8), (42,2), (50,101)] removal test of :(10,4) [null, (39,9), (52,3), (42,2), (78,7), (63,8), (50,101)] size=6 I try to replace the value again here and get an error... package heappriorityqueue; import java.util.*; public class HeapPriorityQueue<K,V> { protected ArrayList<Entry<K,V>> heap; protected Comparator<K> comp; int size = 0; protected static class MyEntry<K,V> implements Entry<K,V> { protected K key; protected V value; protected int loc; public MyEntry(K k, V v,int i) {key = k; value = v;loc =i;} public K getKey() {return key;} public V getValue() {return value;} public int getLoc(){return loc;} public String toString() {return "(" + key + "," + value + ")";} void setKey(K k1) {key = k1;} void setValue(V v1) {value = v1;} public void setLoc(int i) {loc = i;} } public HeapPriorityQueue() { heap = new ArrayList<Entry<K,V>>(); heap.add(0,null); comp = new DefaultComparator<K>(); } public HeapPriorityQueue(Comparator<K> c) { heap = new ArrayList<Entry<K,V>>(); heap.add(0,null); comp = c; } public int size() {return size;} public boolean isEmpty() {return size == 0; } public Entry<K,V> min() throws EmptyPriorityQueueException { if (isEmpty()) throw new EmptyPriorityQueueException("Priority Queue is Empty"); return heap.get(1); } public Entry<K,V> insert(K k, V v) { size++; Entry<K,V> entry = new MyEntry<K,V>(k,v,size); heap.add(size,entry); upHeap(size); return entry; } public Entry<K,V> removeMin() throws EmptyPriorityQueueException { if (isEmpty()) throw new EmptyPriorityQueueException("Priority Queue is Empty"); if (size == 1) return heap.remove(1); Entry<K,V> min = heap.get(1); heap.set(1, heap.remove(size)); size--; downHeap(1); return min; } public V replaceValue(Entry<K,V> e, V v) throws InvalidEntryException, EmptyPriorityQueueException { // replace the value field of entry e in the priority // queue with the given value v, and return the old value This is where I am getting the IndexOutOfBounds exception, on heap.get(i); if (isEmpty()){ throw new EmptyPriorityQueueException("Priority Queue is Empty."); } checkEntry(e); int i = e.getLoc(); Entry<K,V> entry=heap.get(((i))); V oldVal = entry.getValue(); K key=entry.getKey(); Entry<K,V> insert = new MyEntry<K,V>(key,v,i); heap.set(i, insert); return oldVal; } public K replaceKey(Entry<K,V> e, K k) throws InvalidEntryException, EmptyPriorityQueueException, InvalidKeyException { // replace the key field of entry e in the priority // queue with the given key k, and return the old key if (isEmpty()){ throw new EmptyPriorityQueueException("Priority Queue is Empty."); } checkKey(k); checkEntry(e); K oldKey=e.getKey(); int i = e.getLoc(); Entry<K,V> entry = new MyEntry<K,V>(k,e.getValue(),i); heap.set(i,entry); downHeap(i); upHeap(i); return oldKey; } public Entry<K,V> remove(Entry<K,V> e) throws InvalidEntryException, EmptyPriorityQueueException{ // remove entry e from priority queue and return it if (isEmpty()){ throw new EmptyPriorityQueueException("Priority Queue is Empty."); } MyEntry<K,V> entry = checkEntry(e); if (size==1){ return heap.remove(size--); } int i = e.getLoc(); heap.set(i, heap.remove(size--)); downHeap(i); return entry; } protected void upHeap(int i) { while (i > 1) { if (comp.compare(heap.get(i/2).getKey(), heap.get(i).getKey()) <= 0) break; swap(i/2,i); i = i/2; } } protected void downHeap(int i) { int smallerChild; while (size >= 2*i) { smallerChild = 2*i; if ( size >= 2*i + 1) if (comp.compare(heap.get(2*i + 1).getKey(), heap.get(2*i).getKey()) < 0) smallerChild = 2*i+1; if (comp.compare(heap.get(i).getKey(), heap.get(smallerChild).getKey()) <= 0) break; swap(i, smallerChild); i = smallerChild; } } protected void swap(int j, int i) { heap.get(j).setLoc(i); heap.get(i).setLoc(j); Entry<K,V> temp; temp = heap.get(j); heap.set(j, heap.get(i)); heap.set(i, temp); } public String toString() { return heap.toString(); } protected MyEntry<K,V> checkEntry(Entry<K,V> ent) throws InvalidEntryException { if(ent == null || !(ent instanceof MyEntry)) throw new InvalidEntryException("Invalid entry."); return (MyEntry)ent; } protected void checkKey(K key) throws InvalidKeyException{ try{comp.compare(key,key);} catch(Exception e){throw new InvalidKeyException("Invalid key.");} } }

    Read the article

  • How to fix this IndexOutOfBoundsException

    - by Rida
    My program runs fine, but there is a little problem. When I add new tracks previously existing file to the ListBox, the program experiences an error. The code seems unwilling to do looping in a new file which was added in a different time. Please help me. Thanks .... public partial class Form1 : Form { //... string[] files, paths; private void button1_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { files = openFileDialog1.SafeFileNames; paths = openFileDialog1.FileNames; for (int i = 0; i < files.Length - 1; i++) { listBox1.Items.Add(files[i]); } } } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { axWindowsMediaPlayer1.URL = paths[listBox1.SelectedIndex]; } }

    Read the article

  • Find all substrings of a string - StringIndexOutOfBoundsException

    - by nazar_art
    I created class Word. Word has a constructor that takes a string argument and one method getSubstrings which returns a String containing all substring of word, sorted by length. For example, if the user provides the input "rum", the method returns a string that will print like this: r u m ru um rum I want to concatenate the substrings in a String, separating them with a newline ("\n"). Then return the string. Code: public class Word { String word; public Word(String word) { this.word = word; } /** * Gets all the substrings of this Word. * @return all substrings of this Word separated by newline */ public String getSubstrings() { String str = ""; int i, j; for (i = 0; i < word.length(); i++) { for (j = 0; j < word.length(); j++) { str = word.substring(i, i + j); str += "\n"; } } return str; } But it throws exception: java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.substring(String.java:1911) I stuck at this point. Maybe, you have other suggestions according this method signature public String getSubstrings(). How to solve this issue?

    Read the article

  • why toString method does not work here??

    - by user329820
    Hi this is my whole class ,I have added number 2 to the doubly linked list and then I want it to be be print in the concole but it will show this "datastructureproject.Node@f62373" thanks! package datastructureproject; public class DoublyLinkedList { private Node head = new Node(0); private Node tail = new Node(0); private int length = 0; public DoublyLinkedList() { head.setPrev(null); head.setNext(tail); tail.setPrev(head); tail.setNext(null); } public void add(int index, int value) throws IndexOutOfBoundsException { Node cursor = get(index); Node temp = new Node(value); temp.setPrev(cursor); temp.setNext(cursor.getNext()); cursor.getNext().setPrev(temp); cursor.setNext(temp); length++; } private Node get(int index) throws IndexOutOfBoundsException { if (index < 0 || index > length) { throw new IndexOutOfBoundsException(); } else { Node cursor = head; for (int i = 0; i < index; i++) { cursor = cursor.getNext(); } return cursor; } } public long size() { return length; } public boolean isEmpty() { return length == 0; } @Override public String toString() { StringBuffer result = new StringBuffer(); result.append("(head) - "); Node temp = head; while (temp.getNext() != tail) { temp = temp.getNext(); result.append(temp.getValue() + " - "); } result.append("(tail)"); return result.toString(); } public static void main(String[] args){ DoublyLinkedList list = new DoublyLinkedList(); list.add(0,2 ); System.out.println(list.get(0).toString()); } }

    Read the article

  • why it throws index out of bounds exception??

    - by Johanna
    Hi I want to use merge sort for sorting my doubly linked list.I have created 3 classes(Node,DoublyLinkedList,MergeSort) but it will throw this exception for these lines: 1.in the getNodes method of DoublyLinkedList---> throw new IndexOutOfBoundsException(); 2.in the add method of DoublyLinkedList-----> Node cursor = getNodes(index); 3.in the sort method of MergeSort class------> listTwo.add(x,localDoublyLinkedList.getValue(x)); 4.in the main method of DoublyLinkedList----->merge.sort(); this is my Merge class:(I put the whole code for this class for beter understanding) public class MergeSort { private DoublyLinkedList localDoublyLinkedList; public MergeSort(DoublyLinkedList list) { localDoublyLinkedList = list; } public void sort() { if (localDoublyLinkedList.size() <= 1) { return; } DoublyLinkedList listOne = new DoublyLinkedList(); DoublyLinkedList listTwo = new DoublyLinkedList(); for (int x = 0; x < (localDoublyLinkedList.size() / 2); x++) { listOne.add(x, localDoublyLinkedList.getValue(x)); } for (int x = (localDoublyLinkedList.size() / 2) + 1; x < localDoublyLinkedList.size(); x++) { listTwo.add(x, localDoublyLinkedList.getValue(x)); } //Split the DoublyLinkedList again MergeSort sort1 = new MergeSort(listOne); MergeSort sort2 = new MergeSort(listTwo); sort1.sort(); sort2.sort(); merge(listOne, listTwo); } public void merge(DoublyLinkedList a, DoublyLinkedList b) { int x = 0; int y = 0; int z = 0; while (x < a.size() && y < b.size()) { if (a.getValue(x) < b.getValue(y)) { localDoublyLinkedList.add(z, a.getValue(x)); x++; } else { localDoublyLinkedList.add(z, b.getValue(y)); y++; } z++; } //copy remaining elements to the tail of a[]; for (int i = x; i < a.size(); i++) { localDoublyLinkedList.add(z, a.getValue(i)); z++; } for (int i = y; i < b.size(); i++) { localDoublyLinkedList.add(z, b.getValue(i)); z++; } } } and just a part of my DoublyLinkedList: private Node getNodes(int index) throws IndexOutOfBoundsException { if (index < 0 || index > length) { throw new IndexOutOfBoundsException(); } else { Node cursor = head; for (int i = 0; i < index; i++) { cursor = cursor.getNext(); } return cursor; } } public void add(int index, int value) throws IndexOutOfBoundsException { Node cursor = getNodes(index); Node temp = new Node(value); temp.setPrev(cursor); temp.setNext(cursor.getNext()); cursor.getNext().setPrev(temp); cursor.setNext(temp); length++; } public static void main(String[] args) { int i = 0; i = getRandomNumber(10, 10000); DoublyLinkedList list = new DoublyLinkedList(); for (int j = 0; j < i; j++) { list.add(j, getRandomNumber(10, 10000)); MergeSort merge = new MergeSort(list); merge.sort(); System.out.println(list.getValue(j)); } } PLEASE help me thanks alot.

    Read the article

  • exporting non_public type through public API

    - by user329820
    Hi I have written this code in Netbeans but it will show this warning for the name of this method ,would you please help me for what it shows this warning? thanks public Node returnNode(int index) throws IndexOutOfBoundsException { if (index < 0 || index > size) { throw new IndexOutOfBoundsException(); } else { for (int i = 0; i < index; i++) { pointer = pointer.getNext(); } } return pointer; }

    Read the article

  • Index out of bounds, Java bukkit plugin

    - by Robby Duke
    I'm getting index out of bounds errors in my Bukkit plugin, and it's really beginning to piss me off... I for the life of me can't figure this issue out! Caused by: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 This is where I believe the code to be erroring... for(int i = 0; i <= staffOnline.size(); i++) { if(i == staffOnline.size()) { staffList = staffList + staffOnline.get(i); } else { staffList = staffList + staffOnline.get(i) + ", "; } }

    Read the article

  • How to assert that a certain exception is thrown in jUnit4.5 tests

    - by SCdF
    How can use jUnit4.5 idiomatically to test that come code throws an exception? While I can certainly do something like this: @Test public void testFooThrowsIndexOutOfBoundsException() { boolean thrown = false; try { foo.doStuff(); } catch (IndexOutOfBoundsException e) { thrown = true; } assertTrue(thrown); } I recall that there is an annotation or an Assert.xyz or something that is far less cludgy and far more in-the-spirit of jUnit for these sorts of situations.

    Read the article

  • how to solve ArrayList outOfBoundsExeption?

    - by iQue
    Im getting: 09-02 17:15:39.140: E/AndroidRuntime(533): java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1 09-02 17:15:39.140: E/AndroidRuntime(533): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251) when Im killing enemies using this method: private void checkCollision() { Rect h1 = happy.getBounds(); for (int i = 0; i < enemies.size(); i++) { for (int j = 0; j < bullets.size(); j++) { Rect b1 = bullets.get(j).getBounds(); Rect e1 = enemies.get(i).getBounds(); if (b1.intersect(e1)) { enemies.get(i).damageHP(5); bullets.remove(j); Log.d("TAG", "HERE: LOLTHEYTOUCHED"); } if (h1.intersect(e1)){ happy.damageHP(5); } if(enemies.get(i).getHP() <= 0){ enemies.remove(i); } if(happy.getHP() <= 0){ //end-screen !!!!!!! } } } } using this ArrayList: private ArrayList<Enemy> enemies = new ArrayList<Enemy>(); and adding to array like this: public void createEnemies() { Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.female); if (enemyCounter < 24) { enemies.add(new Enemy(bmp, this, controls)); } enemyCounter++; } I dont really understand what the problem is, Ive been looking around for a while but cant really find anything that helps me. If you know or if you can link me someplace where they have a solution for a similar problem Ill be a very happy camper! Thanks for ur time.

    Read the article

  • How do I implement a remove by index method for a singly linked list in Java?

    - by Lars Flyger
    Hi, I'm a student in a programming class, and I need some help with this code I've written. So far I've written an entire linked list class (seen below), yet for some reason the "removeByIndex" method won't work. I can't seem to figure out why, the logic seems sound to me. Is there some problem I don't know about? public class List<T> { //private sub-class Link private class Link { private T value; private Link next; //constructors of Link: public Link (T val) { this.value = val; this.next = null; } public Link (T val, Link next) { this.value = val; this.next = next; } @SuppressWarnings("unused") public T getValue() { return value; } } private static final Exception NoSuchElementException = null; private static final Exception IndexOutOfBoundsException = null; private Link chain = null; //constructors of List: public List() { this.chain = null; } //methods of List: /** * Preconditions: none * Postconditions: returns true if list is empty */ public boolean isEmpty() { return this.chain == null; } /** * Preconditions: none * Postconditions: A new Link is added via add-aux * @param element */ public void add(T element) { this.add_aux(element, this.chain); } /** * Preconditions: none * Postconditions: A new Link is added to the current chain * @param element * @param chain */ private void add_aux(T element, Link chain) { if (chain == null) { //if chain is null set chain to a new Link with a value of //element this.chain = new Link(element); } else if (chain.next != null) { //if chain.next is not null, go to next item in chain and //try //to add element add_aux(element, chain.next); } else { //if chain.next is null, set chain.next equal to a new Link //with value of element. chain.next = new Link(element); } } /** * Preconditions: none * Postconditions: returns the link at the defined index via nthlink_aux * @param index * @return */ private Link nthLink (int index) { return nthLink_aux(index, this.chain); } /** * Preconditions: none * Postconditions: returns the link at the defined index in the specified *chain * @param i * @param c * @return */ private Link nthLink_aux (int i, Link c) { if (i == 0) { return c; } else return nthLink_aux(i-1, c.next); } /** * Preconditions: the specified element is present in the list * Postconditions: the specified element is removed from the list * @param element * @throws Exception */ public void removeElement(T element) throws Exception { if (chain == null) { throw NoSuchElementException; } //while chain's next is not null and the value of chain.next is not //equal to element, //set chain equal to chain.next //use this iteration to go through the linked list. else while ((chain.next != null) && !(chain.next.value.equals(element))){ Link testlink = chain.next; if (testlink.next.value.equals(element)) { //if chain.next is equal to element, bypass the //element. chain.next.next = chain.next.next.next; } else if (testlink.next == null) { throw NoSuchElementException; } } } /** * Preconditions: none * Postsconditions: the Link at the specified index is removed * @param index * @throws Exception */ public void removeByIndex(int index) throws Exception { if (index == 0) { //if index is 0, set chain equal to chain.next chain = chain.next; } else if (index > 0) { Link target = nthLink(index); while (target != null) { if (target.next != null) { target = target.next; } //if target.next is null, set target to null else { target = null; } } return; } else throw IndexOutOfBoundsException; } /** * Preconditions: none * Postconditions: the specified link's value is printed * @param link */ public void printLink (Link link) { if(link != null) { System.out.println(link.value.toString()); } } /** * Preconditions: none * Postconditions: all of the links' values in the list are printed. */ public void print() { //copy chain to a new variable Link head = this.chain; //while head is not null while (!(head == null)) { //print the current link this.printLink(head); //set head equal to the next link head = head.next; } } /** * Preconditions: none * Postconditions: The chain is set to null */ public void clear() { this.chain = null; } /** * Preconditions: none * Postconditions: Places the defined link at the defined index of the list * @param index * @param val */ public void splice(int index, T val) { //create a new link with value equal to val Link spliced = new Link(val); if (index <= 0) { //copy chain Link copy = chain; //set chain equal to spliced chain = spliced; //set chain.next equal to copy chain.next = copy; } else if (index > 0) { //create a target link equal to the link before the index Link target = nthLink(index - 1); //set the target's next equal to a new link with a next //equal to the target's old next target.next = new Link(val, target.next); } } /** * Preconditions: none * Postconditions: Check to see if element is in the list, returns true * if it is and false if it isn't * @param element * @return */ public boolean Search(T element) { if (chain == null) { //return false if chain is null return false; } //while chain's next is not null and the value of chain.next is not //equal to element, //set chain equal to chain.next //use this iteration to go through the linked list. else while ((chain.next != null) && !(chain.next.value.equals(element))) { Link testlink = chain.next; if (testlink.next.value.equals(element)) { //if chain.next is equal to element, return true return true; } else if (testlink.next == null) { return false; } } return false; } /** * Preconditions: none * Postconditions: order of the links in the list is reversed. */ public void reverse() { //copy chain Link current = chain; //set chain equal to null chain = null; while (current != null) { Link save = current; current = current.next; save.next = chain; chain = save; } } }'

    Read the article

  • Throwing exceptions as well as catching exceptions?

    - by Eric S
    I was wondering how Java takes the following scenario public static void main(String[] args) throws IndexOutOfBoundsException, CoordinateException, MissionException, SQLException, ParserConfigurationException { try { doSomething(); } catch (Exception e) { e.printStackTrace(); } } In the above code, I am declaring the main function to throw many different exceptions, but inside the function, I am catching the generic Exception. I am wondering how java takes this internally? I.e., say doSomething() throws an IndexOutOfBounds exception, will the e.printStackTrace() get called in the last catch (Exception e) {...} block? I know if an exception not declared in the throws area of the function gets thrown, the try/catch will handle it, but what about exceptions mentioned in the declaration?

    Read the article

  • Proper snowball analyzer configuration when using Grails Searchable Plugin

    - by Wirsbro
    To improve stemming we want to switch from the default analyzer to snowball, however, having a lot of difficulty with the proper settings and would appreciate any help. In Environment: - Sun's Java 1.6.16 - Grails 1.2.2 - Searchable Plug-In 0.5.5 Config.groovy: Have tried both settings: compassSettings = ['compass.engine.analyzer.stemmed.type': 'snowball', 'compass.engine.analyzer.stemmed.name': 'English'] compassSettings = ['compass.engine.analyzer.snowball.type': 'snowball', 'compass.engine.analyzer.snowball.name': 'English', 'compass.engine.analyzer.search.type': 'snowball', 'compass.engine.analyzer.search.name': 'English'] Search.groovy - The Invocation: def searchResult = searchableService.search(params.q, withHighlighter: { highlighter, index, sr if (!sr.highlights) { sr.highlights = [] } try { sr.highlights[index] = highlighter.fragments("content")[0..2].join(" ") } catch (IndexOutOfBoundsException ex) { sr.highlights[index] = highlighter.fragment("content") } }) def suggestion = searchableService.suggestQuery(params.q) if (suggestion != params.q) { searchResult.suggestedQuery = suggestion }

    Read the article

  • Another ArrayIndexOutOfBoundsException in ListView

    - by synic
    This one is different than the other one I posted. Any ideas? java.lang.IndexOutOfBoundsException: Invalid location 14, size is 1 at java.util.ArrayList.get(ArrayList.java:341) at android.widget.HeaderViewListAdapter.getView(HeaderViewListAdapter.java:188) at android.widget.AbsListView.obtainView(AbsListView.java:1256) at android.widget.ListView.makeAndAddView(ListView.java:1668) at android.widget.ListView.fillUp(ListView.java:667) at android.widget.ListView.fillGap(ListView.java:613) at android.widget.AbsListView.trackMotionScroll(AbsListView.java:2531) at android.widget.AbsListView$FlingRunnable.run(AbsListView.java:2353) at android.os.Handler.handleCallback(Handler.java:587) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:123) at android.app.ActivityThread.main(ActivityThread.java:4595) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:521) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) at dalvik.system.NativeStart.main(Native Method)

    Read the article

  • Prim's MST algorithm implementation with Java

    - by user1290164
    I'm trying to write a program that'll find the MST of a given undirected weighted graph with Kruskal's and Prim's algorithms. I've successfully implemented Kruskal's algorithm in the program, but I'm having trouble with Prim's. To be more precise, I can't figure out how to actually build the Prim function so that it'll iterate through all the vertices in the graph. I'm getting some IndexOutOfBoundsException errors during program execution. I'm not sure how much information is needed for others to get the idea of what I have done so far, but hopefully there won't be too much useless information. This is what I have so far: I have a Graph, Edge and a Vertex class. Vertex class mostly just an information storage that contains the name (number) of the vertex. Edge class can create a new Edge that has gets parameters (Vertex start, Vertex end, int edgeWeight). The class has methods to return the usual info like start vertex, end vertex and the weight. Graph class reads data from a text file and adds new Edges to an ArrayList. The text file also tells us how many vertecis the graph has, and that gets stored too. In the Graph class, I have a Prim() -method that's supposed to calculate the MST: public ArrayList<Edge> Prim(Graph G) { ArrayList<Edge> edges = G.graph; // Copies the ArrayList with all edges in it. ArrayList<Edge> MST = new ArrayList<Edge>(); Random rnd = new Random(); Vertex startingVertex = edges.get(rnd.nextInt(G.returnVertexCount())).returnStartingVertex(); // This is just to randomize the starting vertex. // This is supposed to be the main loop to find the MST, but this is probably horribly wrong.. while (MST.size() < returnVertexCount()) { Edge e = findClosestNeighbour(startingVertex); MST.add(e); visited.add(e.returnStartingVertex()); visited.add(e.returnEndingVertex()); edges.remove(e); } return MST; } The method findClosesNeighbour() looks like this: public Edge findClosestNeighbour(Vertex v) { ArrayList<Edge> neighbours = new ArrayList<Edge>(); ArrayList<Edge> edges = graph; for (int i = 0; i < edges.size() -1; ++i) { if (edges.get(i).endPoint() == s.returnVertexID() && !visited(edges.get(i).returnEndingVertex())) { neighbours.add(edges.get(i)); } } return neighbours.get(0); // This is the minimum weight edge in the list. } ArrayList<Vertex> visited and ArrayList<Edges> graph get constructed when creating a new graph. Visited() -method is simply a boolean check to see if ArrayList visited contains the Vertex we're thinking about moving to. I tested the findClosestNeighbour() independantly and it seemed to be working but if someone finds something wrong with it then that feedback is welcome also. Mainly though as I mentioned my problem is with actually building the main loop in the Prim() -method, and if there's any additional info needed I'm happy to provide it. Thank you. Edit: To clarify what my train of thought with the Prim() method is. What I want to do is first randomize the starting point in the graph. After that, I will find the closest neighbor to that starting point. Then we'll add the edge connecting those two points to the MST, and also add the vertices to the visited list for checking later, so that we won't form any loops in the graph. Here's the error that gets thrown: Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.rangeCheck(Unknown Source) at java.util.ArrayList.get(Unknown Source) at Graph.findClosestNeighbour(graph.java:203) at Graph.Prim(graph.java:179) at MST.main(MST.java:49) Line 203: return neighbour.get(0); in findClosestNeighbour() Line 179: Edge e = findClosestNeighbour(startingVertex); in Prim()

    Read the article

  • How to make a mutable ItemizedOverlay

    - by Hamy
    Hey all, I would like to make a Google map overlay with changable pins. An easy way to visualize this would be to think of a near real time overlay, where the pins are constantly changing location. However, I can't seem to think of a safe way to do this with the ItemizedOverlay. The problem seems to be the call to populate - If size() is called by some maps thread, and then my data changes, then the result when the maps call accesses getItem() can be an IndexOutOfBoundsException. Can anyone think of a better solution than overloading populate and wrapping super.populate in a synchronized block? Perhaps I could get better luck using a normal Overlay? The Itemized one seems to exist to manage the data for you, perhaps I am making a fundamental mistake by using it? Thanks for any help, my brain is hurting! Hamy

    Read the article

  • Saving a movie generated with Jython/JES on local disk

    - by Golgauth
    I made an autogenerated movie clip using JES (Jython Environment for Students). I can play it without any problem using playMovie(), but I can't figure out how to have it saved physically on disk. The full script is located here. ... movie = synthesizeFrameAndCreateMovie("D:\\FOLDER") print movie writeQuicktime(movie,"D:\\FOLDER\\movie.mov", 30) [LINE 35] #playMovie(movie) I get this error when calling the function writeQuicktime(): >>> ======= Loading Progam ======= Movie, frames: 60 The error was: Index: 0, Size: 0 I wasn't able to do what you wanted. The error java.lang.IndexOutOfBoundsException has occured Please check line 35 Note : I also tried the function writeAVI(), with the exact same result. This error sounds like a java bug in Jython/JES library. I am running JES under Windows 7 and have all the common Quicktime and AVI codex installed as well as the QTjava library in my jre... Any brilliant idea ? EDIT : Also tried the Linux version with same result for both QuickTime and AVI...

    Read the article

  • Using java.util.regex in Android apps - are there issues with this?

    - by johnrock
    In an Android app I have a utility class that I use to parse strings for 2 regEx's. I compile the 2 patterns in a static initializer so they only get compiled once, then activities can use the parsing methods statically. This works fine except that the first time the class is accessed and loaded, and the static initializer compiles the pattern, the UI hangs for close to a MINUTE while it compiles the pattern! After the first time, it flies on all subsequent calls to parseString(). My regEx that I am using is rather large - 847 characters, but in a normal java webapp this is lightning fast. I am testing this so far only in the emulator with a 1.5 AVD. Could this just be an emulator issue or is there some other reason that this pattern is taking so long to compile? private static final String exp1 = "(insertratherlong---847character--regexhere)"; private static Pattern regex1 = null; private static final String newLineAndTagsExp = "[<>\\s]"; private static Pattern regexNewLineAndTags = null; static { regex1 = Pattern.compile(exp1, Pattern.CASE_INSENSITIVE); regexNewLineAndTags = Pattern.compile(newLineAndTagsExp); } public static String parseString(CharSequence inputStr) { String replacementStr = "replaceMentText"; String resultString = "none"; try { Matcher regexMatcher = regex1.matcher(inputStr); try { resultString = regexMatcher.replaceAll(replacementStr); } catch (IllegalArgumentException ex) { } catch (IndexOutOfBoundsException ex) { } } catch (PatternSyntaxException ex) { } return resultString; }

    Read the article

  • Java Polynomial Multiplication with ArrayList

    - by user1506919
    I am having a problem with one of my methods in my program. The method is designed to take 2 arraylists and the perform multiplication between the two like a polynomial. For example, if I was to say list1={3,2,1} and list2={5,6,7}; I am trying to get a return value of 15,28,38,20,7. However, all I can get is an error message that says: Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0. I have provided the method below: private static ArrayList<Integer> multiply(ArrayList<Integer> list1,ArrayList<Integer> list2) { ArrayList<Integer> array =new ArrayList<Integer>(list1.size()+list2.size()); for (int i=0;i<array.size();i++) array.add(i, 0); for (int i = 0; i < list1.size(); i++) for (int j = 0; j < list2.size(); j++) array.set(i+j, ((list1.get(i) * list2.get(j))+array.get(i+j))); return array; } Any help with solving this problem is greatly appreciated.

    Read the article

1 2  | Next Page >