0

I want to read in a 6 digit number e.g 123456 using the scanner and store each digit in an array of digits.

System.out.println("Please enter a 6 digit code");
int code = keyboard.nextInt();

And then somehow put that into:

int [] array = {1,2,3,4,5,6};

I need the array to be int type because I am going to find the product when I add together the odd numbers in the sequence (1+3+5) and add the even numbers (2+4+6) (as per specifications of the program) I then have some conditions that tell me which number to concatenate onto the end.

I can achieve this by pre-defining an array of numbers but I want this number to come from the user.

Unless there is another way of doing this without using arrays? I appreciate any pointers.

Here is my code when i have pre-defined the array and it's values.

        int code[] = {1,2,3,4,5,6};



        //add the numbers in odd positions together
        int sum_odd_position = 0;
        for (int i=0; i<6; i+=2)
        {
            sum_odd_position += code[i];
        }


        //convert the initial code into strings
        String string_code = "";
        String seven_digit_code = "";

        //add numbers in even positions together
        int sum_even_position=0;

        for (int i=1; i<6; i+=2)
        {
            sum_even_position += code [i];
        }

        //add them both together
        int sum_odd_plus_even = sum_odd_position + sum_even_position;

        //calculate remainder by doing our answer mod 10
        int remainder = sum_odd_plus_even % 10;
        System.out.println("remainder = "+remainder);


        //append digit onto result
        if (remainder==0) {
            //add a 0 onto the end
            for (int i=0; i<6; i+=2)
            {
                string_code += code [i];
            }

        }
        else {
            //subtract remainder from 10 to derive the check digit
            int check_digit = (10 - remainder);
            //concatenate digits of array
            for (int i=0; i<6; i++)
            {
                string_code += code[i];
            }
            //append check digit to string code

        }
        seven_digit_code = string_code + remainder;
        System.out.println(seven_digit_code);
    }
}
U Kushi
  • 17
  • 1
  • 5

3 Answers3

2

Start by reading in a string from the user. Create an array to put the digits into. Iterate through the string character by character. Convert each character to the appropriate int value and put it into the array.

String line = keyboard.nextLine();
int[] digits = new int[line.length()];
for (int i = 0; i < digits.length; ++i) {
    char ch = line.charAt(i);
    if (ch < '0' || ch > '9') {
        throw new IllegalArgumentException("You were supposed to input decimal digits.");
    }
    digits[i] = ch - '0';
}

(Note also that there are various ways to parse a char as an int if ch-'0' does not suit your purposes.)

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 1
    getNumericValue is problematic here. For example, `Character.getNumericValue('௰')` is `10`, and presumably OPs app is not designed to handle that. `.digit(x, 10)` is guaranteed to return a value in the `0-9` range, or `-1` if the provided character isn't representative of a digit in that range. Note that `Character.digit('೬', 10)` still works (returns 6), and `Character.digit('௰', 10)` returns what you want (-1 instead of 10). `.digit('A', 0x10)` also works whereas getNumericValue would not, but that's less relevant here. – rzwitserloot Oct 28 '20 at 21:50
  • 1
    I see you have now edited it to switch back to 80s style 'unicode, what is that?' - that seems... a bit backward, no? There are other number systems than arabic. – rzwitserloot Oct 28 '20 at 21:52
  • 1
    @rzwitserloot If `Character.getNumericValue` is too permissive, I'll go back to what I know would work, which is `ch - '0'`. I'm pretty sure that fits the OP's actual use case. – khelwood Oct 28 '20 at 21:52
  • @khelwood Java automatically casts `char`s to `int`s when necessary. OP could simply write `digits[i] = ch;` – Aharon K Oct 28 '20 at 22:43
  • @AharonK That is not equivalent. If you cast `'0'` to an int you get 48, not zero. – khelwood Oct 28 '20 at 22:45
  • That's true, my mistake. I am still learning. I was thinking of casting an ascii `int` to a `char` – Aharon K Oct 28 '20 at 22:46
1

To send messages to the user:

System.out.println("Hello, please enter a 6 digit number: ");

To ask for input, make a scanner once and set the delimiter:

// do this once for the entire app
Scanner s = new Scanner(System.in);
s.useDelimiter("\r?\n");

Then to ask for stuff:

int nextInt = s.nextInt();
String nextString = s.next();

Pick whatever data type you want, and call the right nextX() method for this.

This sounds like you should be asking for a string and not a number (Because presumably 000000 is valid input, but that isn't really an integer), so you'd use next().

To check if it's 6 digits, there are many ways you can go. Presumably you need to turn that into an array anyway, so why not just loop through every character:

String in = s.next();
if (in.length() != 6) throw new IllegalArgumentException("6 digits required");

int[] digits = new int[6];
for (int i = 0; i < 6; i++) {
    char c = in.charAt(i); // get character at position i
    int digit = Character.digit(c, 10); // turn into digit
    if (digit == -1) throw new IllegalArgumentException("digit required at pos " + i);
    digits[i] = digit;
}

If you want to be less english/western-centric, or you want to add support for e.g. hexadecimal digits, there's some utility methods in Character you can use instead:

if (digit == -1) throw new IllegalArgumentException("digit required");
rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
1

First, allocate a scanner and an array for the digits

Scanner input = new Scanner(System.in);
int[] digits = new int[6];
  • Prompt for the integer.
  • Use Math.log10 to check for proper number of digits
  • otherwise, re-prompt
  • then using division and remainder operators, fill array with digits. Filling is done in reverse to maintain order.
for (;;) {
    System.out.print("Please enter six digit integer: ");
    int val = input.nextInt();
    // a little math.  Get the exponent of the number
    // and assign to an int. This will determine the number of digits.
    if ((int) Math.log10(val) != 5) {
        System.out
                .println(val + " is not six digits in size.");
        continue;
    }
    for (int i = 5; i >= 0; i--) {
        digits[i] = val % 10;
        val /= 10;
    }
    break;
}

System.out.println(Arrays.toString(digits));

For input of 123456 Prints

[1, 2, 3, 4, 5, 6]
WJS
  • 36,363
  • 4
  • 24
  • 39