Search code examples
javafor-loopreturnsubstringstring-length

Returning a string that begins at the input parameter index of the String


The Method name is getTheString()

The Return type is String

And the Input parameters is int

I have to return a string that begins at input parameter index position of the String str which is the instance variable. Returns empty string if the input parameter index position is larger than or equal to the string length.

An example would be

If str = “Hawaii”

getTheString(8) returns “ “

getTheString(2) returns “waii”

I don't know why nothing happens when I execute it or how to fix it could someone help.


public class LoopM
{
   public int a, b;
   public String str;
   
   public LoopM(){
    }
   
   public String getTheString(int f){
       
       str = "Hawaii";
       
       int length = str.length();
       
       for(f = length; f < 10; f++){
           
           return str.substring(f);
        }
       
       return str.substring(f);
    }
   
   public static void main(String args[]){
       //used for testing

       LoopM me = new LoopM();
       me.getTheString(2);
      
    }
}





Solution

  • Update to this :

    public class Test {
        public static void main(String[] args) {
            System.out.println(getTheString(2));
        }
    
        public static String getTheString(int f) {
    
            String str = "Hawaii";
    
            return (f > str.length() || f < 0) ? "" : str.substring(f);
        }
    
    }
    

    Output :

    waii