[转]java实现,输入数据,空格继续,回车结束输入

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

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

 

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

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

 

来源于百度知道

https://zhidao.baidu.com/question/367772921046984684.html

转载于:https://www.cnblogs.com/mayj/p/7104940.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值