java - Java while循环文本格式化
问题描述
输入
Hi.
Bye.
#
实际输出:
h(1)i(1)
预期产出:
h(1) i(1)
b(1) e(1) y(1)
两个项目之间必须有间隙。我如何需要修改我的while
循环以#
指示停止?
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
int a[] = new int[26];
Scanner sc = new Scanner (System.in);
String str = sc.nextLine();
for (char ch : str.toCharArray())
if (ch >= 65 && ch <= 90)
a[ch - 65]++;
else if (ch >= 97 && ch <= 122)
a[ch - 97]++;
for (int i = 0; i < 26; i++)
if (a[i] > 0)
System.out.print((char)(i + 97) + "(" + a[i] + ")");
}
}
解决方案
First question
Seems you just need to add a space at the end of the print. You have this:
System.out.print( (char)(i+97)+ "(" + a[i]+")");
It should be:
System.out.print( (char)(i+97)+ "(" + a[i]+") "); // Added a space at the end.
Or you could also print the space later:
System.out.print( (char)(i+97)+ "(" + a[i]+")");
System.out.print(" ");
Second question
About the while-loop, you could wrap what you have within the loop and should work, something like:
// This will be used for the initial value ONLY, in your example, it should be the "Hi"
String str = sc.nextLine();
while (!str.equals("#")) {
int a[]=new int[26];
for(int i = 0; i<str.length();i++) {
if(str.charAt(i)>=65 && str.charAt(i)<=90) {
a[str.charAt(i)-65]++;
}
else if(str.charAt(i)>=97 && str.charAt(i)<=122) {
a[str.charAt(i)-97]++;
}
}
for(int i=0;i<26;i++) {
if(a[i]>0) {
System.out.print( (char)(i+97)+ "(" + a[i]+")");
}
}
System.out.println(); // Printing new line to split next output
// This will be for the next inputs you have, in your example: "Bye" and "#"
str = sc.nextLine();
}
推荐阅读
- php - 计算项目的总价格
- search - 如何向现有的手风琴搜索代码添加搜索按钮?
- python - 根据奇/偶条件添加新列
- javascript - 笑话:如何使用 MongoDB 正确测试 Javascript 服务
- azure - 向我们的发布管道添加了无代理作业,但它失败了
- selenium - 使用 selenium 进行测试:chrome screensharing 自动选择选项卡并与音频共享
- java - 对一组名称和日期进行排序
- node.js - 在测试控制台上测试时,我的谷歌操作非常有效,但在实际设备上却没有
- sql - 使用 PATINDEX 在 SQL Server 中提取子字符串?
- php - 如何使用 .htaccess 在 WordPress 中增加最大上传文件大小