[Java]遍历字符串.length(), .charAt(); 输入一句话,输出包含的vowel

 

public class CharAt
{
    public static void main(String[] args)
    {
        String ac = "Hello World";
        //for (int i = 0; i < ac.length(); i++)
        int i = 0;
        //while (i < ac.length())
        
        do {
            System.out.println(ac.charAt(i));
            if (ac.charAt(i) == 'o')
                break;
            i++;
        } while (i < ac.length());
    }
}

 

 

.length(), .charAt()

 

熟悉三种循环

do-while

while

for

 

 

/*
input a sentence and print all the vowels in that sentence.
1. how to loop through a string
*/

import java.util.Scanner;
public class ArrayLoop
{
    public static void main(String[] args)
    {
        var scan = new Scanner(System.in);
        System.out.println("Enter a sentence: ");
        String sent = scan.nextLine();
        for (int i = 0; i < sent.length(); ++i)
        {
            char ch = sent.charAt(i);
            if (isVowel(ch))
                System.out.print(ch);
            else
                System.out.print("");
        }
    }

    static boolean isVowel(char ch)
        {
            switch(ch)
            {
                case 'a': case 'e' : case 'i': case 'o': case 'u': return true;
                default: return false;
            }
        }
}

 

posted @ 2020-06-07 08:36  profesor  阅读(321)  评论(0编辑  收藏  举报