2014-09-23 54 views
0

好吧,通过基于第一个值的所有值的条件循环

因此,我在说明这个问题时存在一些问题。或许以下示例更容易:

假设我们考虑四个季节:冬季,春季,夏季和秋季(按特定顺序)。而现在,我们有以下的文字想:

I love the Summer. 
The Winter is not a good season. 
Spring brings more joy. 
And Fall is the best. 

现在,假设我有一个程序,读取该文件,并在遇到第一个赛季(在这种情况下,夏季)取代所有其他赛季的第一个实例。然后,它会重复打印文本,这次是重复下一季,直到所有季节都被覆盖。

例如,上面的文字应该产生以下输出:

//..Replace with 'Summer' 
I love the Summer. 
The Summer is not a good season. 
Summer brings more joy. 
And Summer is the best. 
//.. Replace with 'Winter' 
I love the Winter. 
The Winter is not a good season. 
Winter brings more joy. 
And Winter is the best. 
//.. Replace with 'Spring' 
I love the Spring. 
The Spring is not a good season. 
Spring brings more joy. 
And Spring is the best. 
//.. Replace with 'Fall' 
I love the Fall. 
The Fall is not a good season. 
Fall brings more joy. 
And Fall is the best. 

但是现在,如果诗,原文如下:

I love the Fall. 
The Winter is not a good season. 
Spring brings more joy. 
And Summer is the best. 

该计划将通过更换的每个实例启动“秋季”,然后在冬季,春季和夏季也一样。 (自冬季,春季,夏季,秋季)是默认顺序。

总之:遇到的第一个季节是定义他“替换”行为的第一次迭代。也就是说,如果遇到“夏天”,则整个文本将其季节替换为夏季。然后是冬季,春季和秋季。如果首先遇到“春天”,则文本首先用“春天”,然后是冬天,夏天和秋天替换所有季节。

我知道人们可以通过编写一系列的条件语句,如做到这一点:

if summer 
    replace summer 
    replace winter 
    replace spring 
    replace fall 

else if spring 
    replace spring 
    replace winter 
    replace summer 
    replace fall 

else if winter 
    replace winter 
    replace spring 
    replace summer 
    replace fall 

else if fall 
    replace fall 
    replace winter 
    replace spring 
    replace summer 

然而,这似乎很难这样做的最佳方式。我知道在某个时候文本必须被所有季节取代。我也知道这些季节的顺序。唯一重要的是第一季的实例,然后决定哪个季节从它的位置被取出,并放在前面。

如果这个问题有任何意义,我会高度赞赏一些建议。我并不特别寻找代码,而是提供关于如何处理这样一个问题的提示。

谢谢你们。

回答

1

直截了当的办法是:

  1. 提取词语的出现顺序,并放置在列表中。
  2. 遍历该列表中的每个元素。
  3. 在该循环中,循环遍历每个可能的单词并将其替换为步骤2中的当前元素。
  4. 打印结果。

我没有做太多的Java,但这里有一个关于replacing multiple strings的回答,这可能会有用。

0

这样做的一种方法是将季节保留在列表中并正好四次读取列表。

  1. 列表迭代开始从本赛季第一次遭遇
  2. 回到开头,如果你到达列表的末尾4读取
0

您可以创建四季的有序列表(冬前,春季,夏季,秋季),然后当你遇到第一季重新排列那个列表时 - 在你的例子列表中会变成(Summer,Fall,Winter,Sprint)。

之后,所有你需要做的就是遍历重新排列的列表,并按照你所说的替换文本。