简体   繁体   English

从用户那里获取 6 位数字输入并将每个数字存储在 Java 中的单个数组中

[英]Take 6 digit input from user and store each digit in a single array in Java

I want to read in a 6 digit number eg 123456 using the scanner and store each digit in an array of digits.我想使用扫描仪读取 6 位数字,例如 123456,并将每个数字存储在数字数组中。

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.我需要数组为 int 类型,因为当我将序列中的奇数 (1+3+5) 相加并添加偶数 (2+4+6)(根据程序)然后我有一些条件告诉我要连接到最后的数字。

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);
    }
}

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.将每个字符转换为适当的 int 值并将其放入数组中。

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.) (另请注意,如果ch-'0'不适合您的目的,则有多种方法可以将 char 解析为 int。)

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.选择您想要的任何数据类型,并nextX()调用正确的nextX()方法。

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() .这听起来你应该要求一个字符串而不是一个数字(因为大概000000是有效的输入,但这不是一个真正的整数),所以你会使用next()

To check if it's 6 digits, there are many ways you can go.要检查它是否为 6 位数字,您可以使用多种方法。 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 eg hexadecimal digits, there's some utility methods in Character you can use instead:如果你想不那么以英语/西方为中心,或者你想添加对十六进制数字的支持,你可以使用 Character 中的一些实用方法:

if (digit == -1) throw new IllegalArgumentException("digit required");

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使用Math.log10检查正确的位数
  • 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用于输入123456照片

[1, 2, 3, 4, 5, 6]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM