如何才能正确调整数字?

时间:2012-07-09 00:29:52

标签: java

我怎么能让一些数字正确对齐?我不明白。我是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"                    );






}
}

3 个答案:

答案 0 :(得分:1)

使用System.out.format课程,例如System.out.format("There are %2d vowels in this sentence", vowelCount)您可以在http://docs.oracle.com/javase/tutorial/java/data/numberformat.html

阅读一本好的教程

答案 1 :(得分: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);

等等。

答案 2 :(得分:0)

看看java.util.Formatter

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

这可能是你最接近'正确证明'这些数字。