首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >循环的逻辑问题

循环的逻辑问题
EN

Stack Overflow用户
提问于 2016-01-28 00:50:16
回答 2查看 37关注 0票数 0

我正在编写一个程序,它接受一个句子作为输入,创建一个这些单词的数组,并显示一个单词是冗余的还是不冗余的。

如果扫描到"Hello Hi Hello“,程序应该通知用户存在冗余。

代码语言:javascript
复制
public static void main(String[] args) 
{
    Scanner sc = new Scanner(System.in);
    String sentence ;
    System.out.println("Enter a sentence :");
    sentence = sc.nextLine();
    String[] T = sentence.split(" "); //split the sentence at each " " into an array

    int i=0, o=0 ; //iterators

    boolean b=false; //redundancy condition

    for(String s : T) // for each String of T
    {
        System.out.println("T["+i+"] = "+ s);

        while(b) //while there's no redundancy
        {
            if(o!=i) //makes sure Strings are not at the same index.
            {

                if(s==T[o])
                {
                    b=true; //redundancy is true, while stops
                }
            }
            o++;
        }
        i+=1;
    }

    if(b)   
    {
        System.out.println("There are identical words.");
    }
    else
    {
        System.out.println("There are no identical words.");
    }

}
EN

回答 2

Stack Overflow用户

发布于 2016-01-28 01:06:45

下面是可用的代码-

代码语言:javascript
复制
        while(o<T.length && !b)
        {
            if(o!=i)
            {

                if(s.equals(T[o]))
                {
                    b=true;
                }
            }
            o++;
        }
        i+=1;
    }
票数 0
EN

Stack Overflow用户

发布于 2016-01-28 01:49:33

我刚修好了!

我实际上搞乱了布尔值x),我没有意识到While(false)不能循环,但While(b==false)可以。

代码语言:javascript
复制
boolean b=true;
    for(String s : T)
    {
        System.out.println("T["+i+"] = "+ s);
        int o = 0;
        while(b && o<T.length)
        {
            if(o!=i)
            {

                if(s.compareTo(T[o])==0)
                {
                    b=false;
                }
            }
            o+=1;
        }
        i+=1;
    }

谢谢你们!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35043316

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档