TransWikia.com

Why am I not getting the correct output in ques of printing even and odd index character seperatly?

Stack Overflow Asked on February 28, 2021

enter link description here

This is the link to the question. I have written this code in java but I am not getting the correct output.Why?

Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for(int i=0; i<n; i++)
        {
            String name = sc.nextLine();
            String even="";
            String odd ="";
            for(int j=0; j<name.length(); j++)
            {
                if(j%2==0)
                    even=even+String.valueOf(name.charAt(j));
                else
                    odd=odd+String.valueOf(name.charAt(j));
            }
            System.out.println(even+" "+odd);

This is the error I am getting.

Input (stdin)
    2
    Hacker
    Rank

Your Output (stdout)

    // a blank space here.
    Hce akr

Expected Output

    Hce akr
    Rn ak

    

2 Answers

Your int n = sc.nextInt(); consumes the integer that's input (2), but there is a still a newline.

When your loop goes through the first time, and you call String name = sc.nextLine();, it will consume that remaining newline (and nothing else). Hence, your blank line.

To get past that, make sure to read in the new line after you read in n

Also, the last entry isn't shown because you likely need a trailing newline (one after "Rank" in your input)

Correct answer by Gryphon on February 28, 2021

your code is correct but the problem is in your input taking. if u take this as a input 2 Hacker Rank then your excepted output never come as u mentioned in your question. Now i tell u in brief about where is the problem:---------

int n = sc.nextInt(); here u take integer input 2 but you delare only one string type variable.u must declare 2string typr variable if u choose 2. otherwise only 1 tring willl be handled .

Hacker Rank thatswhy u take 2 string variable bt according to ur code only hacker will be compiled and give the output. u declare 2 string variable .

Answered by Prashant__Anand on February 28, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP