Close
Close

How do you print just the first word with a for loop?

   Bethany Belbin

Write a for statement that prints only "Hi" from the array you created in Question#5.

This is what I have so far

public static void main(String[] args) {
      

// Question 5
        String welcome = "Hi There";
        
        char[] arr = welcome.toCharArray();
        
        for(int i = 0; i< welcome.length(); i++) {
            
            System.out.print(" "+arr[i]);
            
        } //end of for loop
        

// Part 2
        for(int x = 0; x < welcome.length(); x++) {

            
        } // end of second for loop
        
    } // end of main method
    
} // end of class


Answers

  •   

    Probably this is what you want:

    class Ans{
      public static void main(String[] args){
    
      	String st = "Hi There";
    
      	boolean found = false;
    
      	for(int i = 0;i<st.length()-1;i++)
      	{
      		//if next character is a space
      		if(st.charAt(i+1) == ' '){
      			System.out.println(st.substring(0,i+1));
      			found = true;
      			break;
      		}
      	}
    
      	//if the sentence is only one word long
      	if(found == false)
      	{
      		System.out.println(st);
      	}
    
      }
    }
    

     



Ask Yours
Post Yours
Write your answer