Results 1 to 2 of 2
  1. #1
    Spinalkord is offline Member
    Join Date
    Oct 2010
    Posts
    1
    Rep Power
    0

    Default Loop through array and check values...

    I have this array. I need to go through the array and compare two int variables. If both variables are the same then print all the variables that have the same value.

    If the variable is not the same/ does not exist then ask the user to try again.
    Java Code:
    import java.util.*;
    public class LoopMe {
        private static Scanner scan = new Scanner(System.in);
    
        public static void main (String args[])
        {
            int num1 [] = {1,2,3,4,5,6,6,7};
            int testVal;
            
            System.out.println("Enter a value");
            testVal = Integer.parseInt(scan.nextLine());
            for(int i =0; i<num1.length;i++)
                {
                    
                   if(testVal == num1[i])
                       {
                           System.out.println("Hi");
                           System.exit(0);
                       }                             
                }
            
    
            
        }
        
    }

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

    Default

    Quote Originally Posted by Spinalkord View Post
    I have this array. I need to go through the array and compare two int variables. If both variables are the same then print all the variables that have the same value.

    If the variable is not the same/ does not exist then ask the user to try again.
    If your code finds the value in the array it prints "Hi" and quits; that's not what your assignment asks for; you should register the fact that your code found an identical value and continue the search (a boolean variable perhaps?). If, after the search has finished and nothing was found your code should ask for another value. There should be a while loop around that for loop that does the search.

    kind regards,

    Jos

Similar Threads

  1. Adding up all values generated from a for-loop
    By BariMutation in forum New To Java
    Replies: 4
    Last Post: 10-10-2010, 05:31 PM
  2. question on how to check values before storing
    By SMHouston in forum New To Java
    Replies: 19
    Last Post: 09-21-2009, 10:54 PM
  3. Replies: 8
    Last Post: 08-27-2008, 10:45 PM
  4. Replies: 1
    Last Post: 01-10-2008, 01:18 AM
  5. Replies: 0
    Last Post: 11-30-2007, 11:55 PM

Tags for this Thread

Posting Permissions

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