0

Well , I am currenty learning Java. But for some reason I don't know why, it's not printng String strs.

If I input

42
3.1415
Welcome to HackerRank's Java tutorials!

I get this

String: 
Double: 3.1415
Int: 42

But the expected output is

String: Welcome o HackerRank's Java tutorials!
Double: 3.1415
Int: 42

Orginal code below


import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        double dr= sc.nextDouble();
        String strs = sc.nextLine();
       
        System.out.println("String: " + strs);
        System.out.println("Double: " + dr );
        System.out.println("Int: "+ a);

    }
}

about reopening ( for mods)


as I said, I am new to java and I am learing it. So i don't understand mostly of their code. They used something called option , try catch.... Still learning, so would you mind reopening the question?

  • @Mat sorry, let me correct my ques. I put in wrong order – Pronay Sarker Aug 17 '23 at 09:00
  • @Mat Hello Mat, sorry for bothering you. My question got marked as 'duplicate'. I viewed the original question and I don't understand most of their code. So, I was wondering, if you can explain what went wrong with my code in a easy way.... Would be grateful – Pronay Sarker Aug 17 '23 at 09:07
  • it is nicely explained in this answer from the linked Post: https://stackoverflow.com/a/7056782/9862795 in your example you should do the following: Scanner sc = new Scanner(System.in); int a = sc.nextInt(); double dr= sc.nextDouble(); sc.nextLine(); // to consume the 'next line' after the int/double value String strs = sc.nextLine(); – GoranLegenda Aug 17 '23 at 10:01
  • `nextInt()` and `nextDouble()` do not consume the newline token. so your `String strs = sc.nextLine()` actually scans `\nMyExpectedString\n` and stops after the first `\n`. which is why you need to place an extra `sc.nextLine()` to consume that before saving your expected string – tom Aug 17 '23 at 10:24
  • You shouldn't really mix `nextLine()` with `nextInt()`, `nextDouble()`, etc. If you plan to use `nextLine()` in your code then use it for everything. You should be using **`next()`** with those other *nextFoo()* calls but, make sure you are also using `Scanner sc = new Scanner(System.in).useDelimiter("\\R");` The regex string, `"\\R"`, matches any Unicode newline sequence. Normally the `next()` method is used to retrieve tokens (single words) but now it will retrieve anything up to the ENTER key hit which will be consumed. – DevilsHnd - 退職した Aug 17 '23 at 11:33

0 Answers0