不能使用ints并与JOption对话框求和

use*_*549 2 java string swing joptionpane

我正在使用Java:如何编程,第7版.问题是在第2章之后它不再给你答案.我从书中提出了一个应用程序,它从用户那里获得了2个整数,然后将它们一起添加并输出了一个printf显示消息(控制台应用程序).

现在本书要求我编辑该程序并使用JOption导入函数(即通过JOptionPane.showInputDialog("What is the first integer?");thingy 请求2个整数.我必须弹出一个对话框,询问2个整数,然后在最后显示总和messagebox.

这是我到目前为止所做的,花了一个小时试图修复错误无济于事(书中没有线索):

import javax.swing.JOptionPane;

public class Additions
{
   public static void main( String args[] )
   {
      String name1 = // return type string, pane asking for name
            JOptionPane.showInputDialog( "What is the first integer?" );

      String name2 = // return type string, pane asking for name
            JOptionPane.showInputDialog( "What is the second integer?" );

      sum = name + name2;

      String sum = String.format( "Sum is %d\n", sum );
   } 
} 
Run Code Online (Sandbox Code Playgroud)

nac*_*okk 5

您必须将该String转换为int.你可以用这种方法做到这一点.

String s =JOptionPane.showInputDialog( "What is the first integer?" );
int i = Integer.parseInt(s);
Run Code Online (Sandbox Code Playgroud)

请注意,如果输入不是int,那么NumberFormatException将抛出a.

读取api:Integer#parseInt(String)

所以在你的代码中会是这样的:

 String name1 =JOptionPane.showInputDialog( "What is the first integer?" );
 int first = Integer.parseInt(name1);
 String name2 =JOptionPane.showInputDialog( "What is the second integer?" );
 int second = Integer.parseInt(name2);
 String sum = String.format( "Sum is %d\n", first + second );
 JOptionPane.showMessageDialog(null,sum); // show output
Run Code Online (Sandbox Code Playgroud)