-2

I am writing a very simple program to input a string with space and then output it, my problem is, it not printed out fully as I expected.

Here is my code, as you can see, very simple

import java.util.Scanner;
public class Testjapanese {
public static void main(String[] args) {
    String x;
    Scanner keyboard = new Scanner(System.in);
    System.out.println(" Add a string");
    x = keyboard.next();
    System.out.println(x);
    }
}

For example, it print "Add a string" but when I input a string "Today is very", it gave me "Today", not "Today is very".

I search and they said to me that I should use input.nextLine(), but I do not know how to use it. May be I must use public java.lang.String nextLine() first ?

Sorry if my question is easy to solve. Thank you for your answer.

  • 1
    "_I search and they said to me that I should use input.nextLine()_" - yes, exactly. "_but I do not know how to use it_" - just like you use `next()` right now, simply replace `next()` with `nextLine()`. This will then read the whole line, including all whitespaces, and assign the read `String` to `x`. – maloomeister Sep 28 '21 at 11:16
  • Also this should help: https://stackoverflow.com/questions/39514730/how-to-take-input-as-string-with-spaces-in-java-using-scanner – rjdkolb Sep 28 '21 at 11:17

2 Answers2

0
import java.util.Scanner;
public class MyClass {
    public static void main(String args[]) {
      String x;
    Scanner keyboard = new Scanner(System.in);
    System.out.println(" Add a string");
    x = keyboard.nextLine();
    System.out.println(x);
    }
}
Kamèl Romdhani
  • 342
  • 1
  • 9
-1

You should just replace next with nextLine as below

 public static void main(String[] args) {
    String x;
    Scanner keyboard = new Scanner(System.in);
    System.out.println(" Add a string");
    x = keyboard.nextLine();
    System.out.println(x);
}
Sujit Sharma
  • 110
  • 10