我正在编写代码,使用循环计算给定输入中的空格/数字/字母数量。我试图使用.isdigit()和.isalpha()方法来查看字符串中的每个字母是字母还是数字,如果为true,则将其添加到计数中。我的代码看起来很完美,但是当我运行它时,我只得到长度和空格的计数(不使用.isspace()方法) 也许在我的循环中更新计数时我搞砸了但是再次......这对我来说都很好看,有没有人可以帮助引导我朝着正确的方向前进?
def main():
sentence = input('Enter a sentence: ')
printStats(sentence)
def printStats(input):
print('Statistics on your sentence: ')
print(' Characters:', charCount(input))
print(' Letters:', letterCount(input))
print(' Digits:', digitCount(input))
print(' Spaces:', spaceCount(input))
def charCount(input):
for char in input:
return len(input)
#Section below is where I need help
def letterCount(input):
count=0
for letter in input:
if input.isalpha():
count += 1
return count
def digitCount(input):
count=0
for digit in input:
if input.isdigit():
count += 1
return count
#Section above is where I need help
def spaceCount(input):
for space in input:
return input.count(" ")
main()
感谢您的时间
答案 0 :(得分:1)
package com.drools;
public class TEST {
public static void main(String[] args) {
int charCount = 0;
int digitCount = 0;
String word = "NEW YORK 1";
String data[];
int k = 0;
data = word.split("");
int data1 = word.length();
char temp;
for (int i1 = 0; i1 < word.length(); i1++) {
temp = word.charAt(i1);
if (Character.isLetter(temp)) {
charCount++;
} else if (Character.isDigit(temp)) {
digitCount++;
for (int i = 0; i < data.length; i++) {
if (data[i].equals(" ")) {
k++;
}
}
System.out.println("total count "+ data1 + "||number of spaces in the entire word "+ k + " ||characters " + charCount+ " || digits" + digitCount);
}
}}
}
**Out put:**
total count 10||number of spaces in the entire word 2 ||characters 7 || digits1
答案 1 :(得分:0)
您需要执行letter.isalpha()和digit.isdigit(),而不是在整个输入上调用它们。
答案 2 :(得分:0)
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LettersDigitsSpace {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Pattern pletter = Pattern.compile("[a-zA-Z]");
Pattern pdigit = Pattern.compile("\\d");
Pattern pwhitespace = Pattern.compile("\\s");
System.out.println();
System.out.println("-------------------------------------------------");
System.out.println("--- Letters, Digits, and White Spaces counter ---");
System.out.println("-------------------------------------------------");
System.out.println();
System.out.println("Enter String: ");
String val = input.nextLine();
Matcher mletter = pletter.matcher(val);
Matcher mdigit = pdigit.matcher(val);
Matcher mspace = pwhitespace.matcher(val);
int countl = 0, countd = 0, counts = 0;
while (mletter.find()) {
countl++;
}
while (mdigit.find()) {
countd++;
}
while (mspace.find()) {
counts++;
}
System.out.println("\nLetter count: "+countl+"\nDigit count: " + countd + "\nWhite Space count: " + counts);
}
}