Results 1 to 2 of 2
  1. #1
    raffs03 is offline Member
    Join Date
    Sep 2012
    Posts
    41
    Rep Power
    0

    Default if-else prob help....

    Java Code:
    int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int sch = Integer.parseInt(JOptionPane.showInputDialog("Enter the value to search:"));
    for(int j : nums){
        int p = j == sch ? 30: 0;
        if(j == sch){
            JOptionPane.showMessageDialog(null,"The Value " + j + " is in the Array " + p);
            break;
        }
        
        else{
            JOptionPane.showMessageDialog(null," The Value: " + j + "is not on the array!" + p);
            break;
        }
    }
    My problem is when i put else statement the value of j is not changing it's always 1 but when i erase the else statement the program works that it should be.
    What's is my error.
    Can some pinpoint it?

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,336
    Blog Entries
    7
    Rep Power
    20

    Default Re: if-else prob help....

    If the first number isn't equal to the wanted number then it doesn't mean that number is not in the array (it could be the second or third number or ...); put that else statement after the loop if the number wasn't found in that loop. (you probably need a small boolean flag 'found')

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. Can anyone help? image prob
    By Ritheal in forum Java Applets
    Replies: 3
    Last Post: 04-20-2012, 09:27 AM
  2. Compilin prob
    By imu09 in forum CLDC and MIDP
    Replies: 20
    Last Post: 04-30-2011, 07:47 PM
  3. Lil prob
    By imu09 in forum CLDC and MIDP
    Replies: 8
    Last Post: 04-28-2011, 05:30 PM
  4. for each prob
    By kusumathatavarthi in forum New To Java
    Replies: 7
    Last Post: 05-21-2008, 01:00 PM
  5. Prob with an exercise
    By jhetfield18 in forum New To Java
    Replies: 4
    Last Post: 02-15-2008, 06:11 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •