1

I recently started using Java,and I need to start on a big project,but I'm getting weird issues in my code which looks like this:

    import java.util.Scanner;
public class Sifre {

    public static void main(String[] args) {
        Scanner unos = new Scanner(System.in);
        System.out.println("Unesite broj sifara:");
        int bsif = unos.nextInt();
        String sifre[] = new String [bsif];
        String imena[] = new String [bsif];
        int i,z;
        for (i = 0;i<bsif;i++)
        {
            System.out.println("Unesite sifru broj " + (i+1));
            sifre[i] = unos.nextLine();
        }
        for (z=0;z<bsif;z++)
        {
            System.out.println(sifre[z]);
        }
    }

}

Every time I run the code,It skips the first input step and continues to work normally even if the counter starts with more than 0.Here is the output,tell me what is wrong(I know the code isnt perfect,but its my first time posting after 3 months of Java)

> Unesite broj sifara:

>>3

>Unesite sifru broj 1

>Unesite sifru broj 2
>>first

>Unesite sifru broj 3
>>second
>
>first
>
>second
imulsion
  • 8,820
  • 20
  • 54
  • 84
Fokezy
  • 13
  • 3
  • Add `unos.nextLine();` before the loop and after this statement `int bsif = unos.nextInt();`. – Lion Nov 07 '12 at 17:53
  • You will find hell lot of questions for this issue on SO only, leave Google aside. – Rohit Jain Nov 07 '12 at 18:02
  • I knew this was a common issue,but it was hard for me to phrase my answer to get any results in a search engine – Fokezy Nov 07 '12 at 18:07
  • **Reason :** When you use `Scanner.nextInt()`, it does not consume the new line (or other delimiter) itself so the next token returned will typically be an empty string. Thus, you need to follow it with a `Scanner.nextLine()`. You can simply discard the result. – Lion Nov 07 '12 at 18:08
  • @Fokezy FYI, I ran this search on SO: `[java] +scanner +nextint +skip` and [got this result](http://stackoverflow.com/search?tab=relevance&q=[java]%20%2bscanner%20%2bnextint%20%2bskip) – assylias Nov 07 '12 at 18:15

1 Answers1

0

Add input.nextLine() after

int bsif = unos.nextInt();
nidhin
  • 6,661
  • 6
  • 32
  • 50