1.用消息框显示加法计算结果
package plusdialog;
import javax.swing.JOptionPane; // import class JOptionPane
public class Addition {
public static void main( String args[] )
{
String firstNumber, // first string entered by user 定义第一二个变量
secondNumber; // second string entered by user
int number1, // first number to add //用来字符串数字和整型转化的
number2, // second number to add
sum; // sum of number1 and number2
// read in first number from user as a string
firstNumber =
JOptionPane.showInputDialog( "Enter first integer" );
// read in second number from user as a string
secondNumber =
JOptionPane.showInputDialog( "Enter second integer" );
// convert numbers from type String to type int
number1 = Integer.parseInt( firstNumber ); //字符串数字转化为int类型
number2 = Integer.parseInt( secondNumber );
// add the numbers
sum = number1 + number2;
// display the results
JOptionPane.showMessageDialog(
null, "The sum is " + sum, "Results",
JOptionPane.PLAIN_MESSAGE );
System.exit( 0 ); // terminate the program
}
}
最后会以消息框的形式输出结果。
firstNumber =
JOptionPane.showInputDialog( "Enter first integer" );
用这个来用消息框从键盘读取字符串,
number1 = Integer.parseInt( firstNumber ); //字符串数字转化为int类型
2.变量的作用域
每个变量都有一个“有效”的区域(称为“作用域”),出了这个区域,变量将不再有效。Java变量遵循“同名变量的屏蔽原则”。
3.在运行时读取用户输入。
使用Scanner类 ,imports java.util.*;
Scanner in=new Scanner(System.in);
System.out.print(“What is your name?”);
String name=in. nextLine();
Scanner类有nextInt,nextDouble等方法。
/**
@version 1.10 2004-02-10
@author Cay Horstmann
*/
import java.util.*;
public class InputTest
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
// get first input
System.out.print("What is your name? ");
String name = in.nextLine();
// get second input
System.out.print("How old are you? ");
int age = in.nextInt();
/* int i;
String value="100";
i=Integer.parseInt(value);
i=200;
String s=String.valueOf(i);*/
// display output on console
System.out.println("Hello, " + name + ". Next year, you'll be " + (age + 1));
}
}
4.使用double类型的数值进行计算, 其结果是不精确的。