JOptionPane和读取整数 - 初学者Java [英] JOptionPane and reading integers - Beginner Java

查看:701
本文介绍了JOptionPane和读取整数 - 初学者Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有代码,用于读取用户在一行中输入的月份,日期和年份(以空格分隔)。这是代码。

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

我的问题是!!如何获得一个对话框,以在控制台中的工作方式将一个月,日期和年份的输入作为一行。我在DrJava工作,我所在的那一章对这个具体用途没有帮助。任何帮助都会很棒。谢谢大家!

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

拆分Java API

parseInt Java API

Java Regex教程

这篇关于JOptionPane和读取整数 - 初学者Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆