java 念整数_JOptionPane和读取整数 - 初学者Java

这篇博客讨论了如何从用户那里接收月份、日期和年份输入,并在一个对话框中显示这些输入。博主首先展示了使用Scanner类从控制台读取用户输入的代码,然后检查输入的日期是否为'魔法数字',即月份乘以日期等于年份。接着,博主询问如何将输入过程转移到一个对话框中,给出了解决方案,通过JOptionPane的showInputDialog方法实现,并提供了转换用户输入为整数的步骤。
摘要由CSDN通过智能技术生成

I currently have code that reads the month, date, and year a user enters in one line (separated by spaces). Here is the code.

Scanner input = new Scanner(System.in);

int day = 0;

int month = 0;

int year = 0;

System.out.printf("enter the month, date, and year(a 2 numbered year). Put a space between the month, day, and year");

month = input.nextInt();

day = input.nextInt();

year = input.nextInt();

This works fine, the second part is to display a message, if month * day == year, then it is a magical number, if not, then it is not a magical number. It has to be displayed in a dialog box. here is my code for that, and it is working just fine.

if((day * month) == year)

{

String message = String.format("%s", "The date you entered is MAGIC!");//If the day * month equals the year, then it is a magic number

JOptionPane.showMessageDialog(null, message);

}

if((day * month) != year)

{

String message = String.format("%s", "The date you entered is NOT MAGIC!");//If the day * month does not equal the year, it is not a magic number

JOptionPane.showMessageDialog(null, message);

}

My question is!! How can I get a dialog box to take the inputs of the month, date, and year in one line the way it works in the console. I'm working in DrJava, and the chapter of the book I'm in doesn't help me with this specific use. Any help would be great. Thanks all!

解决方案

You can make use of following to take user input

String word = JOptionPane.showInputDialog("Enter 3 int values");

String[] vals = word.split("\\s+"); // split the sting by whitespaces accepts regex.

// vals[0] cast to int

// convert string representation of number into actual int value

int day = Integer.parseInt(vals[0]); // throws NumberFormatException

// vals[1] cast to int

// vals[2] cast to int

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值