gpt4 book ai didi

java - 对话框中给出的出生日期的数字总和

转载 作者:行者123 更新时间:2023-11-30 02:22:50 26 4
gpt4 key购买 nike

这个问题的要点是打开一个对话框,让它以 yyyy 格式询问您的姓名和出生日期;然后给您出生日期数字的总和。例如,如果您出生于1999年,程序将输出“X:您的出生日期的位数之和为28”。

这是我当前的代码。我被困在计算数字总和的部分。

import javax.swing.JOptionPane;
import java.util.Scanner;

public class Age {
public static void main(String[] args) {
String name;
String inputString;
int age;

name = JOptionPane.showInputDialog("What is " + "your name");
inputString = JOptionPane.showInputDialog("Enter the year " + "of your birth in yyyy format");

//this is where the calculations will go//

JOptionPane.showMessageDialog(null, "Hello " + name + " your age is" + inputString);
System.exit(0);
}
}

最佳答案

使用 Java 8 实现此目的的另一种方法是:

inputString.chars()                             // get a stream of int with the char code point values
.mapToObj(c -> (char) c) // convert each element to its char representation
.mapToInt(Character::getNumericValue) // convert each char to int
.sum(); // sum all elements in the stream

我还建议验证输入以避免异常。您可以使用正则表达式,例如:

if(inputString.matches("\\d{4}")){
// do your sum
}else{
// warn the user
}

关于java - 对话框中给出的出生日期的数字总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46372682/

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