Search code examples
javaarraysfor-loopzipcode

The first position of my array isn't being modified


I'm creating an application that converts a 5 digit zip code into frame bars. Weirdly, the first digit entered doesn't correctly go through the conversion. Here's the code:

import java.util.*;
import java.lang.*;
import java.io.*;
class Zip{

    public static String checkDigit(String bar)
    {
        Scanner s = new Scanner(System.in);
        int [] input;
        input = new int [4];
        for(int p = 0; p < 4; p++)
        {
            input[p] = s.nextInt();
            if (input[p] == 0)
            {
                bar = bar + "||:::";
            }
            if (input[p] == 1)
            {
                bar = bar + ":::||";
            }
        }
        System.out.println();
        return bar;
    }

    public static void main (String[] args) {   
        Scanner s = new Scanner(System.in);
        System.out.println(checkDigit(s.nextLine())); 
    }
}

For example, when entering 1, 0, 0, 0, 0 into the array, the output is

"1||:::||:::||:::||:::"

When entering 0, 1, 1, 1, 1 into the array, the output is

"0:::||:::||:::||:::||"

Instead of converting the first digit at pos [0], it just prints the number outright. Why is this?


Solution

  • It is because of s.nextLine() it will read the first int entered in console and save it in String bar passing into checkDigit()

    Scanner s = new Scanner(System.in);
        System.out.println(checkDigit(s.nextLine())); 
    

    Pass an empty string

    Scanner s = new Scanner(System.in);
        System.out.println(checkDigit("")); 
    

    Input : 0 1 1 1

    Output : ||::::::||:::||:::||