Click here to Skip to main content
15,890,897 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello, I need to make a program that prints "Word" until the user puts point , and find if the given word from the user is already given to say that is given and return the user to put new word.

Like:
Word: cat
Word: done
Word: cat // here it must say that this word is already given

What I have tried:

Java
Scanner sc = new Scanner(System.in);
        int count=0;
        String pass;
        String word = ".";
        String userWords = "";

        do {
            System.out.print("Word: ");
            pass = sc.nextLine();
              String[] sentence = pass.split(" ");
        }
        while (!(pass.equals(word)));
       String  sameWord = " ";
          boolean match = false;
        for (int i = 0; i < sentence.length; i++) {
            if (sentence[i].equals(pass)) {

               sentence[i] += pass + " ";
                match = true;
                sentence = pass.split(" ");
       // String= sentence[i];
                System.out.println("This word already exists!");
                return;
            }
            count++;
            if(count> sentence.length) {
                sentence=Arrays.copyOf(sentence,sentence.length+1);
            }

        }
        for(int j=0; j< sentence.length;j++) {
            System.out.println("All words:");
            System.out.println(sentence[j]);
            System.out.println();
        }
Posted
Updated 16-Dec-20 12:18pm
v3
Comments
Patrice T 16-Dec-20 15:09pm    
What is your problem with this code ?

1 solution

Your main problem is that your "logic" is "outside" the "do while" loop.

You need the code within the "do while" loop, or in a "subroutine" that you call from the "do while" loop.

And you should just "break out" with a "period", since your present code would execute what follows anyway.

Or maybe, you meant to use a "while" loop. Main difference is you "prime" a "while" loop.

while - C# Reference | Microsoft Docs[^]
 
Share this answer
 
Comments
CPallini 17-Dec-20 2:23am    
Hey Gerry, it is Java.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900