一、键盘录入
nextLine()与next()都可以录入字符串,但是两者存在差异
使用nextLine()
import java.util.Scanner;
public class Demo1{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int number1 = sc.nextInt();//录入一个int类型
float number2 = sc.nextFloat();//录入一个float类型
double number3 = sc.nextDouble();//录入一个double类型
sc.nextLine(); //使用这行清除上次残留的回车符
String number4 = sc.nextLine();//录入一个字符串类型
int number5 = sc.nextInt();
System.out.println(number1);//输出
System.out.println(number2);
System.out.println(number3);
System.out.println(number4);
System.out.println(number5);
}
}
使用next()
import java.util.Scanner;
public class Demo2{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int number1 = sc.nextInt();//
float number2 = sc.nextFloat();
double number3 = sc.nextDouble();
String number4 = sc.next();//使用next录入是不需要清除上次的回车
int number5 = sc.nextInt();
System.out.println(number1);
System.out.println(number2);
System.out.println(number3);
System.out.println(number4);
System.out.println(number5);
}
}
``
另外,如果使用next()录入字符串时,字符串是"ab c"时,第一次只会录入字符"ab","c"将录入不了。而使用nextLine()将不会存在这种情况。
二、随机数
例如:产生一个0-100的整数
public class Demo3{
public static void main(String[] args) {
System.out.println((int)(Math.random()*101)); //Math.random()是产生一个[0-1)的随机数
//ps:不要写成(int)Math.random()*101,这样结果将是0
}
}