Java - 向我的程序添加基本统计信息

时间:2015-03-17 19:24:52

标签: java java.util.scanner

我创建了一个小型扫描程序,用于删除输入短语的元音。它工作得很好,除了现在我需要添加一行显示一些简单的统计数据,但我不知道从哪里开始。

我目前拥有的内容:

public static void main(String[] args) {
    new Disemvoweler();
}

public Disemvoweler() {
    System.out.println("Welcome to the disemvoweling utility!\n");
    Scanner in = new Scanner(System.in);
    System.out.println("Enter your phrase: ");
    String input = in.nextLine(); // Take in the input.
    in.close(); // Close the scanner.

    System.out.println("\nYour disemvoweled phrase: "+input.replaceAll("[aeoiu]", ""));

输出

欢迎来到dismvoweling实用程序!

输入您的短语: 谢谢你的帮助!

你的不知名的短语:哇哇哇哇哇哇哇!

我尝试添加到输出中的内容:

从x减少到x个字符。减少率xx%

2 个答案:

答案 0 :(得分:1)

有时候有人应该回答这个问题:)别忘了向我老师打招呼:)

String reduced = input.replaceAll("[aeoiu]", "");
System.out.println("\nYour disemvoweled phrase: "+reduced);
System.out.println("Reduced from " + input.length() + " to " + reduced.length() +" characters. Reduction rate of " + ((double) reduced.length()/input.length() * 100)+"%");

答案 1 :(得分:0)

1)Count the number of vowels,然后

2)calculate the percentage differenceoriginal字符串之间modified ...

import java.util.Scanner;
class Disemvoweler {
public static void main(String[] args) {
    new Disemvoweler();
}

public Disemvoweler() {
    System.out.println("Welcome to the disemvoweling utility!\n");
    Scanner in = new Scanner(System.in);
    System.out.println("Enter your phrase: ");
    String input = in.nextLine(); // Take in the input.
    int inputLength = input.length();
    in.close(); // Close the scanner.
    int count = 0;
                int vowels = 0;
                int consonants = 0;
                for (int i = 0; i < input.length(); i++)
                {
                        char ch = input.charAt(i);
                        if (ch == 'a' || ch == 'e' || ch == 'i' || 
                                        ch == 'o' || ch == 'u')
                        {
                                vowels++;
                        }
                }
                    System.out.println("\nYour disemvoweled phrase: "+input.replaceAll("[aeoiu]", ""));
                    String disemvoweled = input.replaceAll("[aeoiu]", "");
                    int disemvoweledLength = disemvoweled.length();
                    double percent = Math.abs(100*((double)disemvoweledLength-(double)inputLength)/(double)inputLength);
                    System.out.println("Reduced from: " + inputLength + " to " + disemvoweledLength + " characters. Reduction rate of " + percent + "%");
        }
}

INPUT:

asda alsdkaslkd asdasda aldasdjadqweeq asdoiqowie

输出:

Your disemvoweled phrase: sd lsdkslkd sdsd ldsdjdqwq sdqw
Reduced from: 49 to 31 characters. Reduction rate of 36.734693877551024%