1

I wrote simple program that deletes letter or word from text. Everything works perfectly, but I can't write " " [space] in console. When I do that it does nothing. What should I write into console to tell it that I want to delete space from text?

import java.io.*;
import java.util.*;
public class StringDelete {
public static void main(String args[]) {
    String x = "bla bla bla";
            System.out.println(x);
    System.out.println("What do you want to delete?");
    Scanner sc = new Scanner(System.in);
    String fr = sc.next();
    int po = 0;
    int le = x.length();
    int i = 0;
    do {
        po = x.substring(i).indexOf(fr);
        if (po != -1) {
            x = x.substring(0, po+i) + x.substring(po+i + 1);
        }
        i += po;
    }while(i<le&&po!=-1);
    System.out.println(x);
}
}
Elrok
  • 333
  • 2
  • 3
  • 10
  • Code, please! No code, no help... – fge Apr 01 '16 at 13:16
  • 2
    Welcome to Stack Overflow! Your question is difficult to answer as it doesn't contain your code. You'll need to post your code so that people can look at it and point out where the problem is. It's preferred that you create a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). Also see [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask). You can use the [edit] button to update your question. Good luck! – Martin Tournoij Apr 01 '16 at 13:17
  • Possible duplicate of [Scanner doesn't see after space](http://stackoverflow.com/questions/19509647/scanner-doesnt-see-after-space) – Tiz Apr 01 '16 at 13:30

2 Answers2

0

You should replace the line String fr = sc.next(); with String fr = sc.nextLine();.

You can find more info here.

Community
  • 1
  • 1
Tiz
  • 680
  • 5
  • 17
0

Here:

String fr = sc.next();

You are using next() method.

When this method encounters a whitespace character, it returns the string before that character.

eg:

  • for "asd fgh" it returns asd".
  • for "xyz" it returns "xyz"
  • for " " it reurns ""(empty string)

Hence, when you write " "(space), the string before it is empty String, and it returns the empty string.

Instead of next(), use nextLine().

String fr = sc.nextLine();
dryairship
  • 6,022
  • 4
  • 28
  • 54