java 基础练习 a+b

创建文件addab.java

导入java.util.Scanner包说一下这个有什么用:

java.util.Scanner 是 Java5 的新特征,可以通过 Scanner 类来获取用户的输入。

Scanner类的创建对象:     Scanner  scan=new Scanner(System.in);    

方法的基本格式

 hasNextXxx()  判断是否还有下一个输入项,其中Xxx可以是Int,Double等。如果需要判断是否包含下一个字符串,则可以省略Xxx

 scan.hasnextInt()  获取下一个输入项。Xxx的含义和上个方法中的Xxx相同。


scan对象调用下列方法(函数),读取用户在命令行输入的各种数据类型:  

next.Byte(),nextDouble(),nextFloat,nextInt(),nextLine(),nextLong(),nextShot()。

通过 Scanner 类的 next() 与 nextLine() 方法获取输入的字符串,在读取前我们一般需要 使用 hasNext 与 hasNextLine 判断是否还有输入的数据:
a+b实现代码:

import java.util.Scanner;
public class addab {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        while (scan.hasNextInt()) {
            int a = scan.nextInt();
            int b = scan.nextInt();
            int result = add(a,b);
            System.out.println(result);
        }
        scan.close();
    }
    public static int add(int a, int b) {
        return a+b;
    }
}

posted on 2022-12-31 18:27  skywide  阅读(7)  评论(0)    收藏  举报  来源