对于学校我必须制作一个能够接受字符串输入并计算1“a”等元音量的扫描仪。我的问题是,当我输入一个字符串时,它不会通过循环和我可以连续输入,输入什么都不做。 (我正在使用BlueJ进行编码)。谢谢你的帮助!
package VowelCounter;
/**
* Description:
* Author: Jack Cannon
* Date: 11/15/16
*/
import java.util.Scanner;
public class VowelCounter
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
//Prompt the user to enter a phrase
System.out.println("Type in a sentence.");
String phrase = input.nextLine();
//as long as the string isn't "quit",
//count the vowels in the string.
int length = phrase.length();
while(phrase != "quit")
{
int a = 0;
int e = 0;
int i = 0;
int o = 0;
int u = 0;
for(int c = 0; length < 1; length++)
{
char vowels = phrase.charAt(c);
if(vowels == 'a')
{
}
else if(vowels == 'e')
{
}
else if(vowels == 'i')
{
}
else if(vowels == 'o')
{
}
else if(vowels == 'u')
{
}
}
}
System.out.println("There are " + 'a' + "a's");
System.out.println("There are " + 'e' + "e's");
System.out.println("There are " + 'i' + "i's");
System.out.println("There are " + 'o' + "o's");
System.out.println("There are " + 'u' + "u's");
//print out the count of the vowels for this string.
//prompt the user for another phrase.
}
}
答案 0 :(得分:1)
您在上面分享的代码存在一些问题。
首先,您的while循环的条件为phrase != "quit"
。出于两个原因,这是错误的。第一个是这不是你如何比较java中的字符串。为此,请参阅this。第二个原因是你永远不会在while循环中更改变量phrase
,因此这会导致无限循环,因为phrase
永远不会“退出”,除非这是用户输入的内容如果你只需要用户输入一次,我认为不需要这个while循环。
你的代码错误的第二个原因是你的for循环中的if语句(看看当前char是什么字符)什么都不做。在这一点上,它们只是空代码块。很可能你需要做的是增加适当的元音计数器。
最后,您在打印行中使用了不正确的字符串连接方法。在Java中连接的正确方法如下:
"There are " + a + "a's" // a = 1
=> "There are 1 a's"
使用单引号是不正确的;如果你想打印字母'a',你会使用它,如下所示:
"There are a a's"
答案 1 :(得分:0)
这应该解决你的问题,我只在循环中添加了2个if语句,你可以添加其余的。
public static void main(String [] args){
Scanner input = new Scanner(System.in);
//Prompt the user to enter a phrase
System.out.println("Type in a sentence.");
String phrase = input.nextLine();
//as long as the string isn't "quit",
//count the vowels in the string.
int length = phrase.length();
int a = 0;
int e = 0;
int i = 0;
int o = 0;
int u = 0;
while(!phrase.equals("quit")){
for(int c = 0; c<length; c++){
char vowels = phrase.charAt(c);
if(vowels == 'e'){
e++;
}
else if(vowels == "o"){
o++;
}
}
System.out.println("There are " + a + "a's");
System.out.println("There are " + e + "e's");
System.out.println("There are " + i + "i's");
System.out.println("There are " + o + "o's");
System.out.println("There are " + u + "u's");
System.out.println("enter another sentence");
phrase = input.nextLine();
}
}