2

I'm new in Java, and i can't figure out why this code doesn't work (no error but nothing displays on the console).

Thanks

import java.util.Scanner;


public class HelloWorld {
    public static void main(String[] args) {


    Scanner sc = new Scanner(System.in);

    String str2 = sc.nextLine();

    System.out.println("Please write something : ");

    System.out.println("You wrote : "+str2);

}

}
Addon
  • 75
  • 1
  • 1
  • 9

3 Answers3

3

You must enter something and hit enter in order to see any output.

You might want to print the prompt before calling nextLine :

System.out.println("Please write something : ");
String str2 = sc.nextLine();
System.out.println("You wrote : "+str2);
Eran
  • 387,369
  • 54
  • 702
  • 768
1

Because this piece of code String str2 = sc.nextLine(); expecting the input by main thread. Until you enter something into the console, control won't go to the next line.

Raju Guduri
  • 1,237
  • 1
  • 13
  • 25
0

This is, how you want to implement it:

public class HelloWorld {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("Please write something : ");

        String str2 = sc.nextLine();

        System.out.println("You wrote : " + str2);
    }
}
i23
  • 508
  • 2
  • 12