首页 > 解决方案 > 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] + ")");    
    }       
}

标签: javawhile-loopdo-while

解决方案


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();
}

推荐阅读