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; } } }