-2

I want to solve this java problem. but i did not proper answer form my code. Below here is my code:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    int x = sc.nextInt();
    double y = sc.nextDouble();
    String s = sc.nextLine();

    System.out.println("Int: " + x);
    System.out.println("Double: " + y);
    System.out.println("String: " + s);
}

When I take input int, double and string variable, I can't proper answer. below this code's is input and output:

input: 
23
4434.2323

Give output: 
Int: 23
Double: 4434.2323
String: 

At the input time, i can take int, double variable but i can't take string input. my code return int and double variable. If can anybody help me, I will be benefited.

mdshohed
  • 5
  • 3
  • 6
    `next` only reads a token (up until a space, a _word_), use `nextLine` instead. And then be prepared for this https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo – Zabuzard Feb 23 '21 at 13:25
  • Do not use nextLine - it is common, but very bad advice (it breaks, see the first comment with 'but be prepared for'). No, the right fix is to set up your delimiter properly: call `scanner.useDelimiter("\r?\n")` on your scanner right after making it, forget about nextLine, and use next() to grab strings. – rzwitserloot Feb 23 '21 at 13:38

1 Answers1

-1

Yes because sc.next() goes till the end of the word (eg. space).

Use instead sc.nextLine()

Read the util.Scanner documentation

But best practice would be to set a delimiter and keep using sc.next().

String delimiter = " some_delimiter_here "; \\e.g. "\n"
Scanner sc = new Scanner(System.in);
sc.useDelimiter(delimiter);
Aristotle
  • 545
  • 4
  • 15
  • Sorry, It didn't give proper Answer. – mdshohed Feb 23 '21 at 13:36
  • What do you mean by "It didn't give the proper answer"? I didn't give you an algorithm with a right or wrong answer. I suggested what you can use... – Aristotle Feb 23 '21 at 15:00
  • Input: 42 3.1415 Welcome to Java tutorials! Output: String: Welcome to Java tutorials! Double: 3.1415 Int: 42 Please give me a source code of java language which take input and give output same above. And kindly see again my question. – mdshohed Feb 23 '21 at 15:18