Code not producing desired result.

V

Vasu

Hi Friends!

Can anybody tell me why the following code generating
ArrayIndexOutofBoundsException = 5

import java.lang.System;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.*;
public class Bingo1 {
public static void main(String[] args) throws IOException {
System.out.println("Generating 5 Random Nos. for evaluation");
int[] In = new int[5];
int[] In2= new int[2];
int a=0, b=0;
boolean m=false;
boolean n=false;

//Generates random no in the range of 0 - 40 and put in an array.
for(int i=0; i<5; i++){
Random randomNo = new Random();
In=randomNo.nextInt(40);
System.out.println(In); }

//Asks user to enter two digits to search in the Array.
for(int i=0; i<2; i++){
if(i==0) {System.out.print("Please Enter first no.: ");}
else {System.out.print("Please Enter second no.: ");}
System.out.flush();
String y;
DataInputStream keyboardInput = new DataInputStream(System.in);
y=keyboardInput.readLine();
if(i==0){a = Integer.valueOf(y).intValue();
System.out.println("This is first digit : "+a); }
else {b = Integer.valueOf(y).intValue();
System.out.println("This is second digit : "+b);}
}

/*Now code compares the two digits against the array and sets boolean
value accordingly */
System.out.println("Let's compare the two digits you mentioned");
for(int i=0; i<5; i++){
if(In==a){ m=true;} else {m=false;} }

for(int j=0; j<=5; j++){
if(In[j]==b){n=true;} else {n=false;} }

System.out.println("Value of m = "+m);
System.out.println("Value of n = "+n);
if(m==true && n==true){System.out.println("Bingo! You have made
it.");}
else {System.out.println("Sorry! try again.");}
}
}

Now this code, when I'm putting the two digits which are there in the
array, clearly tells "Bingo!...", but when I put one digit different
than in array (particularly the second one) it shows the following
message :
C:\jdk1.6\bin>java Bingo1
Generating 5 Random Nos. for evaluation
13
15
13
12
13
Please Enter first no.: 14
This is first digit : 14
Please Enter second no.: 13
This is second digit : 13
Let's compare the two digits you mentioned
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5

Why?? Please help make me understand the root cause.

Thanks and regards
Vasu
at Bingo1.main(Bingo1.java:52)
 
D

dennis

Hi Vasu,

I haven't evaluated all of you code, but I'm sure the ArrayIndexOutofBound is created by these two lines:
int[] In = new int[5];
for(int j=0; j<=5; j++){

You cannot read ln[5] from an array that has length 5. The last line should read for (int j=0;j<5;j++) for it to work.

Regards,
Dennis..
 
J

John B. Matthews

Vasu said:
for(int i=0; i<5; i++){
Random randomNo = new Random();
In=randomNo.nextInt(40);
System.out.println(In); }


You don't need five new instances of Random; one will do.

[...]
System.out.println("Let's compare the two digits you mentioned");
for(int i=0; i<5; i++){
if(In==a){ m=true;} else {m=false;} }

for(int j=0; j<=5; j++){
if(In[j]==b){n=true;} else {n=false;} } [...]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5

Why?? Please help make me understand the root cause.


The second loop, using index j, has an upper bound of 5, but the array
only has 5 elements, numbered 0 through 4. Use j < 5, as you did with
the first loop.

I'm guessing that you want m and n to be true for any match, not just
the last one. In the example below, the expression "m = m | in == a"
may be read as "the new boolean value of m becomes the logical "or" of
the previous value and the value of the expression in == a". I've
shown a second way to express that using shorthand assignment in a
for-each loop. Notice how the latter precludes the bounds error above.

for (int i = 0; i < 5; i++) {
m = m | in == a;
}

for (int j : in) {
n |= j == b;
}
if (m==true && n==true) ...

Similarly, this predicate can be simplified: if (m & n).

Finally, variable names traditionally start with lower case, and
DataInputStream.html#readLine() is deprecated:

<http://java.sun.com/javase/6/docs/api/java/io/DataInputStream.html#readL
ine()>
 
J

J. Davidson

John said:
I'm guessing that you want m and n to be true for any match, not just
the last one. In the example below, the expression "m = m | in == a"
may be read as "the new boolean value of m becomes the logical "or" of
the previous value and the value of the expression in == a". I've
shown a second way to express that using shorthand assignment in a
for-each loop. Notice how the latter precludes the bounds error above.

for (int i = 0; i < 5; i++) {
m = m | in == a;
}

for (int j : in) {
n |= j == b;
}


|| short-circuits. Unfortunately there's no ||= for some reason.
Similarly, this predicate can be simplified: if (m & n).

&& short-circuits.

|| and && are more normally used for boolean logic on booleans, | and &
more usually for bitwise logic on bytes, shorts, ints, and longs.

- jenny
 
L

Lew

J. Davidson said:
|| short-circuits. Unfortunately there's no ||= for some reason.

Because it would never evaluate the right-hand side once the left-hand side
went 'true', and is therefore a very silly operator?
|| and && are more normally used for boolean logic on booleans, | and &
more usually for bitwise logic on bytes, shorts, ints, and longs.

| and & aren't logical operators on int types, they're arithmetic operators,
ergo not for logic at all. They are logical operators when applied to boolean
operands.

||, &&, | and & are all "normally" used for boolean operations on booleans.
|| and && don't apply to integral types at all. |, & and ^ are "normally"
used for arithmetic operations on integral types.

JLS ss. 15.22 and 15.23.
 
J

John B. Matthews

"J. Davidson said:
John said:
I'm guessing that you want m and n to be true for any match, not just
the last one. In the example below, the expression "m = m | in == a"
may be read as "the new boolean value of m becomes the logical "or" of
the previous value and the value of the expression in == a". I've
shown a second way to express that using shorthand assignment in a
for-each loop. Notice how the latter precludes the bounds error above.

for (int i = 0; i < 5; i++) {
m = m | in == a;
}

for (int j : in) {
n |= j == b;
}


|| short-circuits.


Thank you for expanding on this topic. Of course, I was going for
correct first, optimal second. The assignment "m = m || in == a"
would preclude evaluating the equality test, but exiting the loop on a
match would be even better, on average, half the time.

If this were a real bottleneck, I'd just use a TreeSet, which excludes
duplicates and orders the values conveniently:

Random random = new Random();
Set<Integer> values = new TreeSet<Integer>();
while (values.size() < 5) {
values.add(random.nextInt(40));
}

Then the predicate would be just "values.contains(a)"
Unfortunately there's no ||= for some reason.

See Lew's reply.
&& short-circuits.

|| and && are more normally used for boolean logic on booleans, | and &
more usually for bitwise logic on bytes, shorts, ints, and longs.

I would advocate using the conditional operators (||, &&) where
short-circuiting is the desired behavior, e.g.:

(x != 0) && (1/x > ...) // preclude division by zero
 
T

Tom Anderson

Because it would never evaluate the right-hand side once the left-hand side
went 'true', and is therefore a very silly operator?

That's exactly why you'd want it:

isDatabaseInitialised ||= initialiseDatabase() ;

Note that i am not advocating this.

tom
 
D

Daniel Pitts

Tom said:
That's exactly why you'd want it:

isDatabaseInitialised ||= initialiseDatabase() ;

Note that i am not advocating this.

tom
This is Java, not Perl or Bash. Use an if statement!
 
T

Tom Anderson

This is Java, not Perl or Bash. Use an if statement!

Actually, i prefer C++:

#include <stdio.h>

bool execute_if_needed(bool &var, bool (*func)()) {
if (!var) {
var = func() ;
return var ;
}
return false ;
}

bool init_database() {
printf("initialising database\n") ;
return true ;
}

int main(int argc, char **argv) {
bool dbInited = false ;
printf("dbInited = %i\n", dbInited) ;
execute_if_needed(dbInited, init_database) ;
printf("dbInited = %i\n", dbInited) ;
execute_if_needed(dbInited, init_database) ;
printf("dbInited = %i\n", dbInited) ;
return 0 ;
}

tom
 
L

Lew

John said:
I would advocate using the conditional operators (||, &&) where
short-circuiting is the desired behavior, e.g.:

(x != 0) && (1/x > ...) // preclude division by zero

Also a common idiom for null tests.

if ( x != null && x.equals( foo ))
 
A

Arne Vajhøj

Joshua said:
Lew said:
Tom said:
Actually, i [sic] prefer C++:

#include <stdio.h>

I thought the ".h" was obsolete in C++.

#include <cstdio>

That's the preferred one, although it puts everything in the std namespace.

"For compatibility with the Standard C library, the C++ Standard library
provides the 18 C headers"

"Every C header, each of which has a name of the form name .h, behaves
as if each name placed in the Standard library
namespace by the corresponding cname header is also placed within the
namespace scope of the namespace std and is
followed by an explicit using-declaration"

Arne

PS: It is not just for compatibility with C but also for
compatibility with older pre-ANSI/ISO C++ versions.
 
T

Tom Anderson

Joshua said:
Lew said:
Tom Anderson wrote:
Actually, i [sic] prefer C++:

#include <stdio.h>

I thought the ".h" was obsolete in C++.

#include <cstdio>

That's the preferred one, although it puts everything in the std namespace.

"For compatibility with the Standard C library, the C++ Standard library
provides the 18 C headers"

"Every C header, each of which has a name of the form name .h, behaves
as if each name placed in the Standard library namespace by the
corresponding cname header is also placed within the namespace scope of
the namespace std and is followed by an explicit using-declaration"

PS: It is not just for compatibility with C but also for
compatibility with older pre-ANSI/ISO C++ versions.

I have basically no idea what that means, and i'm pretty glad about that.
I learned some C/C++ from a book in the early to mid 1990s, and have never
had any interest in keeping up with alleged updates to it. Updating C/C++
is like updating latin.

tom
 
M

Martin Gregorie

I have basically no idea what that means, and i'm pretty glad about
that. I learned some C/C++ from a book in the early to mid 1990s, and
have never had any interest in keeping up with alleged updates to it.
Updating C/C++ is like updating latin.
C has been pretty much unchanged since the ANSI and POSIX requirements
got added. Once you know it you can just use it. In any case, the
standard library is at least as well documented as the Java SDK library
classes but its much smaller.

I had a brush with C++ in the mid 90s, decided I hated it, and have
ignored it ever since. Every so often I've had to look at C++ source but
the bits of it I've looked at have all looked remarkably like ANSI C
with // comments - not an object in sight.
 
A

Arne Vajhøj

Tom said:
Joshua said:
Lew wrote:
Tom Anderson wrote:
Actually, i [sic] prefer C++:

#include <stdio.h>

I thought the ".h" was obsolete in C++.

#include <cstdio>

That's the preferred one, although it puts everything in the std
namespace.

"For compatibility with the Standard C library, the C++ Standard
library provides the 18 C headers"

"Every C header, each of which has a name of the form name .h, behaves
as if each name placed in the Standard library namespace by the
corresponding cname header is also placed within the namespace scope
of the namespace std and is followed by an explicit using-declaration"

PS: It is not just for compatibility with C but also for
compatibility with older pre-ANSI/ISO C++ versions.

I have basically no idea what that means, and i'm pretty glad about
that. I learned some C/C++ from a book in the early to mid 1990s, and
have never had any interest in keeping up with alleged updates to it.
Updating C/C++ is like updating latin.

It agrees with Lew & Joshua in that the .h is obsolete/non-preferred.

Arne
 
A

Arne Vajhøj

Martin said:
C has been pretty much unchanged since the ANSI and POSIX requirements
got added. Once you know it you can just use it. In any case, the
standard library is at least as well documented as the Java SDK library
classes but its much smaller.

Actually some things were were added in C99. But they are
not much used. Most C code is older and most compilers do not
support C99.
I had a brush with C++ in the mid 90s, decided I hated it, and have
ignored it ever since. Every so often I've had to look at C++ source but
the bits of it I've looked at have all looked remarkably like ANSI C
with // comments - not an object in sight.

That is a good sign of bad C++ programmers.

Good C++ code would look a lot different from C.

And can be much more complex to understand.

Arne
 
J

John W Kennedy

Arne said:
Tom said:
Joshua Cranmer wrote:
Lew wrote:
Tom Anderson wrote:
Actually, i [sic] prefer C++:

#include <stdio.h>

I thought the ".h" was obsolete in C++.

#include <cstdio>

That's the preferred one, although it puts everything in the std
namespace.

"For compatibility with the Standard C library, the C++ Standard
library provides the 18 C headers"

"Every C header, each of which has a name of the form name .h,
behaves as if each name placed in the Standard library namespace by
the corresponding cname header is also placed within the namespace
scope of the namespace std and is followed by an explicit
using-declaration"

PS: It is not just for compatibility with C but also for
compatibility with older pre-ANSI/ISO C++ versions.

I have basically no idea what that means, and i'm pretty glad about
that. I learned some C/C++ from a book in the early to mid 1990s, and
have never had any interest in keeping up with alleged updates to it.
Updating C/C++ is like updating latin.

It agrees with Lew & Joshua in that the .h is obsolete/non-preferred.

But, annoyingly, gives less cluttered SSCEs. Such is human perversity.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top