输入是“听着,琼斯先生,冷静下来。”
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userText;
int numPun = 0; //number of punctiation and spaces
// Add more variables as needed
userText = scnr.nextLine(); // Gets entire line, including spaces.
for (int i = 0; i < userText.length(); i++){
if ((userText.charAt(i) != ' ') && (userText.charAt(i) != ',') && (userText.charAt(i) != '.'));{
numPun++;
}
}
System.out.println(numPun);
}
}
我当前的输出是到29,这是整行的字符总数。预期输出应该是 21。我哪里出错了?
最佳答案
以杂散分号终止 if
,并使用 &&
NOT ||
在此答案的先前版本中,我指定使用 ||
而不是 &&
。不要那样做。感谢Basil Bourque's answer作为第一个指出这一点的人。
用途:
for (int i = 0; i < userText.length(); i++){
char current = userText.charAt(i);
if (current != ' ' && current != ',' && current != '.'){
numPun++;
}
}
在 if
语句表达式后面有一个额外的 ;
。
说明:
在此答案的先前版本中,表达式 current != ' ' ||当前!= ',' || current != '.'
等于 如果 current 不是空格、逗号或句点,请执行以下操作:
.
这意味着如果字符是逗号,它会在 numPun
上加 1,因为它不是空格。
在 new 表达式中,如果 current 不是空格、逗号且不是句点,则它等于。因此,它会首先检查它是否是空格,然后是逗号,然后是句号。
关于java - 计算不带空格、逗号或句点的输入数 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66727954/