java - 如何将括号括在百分比周围?
问题描述
我正在处理一项关于在字符串中显示元音和数字的数量的任务。输出是正确的,除了我不确定如何显示下面显示的结果:
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) + "%");
}
}
解决方案
该格式可能包含模板文本,并且有一个格式化printf
为System.out
:
System.out.printf("Number of vowels is: %d (%.2f%%)%n",
vCount, totalVowelPercentage);
%%
是自我逃逸百分比。%n
是最后自动添加的行分隔符println
。在 Windows 上\r\n
错误是有"()" + String.format(...)
而不是"(" + S... + ")"
.
推荐阅读
- angular - 如何解决 Angular 应用程序的浏览器缓存问题
- amazon-web-services - Athena 未收集 Amazon S3 中部分文件的结果
- vue.js - 网站冻结但仅适用于某些用户 - 不确定从哪里开始
- php - Hiding the version of Revive Adserver on IIS Webserver 10
- java - Choosing the right list for unknown numbers
- ruby - Stuck with rdoc: Any way to add indentation to call-seq?
- python - The video at python qt webbrowser no player
- javascript - 使用 javascript 在页面之间传输表格数据
- django - How to delete label of a form in Django
- arrays - MongoDB merge int arrays in one result