System类
成员变量:
static InputStream in;//标准输入流
static InputStream out;//标准输出流
static InputStream err;//标准错误输出流
Scanner类
包:java.util.Scannner
1.构造方法有多个
Scanner(System.in)
来自:
Scanner(InputStream source)
构造方法
构造一个新的 Scanner,它生成的值是从指定的输入流扫描的。
2.常用成员方法
public boolean hasNextXxx():判断是否是某种类型的元素
pubic Xxx nextXxx():获取该种类型的元素
从键盘获取String类型的数据
Scanner sc= new Scanner(System.in);
String s= sc.nextLine();
从键盘录入两个整数,并输出最大值
/*
从键盘录入两个整数,并输出最大值
*/
import java.util.Scanner;
class ScannerTwoNum{
public static void main(String[] args){
//创建键盘录入对象
Scanner sc= new Scanner(System.in);
//通过对象获取数据
//输入两个int型数
System.out.println("请输入第1个数字:");
int x=sc.nextInt();
System.out.println("请输入第2个数字:");
if(sc.hasNextInt()){
int y=sc.nextInt();
}
else{
System.out.println("你输入的数据非法!");
}
//输出最大值
System.out.println("Max is:"+( (x>y)?x:y));
}
}
定义一个方法,实现两数求和
/*
定义一个方法
实现两数求和
*/
import java.util.Scanner;
//main()
class FunctionSum{
public static void main(String[] args){
Scanner sc= new Scanner(System.in);
System.out.println("请输入需要求和的两个数:");
int x= sc.nextInt();
int y= sc.nextInt();
int result=sum(x,y);
System.out.println(result);
}
//自定义的方法:sum()
/*这里写的时候未加static,报错:int result=sum(x,y)的sum这,无法从静态上下文中引用非静态方法。
查了一下:静态的随着类的加载而加载,比对象存在早。非静态方法在对象创建时程序才会为其分配内存。
then通过对象去访问非静态方法。不能在静态里直接调用非静态。
在对象未存在时,非静态方法也不存在,所以这里静态方法main()自然不能调用一个不存在的sum()方法。
*/
public static int sum(int a, int b){
return a+b;
}
}
比较两个数是否相等
import java.util.Scanner;
class FunctionIsEqual{
public static void main(String[] args){
Scanner sc= new Scanner(System.in);
//输入两个数
int x= sc.nextInt();
int y= sc.nextInt();
System.out.println(isEqualInt(x,y));
}
public static boolean isEqualInt(int a, int b){
boolean flag= (a==b)? true:false;
return flag;
//改进:return (a==b)? true:false;
//最终版:return a==b;
}
}