[Java] Program cannot count spaces placed after a newline when counting spaces in a string
On 11/30/2022 at 2:02 PM, FakeKGB said:For my CS class (it's Java because CollegeBoard), I'm attempting to create a program that counts all the spaces in a given block of text. Said block of text includes newlines, which my code isn't parsing.
Here's my code:
import java.util.*; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); // get ready to receive text System.out.print("Paste your text here:"); String str = input.nextLine() // places given text into a string int length = str.length(); int space = 0; for(int i=0; i<length-1; i++) { if(str.charAt(i) == ' ') { space++; } } System.out.println(space);When given any length of text without newlines, it parses it perfectly. example:
for real this should work why doesnt it ok maybe it does work what if i add a newline^^ This returns 18, which is how many spaces there are.
But if I add a newline, to make the text this:
for real this should work why doesnt it ok maybe it does work what if i add a newlineit returns 12 spaces, which is how many spaces there are in the first line of text. It ignores all spaces in the second line.
Why is this happening? It should just ignore the \n and parse the rest of the spaces but it's not and I can't figure out why.
Note: I won't be able to test solutions until tomorrow, I'm writing this as my CS class ends
Thanks!
From the docs:
Quote
nextLine()
Advances this scanner past the current line and returns the input that was skipped.
From: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Which to my mind means that @Eigenvektor is correct. You'd need to repeatedly invoke
input.nextLine()
in a loop until such time as there is no further input. Meanwhile, you'd concatenate each line into your string. Look into
Scanner::hasNextLine()
and use a while loop.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now