每当我输入我的句子时,它会在每次循环时打印出结果。我假设我必须把打印线放在循环外面?
import java.util.*;
public class homework4{
public static void main(String[] args) {
//Scanner
Scanner keyBd = new Scanner(System.in);
System.out.println("Enter a sentence ");
String userIn = keyBd.nextLine();
int count = 0;
String empty= "";
//Code
for (int i = 0; i < userIn.length(); i++) {
char ch = userIn.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
count++;
System.out.println("There are " + count + " vowels in this string");
}
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
count++;
empty += ch + " ";
System.out.println("The vowels are: " + empty);
}
}
}
}
答案 0 :(得分:1)
matrix
无需检查条件两次。当您在循环中更新变量(import java.util.*;
public class homework4{
public static void main(String[] args) {
//Scanner
Scanner keyBd = new Scanner(System.in);
System.out.println("Enter a sentence ");
String userIn = keyBd.nextLine();
int count = 0;
String empty= "";
//Code
for (int i = 0; i < userIn.length(); i++) {
char ch = userIn.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
count++;
empty += ch + " ";
}
}
System.out.println("There are " + count + " vowels in this string");
System.out.println("The vowels are: " + empty);
}
}
&amp; count
)时,必须在退出循环后只打印一次。
答案 1 :(得分:0)
您不需要两次测试元音吗? (并且只添加count
两次),只有一次: -
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'){
count++;
empty += ch + " ";
}
每次找到元音时,您的打印声明都不需要发生: -
for (int i = 0; i < userIn.length(); i++) {
// not in here
}
System.out.println("There are " + count + " vowels in this string\n" + "The vowels are: " + empty);
<强>另外... 强>
如果这里的陈述很丑陋,那里有很多条件。交换机更容易阅读,效率更高: -
switch (ch){
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
case 'o': case 'O':
case 'u': case 'U':
count++;
empty += ch + " ";
break;
}
或将整个条件移动到方法
public boolean isVowel(char c){
return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U');
}
并使用
if (isVowel(ch)){
//...
}
答案 2 :(得分:0)
你只需要将print语句移到外面,如果计数仍然为零则设置检查条件,则表示没有元音,如果count不为零,则可以打印它。
<ImageView
android:id="@id/img"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitCenter" />
}