如何使用java实现,输入一个数字然后空格 再输入一个数字,最后回车键,得到两个数字的和?


普通版:可输入,可输出。带详细的注释

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import  java.util.Scanner;
 
public  class  SumDemo {
     public  static  void  main(String[] args) {
         System.out.println( "请输入两个数字,中间用空格隔开,例如5 5" );
         //得到一个扫描器,用来扫描 系统的输入
         Scanner input =  new  Scanner(System.in);
         //申明一个临时的字符串变量temp,用来保存 扫描器读取的一行;
         String temp = input.nextLine();
         //temp字符串首先trim()一下,就是去掉两边的空白,
         //因为有的人可能输入的是 空格5空格5空格回车。.
         //所以去掉两边的空格变成 5空格5回车 就符合要求了
         //split(" ")方法表示,用空格去切割字符串,返回的结果是一个字符串数组
         String[] ss = temp.trim().split( " " );
         //从两个字符串中解析得到两个数字,并求和
         int  num1 = Integer.parseInt(ss[ 0 ]);
         int  num2 = Integer.parseInt(ss[ 1 ]);
         int  sum = num1+num2;
         //输出结果
         System.out.println( "输入的数字是" +num1+ " " +num2+ "两数的和是:" +sum);
         //养成良好的习惯,打开了的资源要记得关闭,我们打开了扫描器,就要关闭扫描器
         input.close();
     }
}

效果

 

 

升级版:可重复输入数字,重复输出结果,并带退出功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import  java.util.Scanner;
 
public  class  SumTest {
     public  static  void  main(String[] args) {
         Scanner input =  new  Scanner(System.in);
         while ( true ){
             System.out.println( "如果输入exit,那么退出。输入两个数字,用空格隔开" );
             String temp = input.nextLine();
             if (temp.trim().equals( "exit" )){
                 break ;
             }
             String[] ss = temp.trim().split( " " );
             int  num1 = Integer.parseInt(ss[ 0 ]);
             int  num2 = Integer.parseInt(ss[ 1 ]);
             int  sum = num1+num2;
             System.out.println( "输入的数字是" +num1+ " " +num2+ "两数的和是:" +sum);
         }
         input.close();
     }
 
}

效果

 

 

 

 

转载: 如何使用java实现,输入一个数字然后空格 再输入一个数字,最后回车键,得到两个数字的和?_百度知道 (baidu.com)

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM