1

我怎样才能使一些数字正确合理?我不明白。我对Java真的很陌生。:-/ 例如,每当我尝试使此代码正确合理时,它都会给我错误。这是我找到的一些示例代码:

import java.util.Scanner;

 public class JFindAlphabete
{
  static Scanner sc = new Scanner(System.in                                                      );

public static void main(String[] Theory)
{

    JWaffles MyWaffles = new JWaffles();

    MyWaffles.ProgramHeading();

    System.out.println("Enter a string:"                                                                                     );
    String SentenceContents = sc.nextLine(                                                                                   );

    int SpaceCount       = SentenceContents.length() - SentenceContents.replaceAll(" ", "").length(                          );
    int VowelCount       = SentenceContents.length() - SentenceContents.replaceAll("(?i)[aeiou]", "").length(                );
    int ConsonantCount   = SentenceContents.length() - SentenceContents.replaceAll("(?i)(?=[a-z])[^aeiou]", "").length(      );
    int SpecialCharCount = SentenceContents.length() - SentenceContents.replaceAll("(?i)[^a-z ]", "").length(                );
    int WordCount        = SentenceContents.trim().split("\\s+").length;




    System.out.println("There are " + VowelCount + " vowels in this sentance"                  );
    System.out.println("There are " + ConsonantCount + " consonants in this sentance"          );
    System.out.println("There are " + SpaceCount + " spaces in this sentance"                  );
    System.out.println("There are " + SpecialCharCount + " special characters in this sentance");
    System.out.println("There are " + WordCount + " words in this sentance"                    );






}
}
4

3 回答 3

1

使用System.out.format该类,例如,您可以在http://docs.oracle.com/javase/tutorial/java/data/numberformat.htmlSystem.out.format("There are %2d vowels in this sentence", vowelCount)阅读一个很好的教程

于 2012-07-09T00:32:50.467 回答
1

您可以使用System.out'printf方法代替println,并使用格式选项来正确调整您打印的值:

System.out.printf("There are %5d vowels in this sentance\n"     , VowelCount);
System.out.printf("There are %5d consonants in this sentance\n" , ConsonantCount);

等等。

于 2012-07-09T00:33:03.367 回答
0

看看java.util.Formatter

它允许您根据预定义的格式进行打印,包括固定宽度的数字(带有空格填充)。

这可能是您最接近“正确证明”这些数字的方法。

于 2012-07-09T00:32:28.640 回答