This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
I have this error in my code:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
70
at Main.main(Main.java:72)
I don't know why it is doing this? please help. I thank you in advance. I have gone through several threads on several websites and it doesn't have anything that worked. I have been working on this for a while. I know what the ArrayIndexOutOfBoundsException is i am trying to figure it out though and i have been unsuccessful
This is the code:
import java.util.Scanner;
import java.util.Random;
public class Main
{
public static void main (String[] args)
{
Scanner myScanner = new Scanner (System.in);
Random myRandom = new Random();
int answer;
int definitionSelected = 0;
String[] code = new String[68];
String[] definition = new String[68];
int[] listedDefinition = new int[4];
int[] definitionUsed = new int[68];
int i;
int Size = 68;
int Other = 4;
double[] alpha = new double[68];
int count = 0;
code[0] = "10-0" ; definition[0] = "Disappeared";
code[1] = "10-1" ; definition[1] = "Frequency Change";
code[2] = "10-2" ; definition[2] = "Negative";
code[3] = "10-3" ; definition[3] = "Stop Transmitting";
code[4] = "10-4" ; definition[4] = "Affirmative";
code[5] = "10-5" ; definition[5] = "Relay Message";
code[6] = "10-6" ; definition[6] = "Busy";
code[7] = "10-7" ; definition[7] = "Out Of Service";
code[8] = "10-8" ; definition[8] = "In Service";
code[9] = "10-9" ; definition[9] = "Repeat";
code[10] = "10-10" ; definition[10] = "Fight In Progress";
code[11] = "10-11" ; definition[11] = "Traffic Stop";
code[12] = "10-12" ; definition[12] = "Standby";
code[13] = "10-13" ; definition[13] = "Gun Shots";
code[15] = "10-15" ; definition[15] = "Subject en Route to station";
code[16] = "10-16" ; definition[16] = "Stolen Vehicle";
code[17] = "10-17" ; definition[17] = "Suspicious Person";
code[19] = "10-19" ; definition[19] = "Active Ride Along";
code[20] = "10-20" ; definition[20] = "location";
code[22] = "10-22" ; definition[22] = "Disregard";
code[23] = "10-23" ; definition[23] = "Arrived on scene";
code[25] = "10-25" ; definition[25] = "Do you have contact with ?";
code[26] = "10-26" ; definition[26] = "ETA";
code[27] = "10-27" ; definition[27] = "Drivers license check for valid";
code[28] = "10-28" ; definition[28] = "license Plate check";
code[29] = "10-29" ; definition[29] = "NCIC Warrant Check";
code[30] = "10-30" ; definition[30] = "Wanted Person";
code[31] = "10-31" ; definition[31] = "Armed Suspect";
code[32] = "10-32" ; definition[32] = "Request Backup, Code 1,2,3";
code[34] = "10-34" ; definition[34] = "Wanted Person";
code[35] = "10-35" ; definition[35] = "Not Wanted No Warrants";
code[38] = "10-38" ; definition[38] = "Suspicious Vehicle";
code[41] = "10-41" ; definition[41] = "Beginning Tour Of Duty";
code[42] = "10-42" ; definition[42] = "Ending Tour Of Duty";
code[43] = "10-43" ; definition[43] = "Information About ?";
code[46] = "10-46" ; definition[46] = "Attempt Of Suicide";
code[49] = "10-49" ; definition[49] = "Drag Racing";
code[50] = "10-50" ; definition[50] = "vehicle Accident";
code[51] = "10-51" ; definition[51] = "Request Towing Service";
code[52] = "10-52" ; definition[52] = "Request EMS";
code[53] = "10-53" ; definition[53] = "Request Fire Department";
code[54] = "10-54" ; definition[54] = "Hit And Run";
code[55] = "10-55" ; definition[55] = "Intoxicated Driver";
code[56] = "10-56" ; definition[56] = "Intoxicated Pedestrian";
code[60] = "10-60" ; definition[60] = "Assault By An Animal";
code[61] = "10-61" ; definition[61] = "Bicycle Theft";
code[62] = "10-62" ; definition[62] = "Kidnapping";
code[63] = "10-63" ; definition[63] = "Radio Check";
code[64] = "10-64" ; definition[64] = "Sexual Assualt";
code[65] = "10-65" ; definition[65] = "Armed Robbery";
code[66] = "10-66" ; definition[66] = "Reckless Driver";
code[67] = "10-67" ; definition[67] = "Fire";
code[70] = "10-70" ; definition[70] = "Foot Pursuit";
code[71] = "10-71" ; definition[71] = "Request Supervisor On Scene";
code[72] = "10-72" ; definition[72] = "Administrative Assistance";
code[73] = "10-73" ; definition[73] = "Advise Status";
code[74] = "10-74" ; definition[74] = "Negative";
code[76] = "10-76" ; definition[76] = "Prowler";
code[80] = "10-80" ; definition[80] = "Vehicle Pursuit";
code[85] = "10-85" ; definition[85] = "Delay Due To";
code[86] = "10-86" ; definition[86] = "Any Traffic For me?";
code[88] = "10-88" ; definition[88] = " Requesting Deputy Chief (Department)";
code[89] = "10-89" ; definition[89] = "Requesting Chief (Department)";
code[90] = "10-90" ; definition[90] = "Warning";
code[91] = "10-91" ; definition[91] = "Unnecessary use of Radio";
code[93] = "10-93" ; definition[93] = "Bank Alarm";
code[97] = "10-97" ; definition[97] = "In route";
code[99] = "10-99" ; definition[99] = "Officer In Distress EXTREME EMERGENCY ONLY";
do
{
answer = myRandom.nextInt(68);
System.out.println("\nCode Is : " + code [answer] + "\n");
for (i = 0;i<Size;i++) {
int j;
do
{
j = myRandom.nextInt(68);
}
while (definitionUsed[j] != 0 || j == answer);
definitionUsed[j] = 1;
listedDefinition[i] = j;
}
listedDefinition[myRandom.nextInt(4)] = answer;
for (i = 0;i<Other;i++)
{
System.out.println((i + 1) + " - " +
definition[listedDefinition[i]]);
}
System.out.print("\nWhat is The definition? (Enter 0 to Stop) ");
definitionSelected = myScanner.nextInt();
if (definitionSelected != 0)
{
if (listedDefinition[definitionSelected - 1] == answer)
System.out.println("That's It Good Job");
}
else
{
System.out.println("Sorry, The answer is " + definition +".");
}
}
while (definitionSelected != 0);
}
}
You have defined an array of size 68 and you are trying to use it beyond this size. Since size of array cannot be dynamically increased. So we get the exception, Array index out of bounds. If you want the size to change dynamically use ArrayList.
You have to fix initial array size.
In your code you have:
code[99] = "10-99"
and
definition[99] = "Officer In Distress EXTREME EMERGENCY ONLY";
In both cases you are trying to assing to position 99 so it means that you have at least 100 element (because for 100 elements positions are from 0 to 99).
So you have to change your initial size from 68 to 100 in those lines:
String[] code = new String[68];
String[] definition = new String[68];
int[] listedDefinition = new int[4];
int[] definitionUsed = new int[68];
double[] alpha = new double[68];
to:
String[] code = new String[100];
String[] definition = new String[100];
int[] listedDefinition = new int[100];
int[] definitionUsed = new int[100];
double[] alpha = new double[100];
Related
I am attempting to read in info from files to implement Dijkstra's algorithm. I believe that the double for loop is causing this to drastically slow down, is there anyway around this?
Edge[] edge = new Edge[127807];
int indexEdge = 0;
String line2 = "";
BufferedReader fileReader2 = new BufferedReader(new FileReader("Road.txt"));
String valueString = null;
String vertex1IDName = null;
String vertex2IDName = null;
String extra = null;
float value = 0;
int vertex1ID = 0;
int vertex2ID = 0;
//Read the file line by line
while ((line2 = fileReader2.readLine()) != null)
{
//Get all tokens available in line
String[] tokens2 = line2.split(DELIMITER);
for(String token1 : tokens2)
{
vertex1IDName = tokens2[0];
vertex2IDName = tokens2[1];
valueString = tokens2[2];
if(tokens2.length - 1 == 3) {
extra = tokens2[tokens2.length - 1];
}
else {
extra = "";
}
vertex1ID = Integer.parseInt(vertex1IDName);
vertex2ID = Integer.parseInt(vertex2IDName);
value = Float.parseFloat(valueString);
}
System.out.println("value: "+ value + " vertex1ID:"+ vertex1ID +" vertex2ID:"+ vertex2ID+ " extra:" + extra);
//if vertex 1 name or vertex 2 name in vertex.getID()
for(int i = 0; i< indexVertex; i++) {
for(int j = 0; j< indexVertex; j++) {
if(vertex1ID == vertex[i].getID() && vertex2ID == vertex[j].getID()) {
vertex[i].addNeighbour(edge[indexEdge] = new Edge(value,vertex[i],vertex[j],extra));
indexEdge++;
}
}
}
}
Here is my code so far, how do I get this to work though as I am struggling to print a sentence at all, let alone randomly.
I need one word from each array to print a sentence using the words in the array
import java.util.Random;
public class MadLibs {
public static void main(String[] args) {
String[] nouns = null;
String[] verbs = null;
String[] adjec = null;
String[] adver = null;
nouns[0] = "Lion";
nouns[1] = "Stewart";
nouns[2] = "Timbaktu";
nouns[3] = "Kilamanjaro";
nouns[4] = "Hawai";
nouns[5] = "Frog";
nouns[6] = "Russia";
nouns[7] = "Dimethyltryptaline";
nouns[8] = "Dog";
nouns[9] = "Badness";
verbs[0] = "hear";
verbs[1] = "achieve";
verbs[2] = "smash";
verbs[3] = "destroy";
verbs[4] = "smoke";
verbs[5] = "burn";
verbs[6] = "rose";
verbs[7] = "speak";
verbs[8] = "type";
verbs[9] = "be";
adjec[0] = "Tangy";
adjec[1] = "Sour";
adjec[2] = "Smooth";
adjec[3] = "Sticky";
adjec[4] = "Soft";
adjec[5] = "Black";
adjec[6] = "Whispering";
adjec[7] = "Resonant";
adjec[8] = "Wide";
adjec[9] = "Long";
adver[0] = "Truthfully";
adver[1] = "Endlessly";
adver[2] = "Painfully";
adver[3] = "Tirelessly";
adver[4] = "Beautifully";
adver[5] = "Uneasily";
adver[6] = "Wickedly";
adver[7] = "Briskly";
adver[8] = "Now";
adver[9] = "Last";
String random = (verbs[new Random().nextInt(verbs.length)]);
System.out.println("Does your" + verbs + " your " + adjec + nouns + adver );
}
}
Here you go :) Hope this is what you want (I wouldn't normally solve a school assignment but sometimes you just feel like it):
public static void main(String[] args) {
String[] nouns = new String[10];
String[] verbs = new String[10];
String[] adjec = new String[10];
String[] adver = new String[10];
nouns[0] = "Lion";
nouns[1] = "Stewart";
nouns[2] = "Timbaktu";
nouns[3] = "Kilamanjaro";
nouns[4] = "Hawai";
nouns[5] = "Frog";
nouns[6] = "Russia";
nouns[7] = "Dimethyltryptaline";
nouns[8] = "Dog";
nouns[9] = "Badness";
verbs[0] = "hear";
verbs[1] = "achieve";
verbs[2] = "smash";
verbs[3] = "destroy";
verbs[4] = "smoke";
verbs[5] = "burn";
verbs[6] = "rose";
verbs[7] = "speak";
verbs[8] = "type";
verbs[9] = "be";
adjec[0] = "Tangy";
adjec[1] = "Sour";
adjec[2] = "Smooth";
adjec[3] = "Sticky";
adjec[4] = "Soft";
adjec[5] = "Black";
adjec[6] = "Whispering";
adjec[7] = "Resonant";
adjec[8] = "Wide";
adjec[9] = "Long";
adver[0] = "Truthfully";
adver[1] = "Endlessly";
adver[2] = "Painfully";
adver[3] = "Tirelessly";
adver[4] = "Beautifully";
adver[5] = "Uneasily";
adver[6] = "Wickedly";
adver[7] = "Briskly";
adver[8] = "Now";
adver[9] = "Last";
String v = (verbs[new Random().nextInt(verbs.length)]);
String a = (adjec[new Random().nextInt(adjec.length)]);
String n = (nouns[new Random().nextInt(nouns.length)]);
String ad = (adver[new Random().nextInt(adver.length)]);
System.out.println("Does your " + v + " your " + a + " " + n + " " + ad );
}
However, the sentences do not make sense. The words should probably come in another order like:
System.out.println("Does your " + a + " " + n + " " + v + " " + ad );
I'm having one problem in show my ListView correctly
If I declare
String[] cod = {"cod1","cod2", "cod3"};
String[] desc = {"desc1","desc2", "desc3"};
String[] preco = {"1.00","2.00", "3.00"};
My adapter is:
lista = (ListView)findViewById(R.id.list);
lista.setAdapter(new dataListAdapter(cod, desc, preco));
It works perfectly!
But if I get the data from a database, the ListView shows only one row.
results = DbHelper.getItemsDao().queryRaw(sqlGetItems);
/*GET ALL RESULTS FROM DATABASE*/
List<String[]> array = results.getResults();
int count = array.size();
String[] cod = null, desc = null, preco = new String[count];
for(int i = 0; i < count; i++) {
String[] res = array.get(i);
cod = new String[]{res[0]} ;
desc = new String[]{res[1]};
preco = new String[]{res[3]};
}
lista = (ListView) findViewById(R.id.list);
lista.setAdapter(new dataListAdapter(cod, desc, preco));
Try this solution:
for(int i = 0; i < count; i++) {
String[] res = array.get(i);
cod.add(res[0]) ;
desc.add(res[1]);
preco.add(res[3]);
}
Look at the code carefully:
for(int i = 0; i<count; i++){
String[] res = array.get(i);
cod = new String[]{res[0]} ;
desc = new String[]{res[1]};
preco = new String[]{res[3]} ;
}
lista=(ListView)findViewById(R.id.list);
lista.setAdapter(new dataListAdapter(cod, desc, preco));
Here, the varables cod, desc and preco are created every time in the loop. So they are the last one at the end.
You can try like as follows:
String[] cod = new String[count];
String[] desc = new String[count];
String[] preco = new String[count];
for(int i = 0; i<count; i++){
String[] res = array.get(i);
cod[i] = res[0] ;
desc[i] = res[1];
preco[i] = res[3] ;
}
for some reason I can't get Strings compareTo method to work. I get this error message:
exception in thread main java.lang.NullpointerException
at java.lang.String.compareTo(Unknown Source)
at Sort.main(Sort.java:27)
What can I do to fix this?
(this code demands that the to arrays are allready sorted individually.)
import java.util.*;
class Sort{
public static void main(String[] args){
String[] ord = new String[6];
ord[0] = "astra";
ord[1] = "bilum";
ord[2] = "deliber";
ord[3] = "kaliber";
ord[4] = "suppe";
ord[5] = "vorte";
String[] ordet = new String[6];
ord[0] = "akilles";
ord[1] = "kopper";
ord[2] = "lipton";
ord[3] = "mus";
ord[4] = "orkester";
ord[5] = "toving";
String[] flettet = new String[ord.length + ordet.length];
for(int i = 0; i < ord.length; i++){
int teller = i;
for(int j = 0; j < ordet.length; j++){
if(ord[i].compareTo(ordet[j]) > 0){ //line 27
teller += 1;
}
}
flettet[teller] = ord[i];
}
}
}
Do you mean - it looks like you are setting the wrong array:
String[] ordet = new String[6];
ordet[0] = "akilles";
ordet[1] = "kopper";
ordet[2] = "lipton";
ordet[3] = "mus";
ordet[4] = "orkester";
ordet[5] = "toving";
You never assign any values to ordet. so compareTo is comparing a string to NULL
String[] ord = new String[6];
ord[0] = "astra";
ord[1] = "bilum";
ord[2] = "deliber";
ord[3] = "kaliber";
ord[4] = "suppe";
ord[5] = "vorte";
String[] ordet = new String[6];
ord[0] = "akilles"; //overwriting ord[0]
ord[1] = "kopper"; //overwriting ord[1]
ord[2] = "lipton"; //overwriting ord[2]
ord[3] = "mus"; //overwriting ord[3]
ord[4] = "orkester"; //overwriting ord[4]
ord[5] = "toving"; //overwriting ord[5]
String[] ordet = new String[6];
ord[0] = "akilles";
ord[1] = "kopper";
ord[2] = "lipton";
ord[3] = "mus";
ord[4] = "orkester";
ord[5] = "toving";
You never filled the ordet array, you just over-wrote the ord array.
At this point there is no elements in the ordet array, just nulls.
So...
if(ord[i].compareTo(ordet[j]) > 0){ //line 27
is comparing to an element that doesnt exist, and #compareTo throws a NullPointerException because you passed in a null, not a String
I have to build a hangman program for java for a class. the problem i'm having is having the letter change once you guess a letter. all it's doing is getting an error when i guess. any help would be appreciated, thank you
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
public class test2 {
public static void main( String[] args ) {
HangmanSession hangmanSession = new HangmanSession();
hangmanSession.play();
}
}
class HangmanSession {
private Player player;
private Words secretWord;
private LetterBox letterBox;
private int triesNumber = 6;
public HangmanSession() {
player = new Player();
player.askName();
secretWord = new Words();
letterBox = new LetterBox();
}
private void printState() {
letterBox.print();
System.out.print( "Hidden word : " );
secretWord.print();
System.out.print( "Tries left: " + triesNumber + "<guess letter:>" );
}
public void play() {
boolean bool = true;
while( true ) {
bool = true;
printState();
char ch = player.takeGuess();
if( letterBox.contains( ch ) ) {
System.out.println( "Try again, you've already used the letter " + ch );
bool = false;
}
if( bool ) {
if( secretWord.guess( ch ) ) {
System.out.println( "You have found the letter " + ch );
}
else {
triesNumber--;
}
if( triesNumber < 1 )
gameOver();
if( secretWord.found() )
congratulations();
}
}
}
public void congratulations() {
System.out.println( "Congratulations " + player + ", you win!" );
System.exit( 0 );
}
public void gameOver() {
System.out.println( "Sorry " + player + ", this time you lose!" );
System.exit( 0 );
}
}
class Words {
private String fv;
private StringBuffer pValue;
private int found = 0;
{
String Words[] = new String[23];
Words[0] = "carbon";
Words[1] = "dictionary";
Words[2] = "restaurant";
Words[3] = "televison";
Words[4] = "responsible";
Words[5] = "technology";
Words[6] = "computer";
Words[7] = "communicate";
Words[8] = "automobile";
Words[9] = "coffee";
Words[10] = "federation";
Words[11] = "exaggerate";
Words[12] = "cappuccino";
Words[13] = "macintosh";
Words[14] = "apple";
Words[15] = "microsoft";
Words[16] = "lighter";
Words[17] = "shark";
Words[18] = "bunker";
Words[19] = "argument";
Words[20] = "playstation";
Words[21] = "parrot";
Words[22] = "canine";
Random random = new Random();
int randomWord = random.nextInt(22);
for (int i = 0; i < Words.length; i++);
String[] displayLetters = new String[Words[randomWord].length()];
for (int i=0; i<displayLetters.length; i++)
{
displayLetters[i] = "_";
}
for (int i=0; i<displayLetters.length; i++)
{
System.out.print(displayLetters[i]+" ");
}
}
{
}
public boolean found() {
System.out.println( "Letters found:" + found + "/" + fv.length() );
return ( found == fv.length() );
}
public boolean guess( char c ) {
int index = fv.indexOf( c );
if( index == -1 )
return false;
else {
found = found + findOccurances( c );
return true;
}
}
private int findOccurances( char c ) {
int idx = fv.indexOf( c );
pValue.setCharAt( idx, fv.charAt( idx ) );
int counter = 1;
while( idx != -1 ) {
int index = fv.indexOf( c, idx + 1 );
idx = index;
if( idx != -1 ) {
counter++;
pValue.setCharAt( idx, fv.charAt( idx ) );
}
}
return counter;
}
public void print() {
System.out.println( pValue );
}
}
class Player {
private String name = "";
public void askName()
{System.out.print( "Player, enter your name:" );
name = receiveInput();
}
public char takeGuess() {
return receiveInput().charAt( 0 );
}
private String receiveInput() {
String str = " ";
BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
try {
str = br.readLine();
}
catch( IOException ex ) {
ex.printStackTrace();
}
return str;
}
public String toString() {
return name;
}
}
class LetterBox {
private char[] lbox = new char[24];
private int counter = 0;
public boolean contains( char c ) {
for( int i = 0; i < counter; i++ ) {
if( lbox[i] == c )
return true;
}
lbox[counter] = c;
counter++;
return false;
}
public void print() {
System.out.print( "\nLetterBox:" );
for( int i = 0; i < counter; i++ ) {
System.out.print( lbox[i] );
}
System.out.println( "" );
}
}
Im getting null for the hidden word: and i'm getting these errors when i try to guess a letter
Exception in thread "main" java.lang.NullPointerException
at Words.guess(Hangman2.java:141)
at HangmanSession.play(Hangman2.java:53)
at Hangman2.main(Hangman2.java:11)
Both your fv and pValue are not initialized, change your initialization block to this
fv = Words[randomWord]; // assign the answer to fv
pValue = new StringBuffer(fv.length()); // init the user result
for (int i = 0; i < displayLetters.length; i++)
{
displayLetters[i] = "_";
pValue.append('_'); // Init the user result to ____
}
And, get yourself a decent IDE like eclipse and try to learn how to set break point and catch exception in debugging.
I don't see where you are initializing private String fv;
and the NullPointerException is caused because of that in this line
int index = fv.indexOf(c);
in public boolean guess(char c) of class Words.
Besides that, there is a lot of stuff to be cleaned up
like empty blocks { } and
for (int i = 0; i < Words.length; i++)
;
do nothing and could be removed.