Reputation: 37
So there is this class project I'm working on. The goal is to remove the white spaces from the sentences. So far my code is okay, but instead of continuing the sentence with no spaces, it stops the output once a space is reached. Please help!
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String inputWords;
char space = ' ';
int i;
inputWords = scnr.next();
for (i = 0; i < inputWords.length(); ++i) {
if (inputWords.charAt(i) != space) {
System.out.print(inputWords.charAt(i));
}
}
}
}
Upvotes: 0
Views: 84
Reputation: 469
The loop is continuing to the end of input, it's not stopping when it reached space. The problem is the input is not taking the whole line, it takes just before space as a single word. Use, inputWords = scnr.nextLine(); instead of inputWords = scnr.next();
NB. You can consider other white space char while the goal is to remove the white spaces. example- tab
Upvotes: 0
Reputation: 163
Because you are getting just a word of a sentence, you should use scnr.nextLine function to get all the sentence.
Upvotes: 2