JAVA PROGRAMMING: hasVowels2 sample code



Definition and Usage

The indexOf() method returns the position of the first occurrence of specified character(s) in a string.

Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.


Syntax

There are 4 indexOf() methods:

public int indexOf(String str)
public int indexOf(String str, int fromIndex)
public int indexOf(int char)
public int indexOf(int char, int fromIndex)

Parameter Values

ParameterDescription
strString value, representing the string to search for
fromIndexAn int value, representing the index position to start the search from
charAn int value, representing a single character, e.g 'A', or a Unicode value

Technical Details

  
Returns:An int value, representing the index of the first occurrence of the character in the string, or -1 if it never occurs

hasVowels java code Examples

import java.util.Scanner;

public class has_vowels_2
{  
  public static boolean has_vowels(String s)
  {
    for (int i = 0; i < s.length(); i++)
    {
      if ("aeiouAEIOU".indexOf(s.charAt(i)) >= 0)
      {
        return true;
      }
    }
    
    return false;
  }

  public static void main(String[] args) 
  {
    Scanner in = new Scanner(System.in);
    System.out.printf("Enter a word: ");
    String word = in.next();
    boolean result = has_vowels(word);
    System.out.printf("result = %b\n", result);
  }
}


Post a Comment

0 Comments