在我之前刚接触java时,就打算将代码和想法挑选一些经典的记录到博客。
所以这次算是我第一次在掘金发布博客。
import java.util.Scanner;//在程序首部导入Scanner类,用外部设备为变量赋值
public class DiYiGe { //类名为DiYiGe
public static void main(String[] args) {//头文件
Scanner sr=new Scanner(System.in);
int x,y;
System.out.print("请输入第一个数值:");
x=sr.nextInt();
System.out.print("请输入第二个数值:");
y=sr.nextInt();
System.out.println(x+"+"+y+"="+(x+y));
}
}
在这段代码中:
- 第一句是为了接下来用外部设备为变量赋值而导入的Scanner类;
- “public class DiYiGe”中的“DiYiGe”是我给类的命名;
- 第四句中的“sr”是我定义的变量;
- 第四句意思为通过new Scanner(System.in)创建一个Scanner,控制台会一直等待输入,直到敲回车键结束,把所输入的内容传给Scanner。
- 如果要获取输入的内容,则只需要调用Scanner的nextLine()方法,我这里用的是nextInt()。
补充: nextInt()和nextLine()方法的官方文档
nextLine()
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
nextInt()方法会读取下一个int型标志的token.但是焦点不会移动到下一行,仍然处在这一行上。当使用nextLine()方法时会读取该行剩余的所有的内容,包括换行符,然后把焦点移动到下一行的开头。所以这样就无法接收到下一行输入的String类型的变量。