我需要编写一个程序来计算字符串中的某些标点符号。我有这个代码我认为可以工作,但在每个charAt,我有一个错误,说分配的左手必须是一个变量。需要帮助解决这个问题
public static void main(String[] args)
{
Scanner kbd = new Scanner (System.in);
System.out.println("Enter a string: ");
String s = kbd.next();
countPunctuation(s);
}
public static int countPunctuation(String s)
{
int periodCount = 0;
int commaCount = 0;
int semicolonCount = 0;
int colonCount = 0;
int exclamationCount = 0;
int questionCount = 0;
int total = 0;
for(int i = 0; i < s.length(); i++)
{
if(s.charAt(i) = ".")
{
periodCount++;
total++;
}
if(s.charAt(i) = ",")
{
commaCount++;
total++;
}
if(s.charAt(i) = ";")
{
semicolonCount++;
total++;
}
if(s.charAt(i) = ":")
{
colonCount++;
total++;
}
if(s.charAt(i) = "!")
{
exclamationCount++;
total++;
}
if(s.charAt(i) = "?")
{
questionCount++;
total++;
}
}
System.out.println("There are " + periodCount + " periods in this String.");
System.out.println("There are " + commaCount + " commas in this String.");
System.out.println("There are " + semicolonCount + " semicolons in this String.");
System.out.println("There are " + colonCount + " colons in this String.");
System.out.println("There are " + exclamationCount + " exclamation marks in this String.");
System.out.println("There are " + questionCount + " quesiton marks in this String.");
return total;
}
答案 0 :(得分:2)
平等检查是==
而不是=
。您需要具有if(s.charAt(i) == '.')
之类的内容,或者您可以在这种情况下使用switch:
for(int i = 0; i < s.length(); i++) {
switch(s.charAt(i)) {
case '.':
periodCount++;
break;
case ',':
commaCount++;
break;
... // similar conditions for others
}
total += 1;
}
答案 1 :(得分:1)
如果这会有帮助,请点击,但我发现了一个小错误
更改:
String s = kbd.next();
要:
String s = kbd.nextLine();
我认为这绝对应该解决它。
为什么:
next(); -is mostly used for characters, as it doesn't get the whole line.
nextLine(); -gets the entire line, which for your code, you'd want.
就像那个人说的那样,你的使用
= -instead of- ==
&#34; =&#34;用于指定的变量和东西 &#34; ==&#34;是检查,如if(String s ==&#34;;&#34;)