java - 如何将用户输入的数字(学生 ID)拆分为公式

标签 java for-loop while-loop

我在使用分配给我的这个初学者 Java 程序时遇到了麻烦,我是 Java 的新手,而且我在使用这个特定程序时遇到了很多麻烦。这些是说明:

Your program should prompt users to enter an n-digit number as a student ID, and then display the validity of the entered ID. You can assume n will be in the range of 6 and 10 inclusive. The checksum digit is part of student ID. Your algorithm is to match the rightmost digit in the entered ID with the computed checksum digit. If there is no match, then your program shall report the entered ID being invalid. For example, the entered ID 1234567 is invalid because the computed 7th digit is 1 (= (1 * (digit1) + 2 * (digit 2) + 3 * (digit 3) + 4 * (digit 4) + 5 * (digit 5) + 6 * (digit 6)) % 10) and is different from the actual 7th digit which is 7. However, if the entered ID is 1234561 your program shall display a message of acceptance.

我要做的第一步是从用户输入中读取每个没有空格的数字,就好像它有空格一样。然后,我试图将这些数字中的每一个分配给数字 1、数字 2 等变量以进行计算。

import java.util.Scanner;
public class H4_Ruby{
public static void main(String[] args){
// this code scans the the user input 
  Scanner scan = new Scanner(System.in);
  System.out.println("Please enter a student ID between 6-10 digits");
  String nums = scan.nextLine(); 
  String[] studentIdArray = nums.split(" ");
  int[] studentID = new int [studentIdArray.length];



  for (int i = 0; i < studentIdArray.length; i++) 
  { 
     studentID[i]= Integer.parseInt(studentIdArray[i]);
     System.out.print(studentID[i] + ",");
  }
}

到目前为止,这是我的代码......

最佳答案

您不能通过 nums.split("") 拆分来获得 String 数组。您已经从用户那里得到了一个没有空格的 String Id。

因此遍历 String 并继续计算乘积的总和/强>像下面。我在代码本身中添加了注释

public static void main(String[] args) {
    // this code scans the the user input
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter a student ID between 6-10 digits");
    String nums = scan.nextLine();

    int multiplier = 1, totalProductSum = 0;
    for (int i = 0; i < nums.length() - 1; i++) {

        // if the character is not digit, its not a valid id
        if (!Character.isDigit(nums.charAt(i))) {
            System.out.println("Invaild Id");
            return;
        }

        // maintain the sum of products and increment the multiplier everytime
        totalProductSum += (multiplier * (nums.charAt(i) - '0'));
        multiplier++;
    }

    // the condition for validity i.e totalProduct sum mod 10 and last digit in input Id
    if ((totalProductSum % 10) == (nums.charAt(nums.length() - 1) - '0'))
        System.out.println("Valid Id");
    else
        System.out.println("Invaild Id");
}

关于java - 如何将用户输入的数字(学生 ID)拆分为公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51237695/

相关文章:

javascript - 在循环开始时设置一次变量

c - 为什么 scanf 在这里跳过输入?

Java日期时间戳转换问题

java - 我可以在java中显式调用接口(interface)方法吗?如果没有那么有解决方法吗?

c - C 奇怪形式的 For 循环语法

arrays - 比较字符串和数组

php - 使用 php 问题删除 mysql 上的一行

c - Do While 循环的一个小问题

Java ExecutorService 仅运行 2 个线程而不是 4 个

java - Maven 尝试从 Maven Central 获取 shrinkwrap-bom,而不是配置的存储库