**结束。**此问题需要详细的调试信息。它目前不接受答案。
**想改进这个问题吗?**更新问题,使其成为堆栈溢出的主题。
上个月关门了。
改进这个问题
如何以“nxw”格式打印出特定数字的数字和数字本身。n是数字的频率,w是数字本身。
例如,如果用户的输入是1。输出为3x1。
如果用户的输入在第一行是1 1 1,在第二行是7 7 1 0。输出为3x1.2x7.2x1.1x0。没有空间。
注:
循环以点结束。
数字不必按特定顺序排列
用户可以输入任意多的数字。
例如,输入可以是第一行的11,第二行的7,7,1,0。。。等。
这是我目前的代码。但我知道这不是真的。
import java.util.*;
public class LaufLaengenKodierung {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int freq = 0;
int oldNum = 0;
int num = 0;
boolean first = true;
while(sc.hasNextInt()) {
int i = sc.nextInt();
if(i == oldNum) {
freq++;
num = i;
} else if(i != oldNum) {
freq = 1;
oldNum = i;
num = i;
if(first) {
first = false;
num = i;
freq = 1;
}
}
}
System.out.print(freq + "x" + num + ".");
sc.close();
}
}
2条答案
按热度按时间nr9pn0ug1#
您必须保存每个数字的计数。可以通过创建
int
大小为10的数组,用于数字0
至9
. 然后是一个简单的循环,就像然后检查数组中的每个元素,并在大于0时输出数字的计数。它可以是这样的:
请记住,您必须检查用户输入的数字是否在0到9的限制范围内,否则会遇到错误
ArrayIndexOutOfBoundsException
s。svmlkihl2#
现有代码需要稍微重构,以便在相同值的子序列结束时立即打印频率和整数值。
测验:
输出:
如果只需要计算单独的数字(而不是整数),则更新,例如输入
11 11 11
应转换为6x1.
而不是3x11.
如上所示,应重构该方法以处理数字中的数字:测试输出:
"11 11 11", "112 223", "1 1 1\n7 7 1 1 0", "0 0 0"
:两种方法的在线演示
printRLE
以及printRLEDigits