gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:08:04 24 4
gpt4 key购买 nike

我在使用分配给我的这个初学者 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com