简体   繁体   中英

Trying to return a value in a method created in an object and the method contains for loops and if statements but can't do it

So I am asked to write a program that reads a sentence from the user, reports and removes wrong repetitions if any. By wrong repetitions I mean that a word (or more) is repeated (two occurrences or more) and that these repetition are consecutive.

`

public class checker {
    
    private String sentence;
    
    checker(String sentence){this.sentence=sentence;}
    
    public String check(){
        
        String[] word = sentence.split(" ");
        
        for(int i=0; i<word.length; i++){
            for(int j=i+1; j<word.length; j++){
                if(word[i].equals(word[j])){
                    word[j]="error";}}}
        
        for(int i=0; i<word.length; i++) {
            if (!"error".equals(word[i])) {
                System.out.print(word[i] + " ");}}
        
        return "";}
}

***This is the output of my code: ***

Enter a Sentence: The operator did not not skip his meal The operator did not skip his meal BUILD SUCCESSFUL (total time: 12 seconds)

So my code does the job of finding the repeated words and prints the corrected version, but the problem is that I just can't find a way to make it print out like it is supposed to do in the sample run!

[Sample runs:

-Enter a sentence: The operator did not not skip his meal -The sentence includes wrong repetitions. -The sentence should be: The operator did not skip his meal

-Enter a sentence: Happy people live longer -There are no wrong repetitions]

**I do know my problem, every time I try to write a piece of code containing any time type of loops and if statements together I just don't know to extract what I want from the loop and conditional statements, I was trying to

`

for(int i=0; i<word.length; i++){
    for(int j=i+1; j<word.length; j++){
        if(word[i].equals(word[j])){
            System.out.println("The sentence includes wrong repetitions.\nThe sentence should be: ");
            word[j]="error";}
        else{
             System.out.println("There are no wrong repetitions");
            }
    }   
}

` but I know it'll print it every time the loop gets executed!

I would really appreciate a helpful tip that I can carry with me going forward!

Thanks in advance guys!**

You don't have any mechanism by which to store your valid words so you can print them in the format you need to after your sentence evaluation is complete. I recommend storing the valid words in a StringBuilder or ArrayList as you go so you can print the resulting string when you are ready.

Here is a sample program to accomplish this using a StringBuilder. You could also use an ArrayList and call String.join(" ", wordList); to create the sentence when finished.

final String sentence = "This is an invalid invalid sentence that that needs corrected";
final String[] words = sentence.split(" ");
StringBuilder sentenceBuilder = new StringBuilder();
for (int i = 0; i < words.length; i++)
{
    final String checkWord = words[i];
    final boolean lastWord = i == words.length - 1;
    final boolean duplicate = !lastWord && checkWord.equals(words[i + 1]);
    if (lastWord || !duplicate)
        sentenceBuilder.append(checkWord);
    if (!lastWord && !duplicate)
        sentenceBuilder.append(' ');
}
if (!sentence.equals(sentenceBuilder.toString()))
    System.out.printf("The sentence includes wrong repetitions.%nThe sentence should be: %s%n", sentenceBuilder);
else
    System.out.println("There are no wrong repetitions");

I faced the same problem in my assignment last week. I couldn't solve it but I had to submit something so I don't get a zero. The errors in my program is that there is a space left in place of the duplicated word, and it only detects two occurrences.

Here's the code i wrote:

 String [] n= s.split(" ");
   boolean check=false;
 
   for (int i=1;i<n.length;i++){
       String    temp=n[i-1];
       if (n[i].equals(temp) == true) {
       check = true;
           System.out.println("The sentence includes wrong repetitions.");
     n[i]="";
     System.out.print("The sentence should be: ");
   for(int j=0;j<n.length;j++) {
       System.out.print(n[j]+" ");
       
   }
       }
      
   }
   
   if (check == false)
            System.out.println("There are no wrong repetitions");   
    }
    
}

Let me know if you found the solution or if you can improve my code

The insturctor sent us the solution, adding it here for future reference:

/* 

CSCI300 - Solution of Assignment 1 Problem 2 */ package repetitions;

import java.util.Scanner;

public class Repetitions {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    boolean hasSuccessiveReptition = false; //Assume no repetitions
    
    System.out.print("Enter a sentence: ");
    // Read the whole sentence into one String:
    String sentence = scan.nextLine();
    
    //create an array of Strings to handle each word separately
    String[] words = sentence.split(" ");
    //Create a string to add non repetetive words to
    String repetitionFreeSentence = words[0];  // add the fisrt word

    for(int i = 1; i < words.length; i++)
        if(words[i].equalsIgnoreCase(words[i-1])) // compare successive words
            hasSuccessiveReptition = true;
        else // add the word to the corrected setence
            repetitionFreeSentence += " " + words[i];        
    if(hasSuccessiveReptition){
        System.out.println("The sentence includes wrong repetitions.");
        System.out.println("The sentence should be: " + repetitionFreeSentence);
    }
    else
        System.out.println("There are no wrong repetitions");
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM