首页 > 解决方案 > 如何将括号括在百分比周围?

问题描述

我正在处理一项关于在字符串中显示元音和数字的数量的任务。输出是正确的,除了我不确定如何显示下面显示的结果:

Enter a String: testing12345

Number of vowels is: 2 (16.67%)

Number of digits is: 5 (41.67%)

当我处理我的代码时,结果显示如下:

Enter a String: testing12345

Number of vowels is: 2()16.67%

Number of digits is: 5()41.67%

我想知道如何用括号括住百分比,下面附上我的代码:

import java.util.Scanner;

public class CountVowelDigit {    
    public static void main(String[] args) {    

        //Counter variable to store the count of vowels and consonant    
        int vCount = 0, cCount = 0;    
        String inStr;
        int inStrLen;
        double totalDigitPercentage = 0.0;
        double totalVowelPercentage = 0.0;

        Scanner in = new Scanner(System.in);
        System.out.print("Enter a String: ");
        inStr = in.next().toLowerCase();
        inStrLen = inStr.length();

        for (int i = 0; i < inStrLen; i++) {    
            char ch = inStr.charAt(i);
            //Checks whether a character is a vowel    
            if(ch == 'a' || ch == 'e' || ch == 'i' || ch== 'o' || ch == 'u') {    
                //Increments the vowel counter    
                vCount++;    
            }    
            //Checks whether a character is a consonant    
            else if(ch >= '0' && ch<='9') {      
                //Increments the consonant counter    
                cCount++;    
            }    

            totalVowelPercentage = 100.0*vCount/inStr.length();
            totalDigitPercentage = 100.0*cCount/inStr.length();
        }    

        System.out.println("Number of vowels is: " + vCount + "()" + String.format("%.2f",totalVowelPercentage) + "%");   
        System.out.println("Number of digits is: " + cCount + "()" + String.format("%.2f",totalVowelPercentage) + "%");
    }    
} 

标签: java

解决方案


该格式可能包含模板文本,并且有一个格式化printfSystem.out

    System.out.printf("Number of vowels is: %d (%.2f%%)%n",
            vCount, totalVowelPercentage);   
  • %%是自我逃逸百分比。
  • %n是最后自动添加的行分隔符println。在 Windows 上\r\n

错误是有"()" + String.format(...)而不是"(" + S... + ")".


推荐阅读