954,523 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How can i exit the for loop prematurely that am using to read arrays arguments

public  void readArguments(String[]args ) {
         
         
        String [] readArray = new String[ 10 ]; 
        Scanner readscanner=new Scanner(System.in); 
         
        // read values from keyboard into array 
        System.out.println("Enter your arguments or type Exit to exit the loop");
         for ( int i = 0 ; i <  readArray.length ; i ++) { 
                 
                             
                 if(readArray[i] =="Exit" ) break;                                    
                 readArray[i] = readscanner.nextLine();
                 
                 
          }              
              
   //Determine if the number of Arguments is less or greater than 5
               if(readArray.length<=4 ){
                  
                  System.out.println("There are less than 5 arguments passed");
                }
                 else {
                       System.out.println("More than 5 arguments passed");         
              
              
             
                 
        
       } 
    }
betny
Newbie Poster
20 posts since Aug 2011
Reputation Points: 10
Solved Threads: 0
 

First, when you do "if(readArray[i] =="Exit" ) break;", you don't actually check the value of the string, rather the position in the memory. To check the actual value, use readArray[i].equals("Exit").

Second, you need to place your if statement after your input. As it is now, at your if statement, readArray[i] is null, since you haven't done anything with it yet. So your if-statement will never be true.

Aviras
Junior Poster in Training
82 posts since Jul 2008
Reputation Points: 24
Solved Threads: 8
 

Wow!! thank you very much. its working now.

betny
Newbie Poster
20 posts since Aug 2011
Reputation Points: 10
Solved Threads: 0
 

Another option would be to use a while loop.

hfx642
Posting Pro
515 posts since Nov 2009
Reputation Points: 248
Solved Threads: 105
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: