我在显示输出时遇到问题。我想打印出来,以便它首先显示数字而不是字母。例如,当我输入“ WWWHJJJ”时,它会显示为“ W3HJ3”,而我希望它显示为“ 3WH3J”。
import java.util.Scanner;
public class CompressString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter string: ");
String str = sc.nextLine();
System.out.println("Entered input: " + str);
String encode = "";
char ch=0;
int count=1;
for (int i = 0; i < str.length(); i++)
{
if (ch == str.charAt(i))
{
count = count + 1;
}
else
{
encode = encode + ch;
if(count != 1)
{
encode = encode + count;
}
ch = str.charAt(i);
count = 1;
}
}
encode = encode + ch;
if(count != 1)
{
encode = encode + count;
}
System.out.println("Encoded: " + encode);
}
}
答案 0 :(得分:1)
这似乎很明显:
encode = encode + ch;
if(count != 1)
{
encode = encode + count;
}
附加字符,然后加上计数。只需颠倒顺序:
if(count != 1)
{
encode = encode + count;
}
encode = encode + ch;