我在编程方面经验很少,而且我现在正在大学学习第一门编程课程。我们在课堂上遇到一个问题,即编写一个程序,该程序生成一系列从1到6的随机数,并将括号括在一系列连续数字周围。例如,如果序列是12553124322223655631,程序将打印12(55)31243(2222)36(55)631。
这是我到目前为止的代码:
package inRun;
import java.util.Random;
public class Prob612 {
public static void main(String args []){
Random rand = new Random();
boolean inRun = false;
int i = 0;
int [] values;
values = new int[20];
while (i < values.length){
int j = rand.nextInt(7);
if (j > 0 && j <= 6){
values[i] = j;
i++;
}
}
for (i = 0; i < values.length; i++){
if (inRun){
if (values[i] != values[i + 1]){
System.out.print(")");
inRun = false;
}
}
if (inRun = false){
if (values[i] == values[i - 1]){
System.out.print("(");
inRun = true;
}
}
System.out.print(values[i]);
}
if (inRun){System.out.print(")");}
}
}
当我运行这个程序时,它打印序列,但没有括号。我认为我需要使用增强的for
循环,但我不知道如何使用这样的程序来实现这一点。任何见解将不胜感激。谢谢。
答案 0 :(得分:2)
你几乎解决了它。有两点需要注意:
(inRun = false)
应为( inRun == false )
。 这应该这样做。
boolean inside = false;
for (int i = 0; i < values.length; i++) {
if (inside) {
if (values[i] != values[i - 1]) {
System.out.print(')');
inside = false;
}
} else {
if (i < values.length - 1) {
if (values[i + 1] == values[i]) {
System.out.print('(');
inside = true;
}
}
}
System.out.print(values[i]);
}
答案 1 :(得分:0)
我给你另一个解决方案而不使用布尔值,但是使用两个for循环来找到匹配的连续数字。评论应该解释代码:
for (int i = 0; i < values.length; i++)
{
// store the number of consecutive numbers
int count = 0;
/* check if it's not the last element (avoid outOfBound Exception when you reach the last element)
and if there is a match */
if(i+1 < values.length && values[i] == values[i+1])
{
count++;
//print parenthesis and the first matching number
System.out.print("("+values[i]);
// use a second for to match all the possible consecutive equal numbers
for(int j = i+1; j < values.length; j++)
{
// same as before, check if it's not the last element and if there is a match
if(j+1 < values.length && values[j] == values[j+1])
{
count++;
System.out.print(values[j]);
}
else
{
// if you have a different value in the next array cell, then print value and close the match
System.out.print(values[j]+")");
/* assing to i the value of i + the number of matching consecutive numbers
to resume the first for from the next value after the series of consecutive numbers */
i = i + count;
// exit to avoid unnecessary loops
break;
}
}
}
// print if you have a single number
else
System.out.print(values[i]);
}