Code not producing desired result.

Discussion in 'Java' started by Vasu, Nov 15, 2008.

  1. Vasu

    Vasu Guest

    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)
    Vasu, Nov 15, 2008
    #1
    1. Advertising

  2. Vasu

    dennis Guest

    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..
    dennis, Nov 15, 2008
    #2
    1. Advertising

  3. In article
    <>,
    Vasu <> wrote:
    [...]
    > 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()>

    --
    John B. Matthews
    trashgod at gmail dot com
    http://home.roadrunner.com/~jbmatthews/
    John B. Matthews, Nov 15, 2008
    #3
  4. Vasu

    J. Davidson Guest

    John B. Matthews wrote:
    > 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
    J. Davidson, Nov 17, 2008
    #4
  5. Vasu

    Lew Guest

    J. Davidson wrote:
    > || 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.

    --
    Lew
    Lew, Nov 18, 2008
    #5
  6. In article <gfrdtp$8d6$>,
    "J. Davidson" <> wrote:

    > John B. Matthews wrote:
    > > 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.

    > > 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.


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

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

    --
    John B. Matthews
    trashgod at gmail dot com
    http://home.roadrunner.com/~jbmatthews/
    John B. Matthews, Nov 18, 2008
    #6
  7. Vasu

    Tom Anderson Guest

    On Mon, 17 Nov 2008, Lew wrote:

    > J. Davidson wrote:
    >
    >> || 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?


    That's exactly why you'd want it:

    isDatabaseInitialised ||= initialiseDatabase() ;

    Note that i am not advocating this.

    tom

    --
    life finds a way
    Tom Anderson, Nov 18, 2008
    #7
  8. Vasu

    Daniel Pitts Guest

    Tom Anderson wrote:
    > On Mon, 17 Nov 2008, Lew wrote:
    >
    >> J. Davidson wrote:
    >>
    >>> || 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?

    >
    > 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!
    --
    Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>
    Daniel Pitts, Nov 18, 2008
    #8
  9. Vasu

    Tom Anderson Guest

    On Tue, 18 Nov 2008, Daniel Pitts wrote:

    > Tom Anderson wrote:
    >> On Mon, 17 Nov 2008, Lew wrote:
    >>
    >>> J. Davidson wrote:
    >>>
    >>>> || 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?

    >>
    >> That's exactly why you'd want it:
    >>
    >> isDatabaseInitialised ||= initialiseDatabase() ;
    >>
    >> Note that i am not advocating this.

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

    --
    life finds a way
    Tom Anderson, Nov 18, 2008
    #9
  10. Vasu

    Lew Guest

    Tom Anderson wrote:
    > Actually, i [sic] prefer C++:
    >
    > #include <stdio.h>


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

    --
    Lew
    Lew, Nov 19, 2008
    #10
  11. Vasu

    Lew Guest

    John B. Matthews wrote:
    > 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 ))

    --
    Lew
    Lew, Nov 19, 2008
    #11
  12. 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.

    --
    Beware of bugs in the above code; I have only proved it correct, not
    tried it. -- Donald E. Knuth
    Joshua Cranmer, Nov 19, 2008
    #12
  13. In article <gfvmlg$gcb$>, Lew <> wrote:

    > John B. Matthews wrote:
    > > 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 ))


    Ah, an even more cogent example.

    By way of comparison, in Ada one might say "if x /= null and then x.foo
    = 42 then":

    <http://www.adaic.com/standards/05rm/html/RM-4-5-1.html>

    --
    John B. Matthews
    trashgod at gmail dot com
    http://home.roadrunner.com/~jbmatthews/
    John B. Matthews, Nov 19, 2008
    #13
  14. 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"

    Arne

    PS: It is not just for compatibility with C but also for
    compatibility with older pre-ANSI/ISO C++ versions.
    Arne Vajhøj, Nov 19, 2008
    #14
  15. Vasu

    Tom Anderson Guest

    On Tue, 18 Nov 2008, Arne Vajhøj wrote:

    > 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.

    tom

    --
    uk.local groups TO BE RENAMED uk.lunatic.fringe groups
    Tom Anderson, Nov 19, 2008
    #15
  16. On Wed, 19 Nov 2008 17:52:28 +0000, Tom Anderson wrote:

    > 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.


    --
    martin@ | Martin Gregorie
    gregorie. | Essex, UK
    org |
    Martin Gregorie, Nov 19, 2008
    #16
  17. Vasu

    Arne Vajhøj Guest

    Tom Anderson wrote:
    > On Tue, 18 Nov 2008, Arne Vajhøj wrote:
    >> 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.

    Arne
    Arne Vajhøj, Nov 19, 2008
    #17
  18. Martin Gregorie wrote:
    > On Wed, 19 Nov 2008 17:52:28 +0000, Tom Anderson wrote:
    >> 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.


    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
    Arne Vajhøj, Nov 19, 2008
    #18
  19. Arne Vajhøj wrote:
    > Tom Anderson wrote:
    >> On Tue, 18 Nov 2008, Arne Vajhøj wrote:
    >>> 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.
    --
    John W. Kennedy
    Read the remains of Shakespeare's lost play, now annotated!
    http://pws.prserv.net/jwkennedy/Double Falshood/index.html
    John W Kennedy, Nov 19, 2008
    #19
  20. On Wed, 19 Nov 2008 18:29:50 -0500, Arne Vajhøj wrote:

    > Martin Gregorie wrote:
    >> 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.
    >

    My point exactly!


    --
    martin@ | Martin Gregorie
    gregorie. | Essex, UK
    org |
    Martin Gregorie, Nov 20, 2008
    #20
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Keith Patrick
    Replies:
    0
    Views:
    540
    Keith Patrick
    Jul 19, 2006
  2. richard
    Replies:
    2
    Views:
    464
    richard
    Jan 13, 2006
  3. Tony
    Replies:
    48
    Views:
    1,131
    Mathias Gaunard
    Dec 12, 2006
  4. J.Ram
    Replies:
    7
    Views:
    641
  5. Michael Tan
    Replies:
    32
    Views:
    937
    Ara.T.Howard
    Jul 21, 2005
Loading...

Share This Page