почему этот метод убирает последнюю букву в строке? - PullRequest
0 голосов
/ 07 августа 2020

Это часть проекта java, мы должны взять предложение, в котором есть несколько пробелов между мирами (a sentence like this), и преобразовать его в массив символов, а затем распечатать предложение без всех лишних пробелов. . Он работает, но выводит предложение без последней буквы. Класс предложения:

public class sentences {
    
    String sentence;
    int length;
    private char[] ch;
    
    public sentences(String sentence, int length) {
        this.sentence = sentence;
        this.length = length;
        char [] ch;
    }

    /**method that takes a string and turns it into an array then prints out the array
     * makes an empty string and fills it with the char, takes out empty spaces
     * 
     */
    
    public char[] makesentenceanarray(String sentence, int length) {
        char[] ch = new char[sentence.length()];
        //String noWhite = "";
        StringBuilder s = new StringBuilder();
        char prevchar = ' ';
        for (int i = 0; i < sentence.length(); i++) {
            ch[i] = sentence.charAt(i);
        }     
         for(int j = 0; j < sentence.length(); j++) {
             char currentchar = ch[j];
             
             if( !(prevchar == ' ' && currentchar == prevchar)) {
                 s.append(prevchar);
                
             }
             prevchar = currentchar;
         }
         
         s.deleteCharAt(0);
        
        System.out.println(ch);
        System.out.print(s);
        return ch;      

            
        }
        
    }
    

Класс тестера:

import java .util.Scanner;

publi c class tester {

public static void main(String [] args) {
    
    Scanner scan = new Scanner(System.in);
    System.out.print("enter your sentence: ");
    
    String a = scan.nextLine();

    sentences s1 = new sentences(a, a.length());
    s1.makesentenceanarray(a, a.length());
        
    }

}

********************************************************************************
heres what I end up with:


enter your sentence: this  is   my    sentence
this  is   my    sentence 
this is my sentenc

любая помощь приветствуется, спасибо!

Ответы [ 3 ]

0 голосов
/ 07 августа 2020

Вы добавляете предыдущий символ. Вместо этого подумайте об обстоятельствах, при которых вы бы добавили текущий символ. В вашем l oop вы будете смотреть на каждый текущий символ, но для самого последнего символа предыдущий будет предпоследним символом, а затем l oop остановится. Имеет смысл?

0 голосов
/ 07 августа 2020

offer.length () начинает отсчет с 1. (Да, я знаю, что это непоследовательно: D) Поэтому вам нужно начать отсчет с 1 и сравнить с <= первым для l oop. </p>

 public char[] makesentenceanarray(String sentence, int length) {
        char[] ch = new char[sentence.length()];
        //String noWhite = "";
        StringBuilder s = new StringBuilder();
        char prevchar = ' ';
        for (int i = 1; i <= sentence.length(); i++) {
            //you should do this now bc of the change of the for loop: 
            //ch[i - 1] = sentence.charAt(i - 1);
            ch[i] = sentence.charAt(i);
        }     
         for(int j = 0; j < sentence.length(); j++) {
             char currentchar = ch[j];
             
             if( !(prevchar == ' ' && currentchar == prevchar)) {
                 s.append(prevchar);
                
             }
             prevchar = currentchar;
         }
         //Now you should be able to delete this
         //s.deleteCharAt(0);
        
        System.out.println(ch);
        System.out.print(s);
        return ch;      

            
        }
        
    }
0 голосов
/ 07 августа 2020

После l oop добавьте prevchar. Также используйте StringBuilder.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...