0

I am new to java and I barely have the time to study it. Actually, my question is a little bit awkward and meaningless. I am trying to get letters from user input. I know that there are more efficient ways to do it, but I only want to know what is wrong with this method. The problem is when I write a string that doesn't contain any space the program is fine but if I write one with spaces it stops work.

Scanner qx = new Scanner(System.in);
String a = qx.next();
for(int b = 0; b<a.length();b++){
    char z = a.charAt(b);
    System.out.print(z + " ");
    }

For example: When I wrote "Hi there" (without quotes)
I expect the output of "H i t h e r e"
But it only shows "H i "
İf I would have written "Hithere" it would show "H i t h e r e "
So why is there a difference between the one has spaces and the one doesn't?
Also, I am sorry for my grammar. I tried to do my best but I haven't practised for a long time.

Stephan Hogenboom
  • 1,309
  • 2
  • 13
  • 23
Metin Usta
  • 85
  • 1
  • 5

4 Answers4

1

I had these same problems when started to code in java. Like reading inputs which are mixed with integer and string.

For Ex :

if you want to read...

5 // as an Integer
Hi there // as a string

you have to code like this

Scanner in = new Scanner(System.in);
int number = in.nextInt();
in.next();
String str = in.nextLine();

I put that extra in.next() to move the buffer to the next line (as it would be only at the end of the same line after reading an integer number).

So, now coming to your question, next() will just read the bytes until the whitespace occurs. so if you want to read one full line of input you have to use nextLine(). nextLine() will read the whole line.

Ramanan
  • 11
  • 3
0

next returns any string up to a whitespace character (space, tab, enter).

You need to use nextLine which returns any string up to a carriage return (aka enter).

Bunyamin Coskuner
  • 7,831
  • 1
  • 23
  • 43
0

That's how .next() works. It takes string until first space. This will work for you:

String a;
while(qx.hasNext){
a = a + qx.next();
}

And then continue with your loop.

Said
  • 600
  • 5
  • 18
-1

this code will help you to extarct the exact substring from your main string

public static void main (String [] args) {

Scanner input = new Scanner (System.in);
System.out.println("Enter a String");
String name = input.next();
/*from this line it will extract the charcter from the string
 * according to tour indexes given
 */
String subString = name.substring(0, 3);
System.out.println("Substring is :"+subString);

}
uvindu sri
  • 104
  • 1
  • 10
  • I don't understand why this is answering the question. You are still getting only `"hi"` if you input `"hi there"`. And the substring with constant value doesn't help if I input "hello there" or worst `"a"` ... Can you explain why you think this is useful please ? – AxelH May 27 '19 at 06:13