【发布时间】:2021-03-20 01:32:51
【问题描述】:
这是我第一次使用堆栈溢出,所以如果格式不正确,我很抱歉。对于一个 comp sci 项目,我必须对一个 40 项的随机数数组列表做一些不同的事情。
我正在努力完成的任务是:
计算相同数字的最长运行。仅当连续数字时才继续运行 具有相同的价值。然后打印重复的编号和运行的长度。(例如:最长运行的编号为:3,长度为:5。)
如果有超过一次的最大长度,请标记最后一个。打印以下列方式标记的最长运行的数组: 1 1 1 6 5 4 6 3 2 3 2 (3 3 3 3 3) 1 5 6 3 4 4 4
我真的不知道如何解决这个问题。即使只是一些伪代码也可能会有所帮助;我知道这些可能应该是 2 个不同的“for”循环,一个检测运行,另一个打印它。 我有一些朋友使用 Arrays 而不是 ArrayLists 完成的代码:
public String longestRun()
{
int maxRun=1;
int currentLen = 1;
int repeated = x[0];
for (int i =1; i< 40-1; i++)
{
if (x[i] == x[i+1])
currentLen++;
else
{
if (currentLen >= maxRun)
{
maxRun = currentLen;
repeated = x[i-1];
startRun = i-maxRun;
endRun = i-1;
}
currentLen = 1;
}
}
return "The longest run is " + maxRun + " and the repeated number is " + repeated ;
}
public String printParenth()
{
for(int i = 0; i<40; i++)
{
if(i != startRun+1 && i != endRun+1)
System.out.print(x[i]);
else if(i == startRun+1)
System.out.print("(" + x[i]);
else
System.out.print(x[i] + ")");
}
return "";
}
我知道如何创建 ArrayList、转换为字符串和打印等,这只是我不明白的一项任务。考虑到 ArrayList 方法的数量和实用性的增加,我认为使用 ArrayList 应该更容易。提前非常感谢,我真的很感激!
【问题讨论】:
标签: java for-loop arraylist iteration