1

I am trying to take string input in java using Scanner, but before that I am taking an integer input. Here is my code.

import java.util.*;

class prc
{
    public static void main(String[] args) 
    {
        Scanner input=new Scanner(System.in);
        int n=input.nextInt();
        for(int i=1;i<=n;i++)
        {
            String str=input.nextLine();

            System.out.println(str);
        }

    }
}

The problem is that if I give a number n first, then the number of string it is taking as inputs is n-1. e.g if the number 1 is entered first, then it is taking no string inputs and nothing is printed.

Why is this happening ? Thanks in Advance!

3
  • @MaxZoom: While that's better style, it won't affect the behavior of this program. Commented Apr 30, 2015 at 19:40
  • 1
    Try to change your for loop like for(int i=0;i<=n;i++) Commented Apr 30, 2015 at 19:46
  • 1
    @Neferseti BTW according java convention class name must start with Upper letter - Prc, at this case Commented Apr 30, 2015 at 19:50

3 Answers 3

5

nextLine() reads everything up to and including the next newline character.

However, nextInt() only reads the characters that make up the integer, and if the integer is the last (or only) text in the line, you'll be left with only the newline character.

Therefore, you'll get a blank line in the subsequent nextLine(). The solution is to call nextLine() once before the loop (and discard its result).

Sign up to request clarification or add additional context in comments.

Comments

1

Information regarding the code is mentioned in the comments written next to each line.

public static void main(String[] args) {
            int num1 = sc.nextInt();       //take int input
            double num2 = sc.nextDouble();    //take double input
            long num3 = sc.nextLong();      //take long input
            float num4 = sc.nextFloat();     //take float input
            sc.nextLine();      //next line will throw error if you don't use this line of code
            String str = sc.nextLine();      //take String input
    }

1 Comment

please add some description explaining solution.
0
import java.util.*;

class prc
{
    public static void main(String[] args) 
    {
        String strs[];
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        input.nextLine();

        strs = new String[n];
        for(int i = 1; i < n; i++)
        {
            strs[i] = input.nextLine();
            System.out.println(strs[i]);
        }

    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.